repo_name
stringlengths
6
130
hexsha
sequence
file_path
sequence
code
sequence
apis
sequence
possible_versions
list
mvinyard/vintools
[ "496889c8a89a41cc481b6903453de23bd4a50500" ]
[ "vintools/_utilities/_system_utils/_get_pypi_package_loc.py" ]
[ "import os\nimport string\nimport numpy as np\nimport pandas as pd\n\n\ndef _get_pypi_package_loc(package=\"vintools\"):\n\n \"\"\"\"\"\"\n\n signature = \"\".join(np.random.choice(list(string.ascii_lowercase), 6))\n tmp_info_file = \"info_{}.txt\".format(signature)\n\n os.system(\"pip show {} > {}\".format(package, tmp_info_file))\n df = pd.read_table(tmp_info_file, sep=\": \", engine=\"python\")\n package_loc = df.loc[df.Name == \"Location\"].vintools.values.astype(str)[0]\n os.remove(tmp_info_file)\n\n return package_loc\n" ]
[ [ "pandas.read_table" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Liuhongzhi2018/ClassNet
[ "7d427dc9b8c38abf0a4eedfdeb75c09c59aa7185" ]
[ "baseline/core/model_vgg13.py" ]
[ "from torch import nn\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable\r\nfrom core import resnet, densenet, resnext, vgg\r\nimport numpy as np\r\nfrom core.anchors import generate_default_anchor_maps, hard_nms\r\nfrom config import CAT_NUM, PROPOSAL_NUM\r\n\r\n\r\nclass ProposalNet(nn.Module):\r\n def __init__(self, in_features=2048):\r\n super(ProposalNet, self).__init__()\r\n # self.down1 = nn.Conv2d(2048, 128, 3, 1, 1)\r\n self.down1 = nn.Conv2d(512, 128, 3, 1, 1)\r\n\r\n self.down2 = nn.Conv2d(128, 128, 3, 2, 1)\r\n self.down3 = nn.Conv2d(128, 128, 3, 2, 1)\r\n self.ReLU = nn.ReLU()\r\n self.tidy1 = nn.Conv2d(128, 6, 1, 1, 0)\r\n self.tidy2 = nn.Conv2d(128, 6, 1, 1, 0)\r\n self.tidy3 = nn.Conv2d(128, 9, 1, 1, 0)\r\n\r\n def forward(self, x):\r\n batch_size = x.size(0)\r\n d1 = self.ReLU(self.down1(x))\r\n d2 = self.ReLU(self.down2(d1))\r\n d3 = self.ReLU(self.down3(d2))\r\n t1 = self.tidy1(d1).view(batch_size, -1)\r\n t2 = self.tidy2(d2).view(batch_size, -1)\r\n t3 = self.tidy3(d3).view(batch_size, -1)\r\n return torch.cat((t1, t2, t3), dim=1)\r\n\r\n\r\nclass attention_net(nn.Module):\r\n def __init__(self, topN=4, classNum=200):\r\n super(attention_net, self).__init__()\r\n # self.pretrained_model = resnet.resnet50(pretrained=True)\r\n # self.pretrained_model = resnext.resnet18(pretrained=True,num_classes=classNum)\r\n # self.pretrained_model = resnext.resnet34(pretrained=True,num_classes=classNum)\r\n # self.pretrained_model = resnet.resnet152(pretrained=True)\r\n # self.pretrained_model = resnet.resnet101(pretrained=True)\r\n # self.pretrained_model = densenet.densenet121(pretrained=False,num_classes=classNum)\r\n # self.pretrained_model = densenet.densenet169(pretrained=True,num_classes=classNum)\r\n # self.pretrained_model = densenet.densenet161(pretrained=True,num_classes=classNum)\r\n # self.pretrained_model = resnext.resnext101_32x8d(pretrained=True,num_classes=classNum)\r\n # self.pretrained_model = resnext.wide_resnet101_2(pretrained=True,num_classes=classNum)\r\n # self.pretrained_model.avgpool = nn.AdaptiveAvgPool2d(1)\r\n # print(\"classNum: \",classNum) # classNum: 20 Fish\r\n self.pretrained_model = vgg.vgg13(pretrained=True,num_classes=classNum)\r\n # num_ftrs = self.pretrained_model.classifier.in_features\r\n # self.pretrained_model.fc = nn.Linear(num_ftrs, classNum)\r\n # self.pretrained_model.fc = nn.Linear(512 * 4, classNum)\r\n\r\n self.proposal_net = ProposalNet()\r\n self.topN = topN\r\n self.concat_net = nn.Linear(125440, classNum)\r\n self.partcls_net = nn.Linear(25088, classNum)\r\n _, edge_anchors, _ = generate_default_anchor_maps()\r\n self.pad_side = 224\r\n self.edge_anchors = (edge_anchors + 224).astype(np.int)\r\n\r\n def forward(self, x):\r\n resnet_out, rpn_feature, feature = self.pretrained_model(x)\r\n # print(\"resnet_out {} rpn_feature {} feature {}\".format(resnet_out.shape, rpn_feature.shape, feature.shape))\r\n # resnet_out torch.Size([3, 1000]) \r\n # rpn_feature torch.Size([3, 1024, 14, 14]) feature torch.Size([3, 1024])\r\n\r\n x_pad = F.pad(x, (self.pad_side, self.pad_side, self.pad_side, self.pad_side), mode='constant', value=0)\r\n batch = x.size(0)\r\n # we will reshape rpn to shape: batch * nb_anchor\r\n rpn_score = self.proposal_net(rpn_feature.detach())\r\n all_cdds = [\r\n np.concatenate((x.reshape(-1, 1), self.edge_anchors.copy(), np.arange(0, len(x)).reshape(-1, 1)), axis=1)\r\n for x in rpn_score.data.cpu().numpy()]\r\n top_n_cdds = [hard_nms(x, topn=self.topN, iou_thresh=0.25) for x in all_cdds]\r\n top_n_cdds = np.array(top_n_cdds)\r\n top_n_index = top_n_cdds[:, :, -1].astype(np.int)\r\n top_n_index = torch.from_numpy(top_n_index).cuda()\r\n top_n_prob = torch.gather(rpn_score, dim=1, index=top_n_index)\r\n part_imgs = torch.zeros([batch, self.topN, 3, 224, 224]).cuda()\r\n for i in range(batch):\r\n for j in range(self.topN):\r\n [y0, x0, y1, x1] = top_n_cdds[i][j, 1:5].astype(np.int)\r\n part_imgs[i:i + 1, j] = F.interpolate(x_pad[i:i + 1, :, y0:y1, x0:x1], size=(224, 224), mode='bilinear',\r\n align_corners=True)\r\n part_imgs = part_imgs.view(batch * self.topN, 3, 224, 224)\r\n _, _, part_features = self.pretrained_model(part_imgs.detach())\r\n part_feature = part_features.view(batch, self.topN, -1)\r\n part_feature = part_feature[:, :CAT_NUM, ...].contiguous()\r\n part_feature = part_feature.view(batch, -1)\r\n # concat_logits have the shape: B*200\r\n # print(\"part_feature {}\".format(part_feature.shape))\r\n concat_out = torch.cat([part_feature, feature], dim=1)\r\n concat_logits = self.concat_net(concat_out)\r\n raw_logits = resnet_out\r\n # part_logits have the shape: B*N*200\r\n part_logits = self.partcls_net(part_features).view(batch, self.topN, -1)\r\n return [raw_logits, concat_logits, part_logits, top_n_index, top_n_prob]\r\n\r\n\r\ndef list_loss(logits, targets):\r\n temp = F.log_softmax(logits, -1)\r\n loss = [-temp[i][targets[i].item()] for i in range(logits.size(0))]\r\n return torch.stack(loss)\r\n\r\n\r\ndef ranking_loss(score, targets, proposal_num=PROPOSAL_NUM):\r\n loss = Variable(torch.zeros(1).cuda())\r\n batch_size = score.size(0)\r\n for i in range(proposal_num):\r\n targets_p = (targets > targets[:, i].unsqueeze(1)).type(torch.cuda.FloatTensor)\r\n pivot = score[:, i].unsqueeze(1)\r\n loss_p = (1 - pivot + score) * targets_p\r\n loss_p = torch.sum(F.relu(loss_p))\r\n loss += loss_p\r\n return loss / batch_size\r\n" ]
[ [ "torch.nn.functional.log_softmax", "torch.cat", "torch.zeros", "torch.nn.Conv2d", "torch.gather", "torch.from_numpy", "torch.nn.Linear", "torch.nn.functional.relu", "torch.nn.functional.interpolate", "torch.stack", "torch.nn.ReLU", "numpy.array", "torch.nn.functional.pad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zhouxiaoxu/pytorch-retinanet
[ "72013ee0f46d2da08dd141f143a7a094477aa5e4" ]
[ "retinanet/anchors.py" ]
[ "import numpy as np\nimport torch\nimport torch.nn as nn\n\n\nclass Anchors(nn.Module):\n def __init__(self, pyramid_levels=None, strides=None, sizes=None, ratios=None, scales=None):\n super(Anchors, self).__init__()\n\n if pyramid_levels is None:\n self.pyramid_levels = [3, 4, 5, 6, 7]\n if strides is None:\n self.strides = [2 ** x for x in self.pyramid_levels]\n if sizes is None:\n self.sizes = [2 ** (x + 2) for x in self.pyramid_levels]\n if ratios is None:\n self.ratios = np.array([0.5, 1, 2])\n if scales is None:\n self.scales = np.array([2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)])\n\n def forward(self, image):\n \n image_shape = image.shape[2:] # 取得输入图片的长宽\n image_shape = np.array(image_shape)\n image_shapes = [(image_shape + 2 ** x - 1) // (2 ** x) for x in self.pyramid_levels]\n\n # compute anchors over all pyramid levels\n all_anchors = np.zeros((0, 4)).astype(np.float32)\n\n for idx, p in enumerate(self.pyramid_levels):\n anchors = generate_anchors(base_size=self.sizes[idx], ratios=self.ratios, scales=self.scales)\n shifted_anchors = shift(image_shapes[idx], self.strides[idx], anchors)\n all_anchors = np.append(all_anchors, shifted_anchors, axis=0)\n\n all_anchors = np.expand_dims(all_anchors, axis=0)\n\n if torch.cuda.is_available():\n return torch.from_numpy(all_anchors.astype(np.float32)).cuda()\n else:\n return torch.from_numpy(all_anchors.astype(np.float32))\n\ndef generate_anchors(base_size=16, ratios=None, scales=None):\n \"\"\"\n Generate anchor (reference) windows by enumerating aspect ratios X\n scales w.r.t. a reference window.\n \"\"\"\n\n if ratios is None:\n ratios = np.array([0.5, 1, 2])\n\n if scales is None:\n scales = np.array([2 ** 0, 2 ** (1.0 / 3.0), 2 ** (2.0 / 3.0)])\n\n num_anchors = len(ratios) * len(scales)\n\n # initialize output anchors\n anchors = np.zeros((num_anchors, 4))\n\n # scale base_size\n anchors[:, 2:] = base_size * np.tile(scales, (2, len(ratios))).T\n\n # compute areas of anchors\n areas = anchors[:, 2] * anchors[:, 3]\n\n # correct for ratios\n anchors[:, 2] = np.sqrt(areas / np.repeat(ratios, len(scales)))\n anchors[:, 3] = anchors[:, 2] * np.repeat(ratios, len(scales))\n\n # transform from (x_ctr, y_ctr, w, h) -> (x1, y1, x2, y2)\n anchors[:, 0::2] -= np.tile(anchors[:, 2] * 0.5, (2, 1)).T\n anchors[:, 1::2] -= np.tile(anchors[:, 3] * 0.5, (2, 1)).T\n\n return anchors\n\ndef compute_shape(image_shape, pyramid_levels):\n \"\"\"Compute shapes based on pyramid levels.\n\n :param image_shape:\n :param pyramid_levels:\n :return:\n \"\"\"\n image_shape = np.array(image_shape[:2])\n image_shapes = [(image_shape + 2 ** x - 1) // (2 ** x) for x in pyramid_levels]\n return image_shapes\n\n\ndef anchors_for_shape(\n image_shape,\n pyramid_levels=None,\n ratios=None,\n scales=None,\n strides=None,\n sizes=None,\n shapes_callback=None,\n):\n\n image_shapes = compute_shape(image_shape, pyramid_levels)\n\n # compute anchors over all pyramid levels\n all_anchors = np.zeros((0, 4))\n for idx, p in enumerate(pyramid_levels):\n anchors = generate_anchors(base_size=sizes[idx], ratios=ratios, scales=scales)\n shifted_anchors = shift(image_shapes[idx], strides[idx], anchors)\n all_anchors = np.append(all_anchors, shifted_anchors, axis=0)\n\n return all_anchors\n\n\ndef shift(shape, stride, anchors):\n shift_x = (np.arange(0, shape[1]) + 0.5) * stride\n shift_y = (np.arange(0, shape[0]) + 0.5) * stride\n\n shift_x, shift_y = np.meshgrid(shift_x, shift_y)\n\n shifts = np.vstack((\n shift_x.ravel(), shift_y.ravel(),\n shift_x.ravel(), shift_y.ravel()\n )).transpose()\n\n # add A anchors (1, A, 4) to\n # cell K shifts (K, 1, 4) to get\n # shift anchors (K, A, 4)\n # reshape to (K*A, 4) shifted anchors\n A = anchors.shape[0]\n K = shifts.shape[0]\n all_anchors = (anchors.reshape((1, A, 4)) + shifts.reshape((1, K, 4)).transpose((1, 0, 2)))\n all_anchors = all_anchors.reshape((K * A, 4))\n\n return all_anchors\n\n" ]
[ [ "numpy.expand_dims", "numpy.meshgrid", "numpy.arange", "numpy.tile", "numpy.append", "torch.cuda.is_available", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
randall-romero/CompEcon-python
[ "c7a75f57f8472c972fddcace8ff7b86fee049d29" ]
[ "_build/jupyter_execute/notebooks/dp/01b Timber Harvesting -- cubic spline.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n\n# # Timber Harvesting -- using cubic splines\n# \n# **Randall Romero Aguilar, PhD**\n# \n# This demo is based on the original Matlab demo accompanying the <a href=\"https://mitpress.mit.edu/books/applied-computational-economics-and-finance\">Computational Economics and Finance</a> 2001 textbook by Mario Miranda and Paul Fackler.\n# \n# Original (Matlab) CompEcon file: **demdp01b.m**\n# \n# Running this file requires the Python version of CompEcon. This can be installed with pip by running\n# \n# !pip install compecon --upgrade\n# \n# <i>Last updated: 2021-Oct-01</i>\n# <hr>\n\n# ## About\n# \n# Profit maximizing owner of a commercial tree stand must decide when to clearcut the stand.\n# \n\n# In[1]:\n\n\nimport numpy as np\nfrom compecon import NLP, demo, BasisSpline\nimport matplotlib.pyplot as plt\n\n\n# In[2]:\n\n\nprice = 1.0 # price of biomass\nkappa = 0.2 # clearcut-replant cost\nsmax = 0.5 # stand carrying capacity\ngamma = 0.1 # biomass growth parameter\ndelta = 0.9 # discount factor\n\n\n# ### Code the growth function\n\n# In[3]:\n\n\ndef h(s): return np.array(s + gamma*(smax - s))\n\n\n# ## SOLUTION\n# \n# ### Code the approximant and the residual\n\n# In[4]:\n\n\nns = 200\nvhat = BasisSpline(ns,0,smax,k=3)\n\n\n# In[5]:\n\n\ndef vhat1(s): return price*s - kappa + delta * vhat(h(0))\ndef vhat0(s): return delta * vhat(h(s))\n\n\n# In[6]:\n\n\ndef resid(c,s=vhat.nodes):\n vhat.c = c\n return vhat(s) - np.maximum(vhat0(s), vhat1(s))\n\n\n# ### Solve collocation equation\n\n# In[7]:\n\n\ncc = NLP(resid).broyden(vhat.c)\n\n\n# ### Compute critical biomass\n\n# In[8]:\n\n\nscrit = NLP(lambda s: vhat0(s)-vhat1(s)).broyden(0.0)[0]\n\n\n# ## ANALYSIS\n\n# ### Compute refined state grid\n\n# In[9]:\n\n\nss = np.linspace(0,smax,1000)\n\n\n# ### Plot Conditional Value Functions\n\n# In[10]:\n\n\nfig1 =demo.figure('Conditional Value Functions','Biomass','Value of Stand')\nplt.plot(ss,vhat0(ss),label='Grow')\nplt.plot(ss,vhat1(ss),label='Clear-Cut')\nplt.legend()\n\nvcrit = vhat(scrit)\nymin = plt.ylim()[0]\nplt.vlines(scrit, ymin,vcrit,'grey',linestyles='--')\ndemo.annotate(scrit,ymin,'$s^*$',ms=10)\ndemo.bullet(scrit,vcrit)\nprint(f'Optimal Biomass Harvest Level = {scrit:.4f}') \n\n\n# ### Plot Value Function Residual\n\n# In[11]:\n\n\nfig2 = demo.figure('Bellman Equation Residual', 'Biomass', 'Percent Residual')\nplt.plot(ss, 100*resid(cc,ss) / vhat(ss))\nplt.hlines(0,0,smax,linestyles='--')\n\n\n# ### Compute ergodic mean annual harvest \n\n# In[12]:\n\n\ns = h(0)\nfor n in range(100):\n if s > scrit: break\n s = h(s)\n \nprint(f'Ergodic Mean Annual Harvest = {s/n:.4f} after {n+1} iterations') \n\n\n# In[13]:\n\n\n#demo.savefig([fig1,fig2])\n\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.linspace", "matplotlib.pyplot.ylim", "matplotlib.pyplot.hlines", "matplotlib.pyplot.vlines", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lacava/deep-symbolic-regression
[ "d7b98b943740405724c2a9860c4b1ec5d6a532f3" ]
[ "dsr/dsr/utils.py" ]
[ "\"\"\"Utility functions used in deep symbolic regression.\"\"\"\n\nimport os\nimport functools\nimport numpy as np\n\n\ndef is_float(s):\n \"\"\"Determine whether str can be cast to float.\"\"\"\n\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n\n# Adapted from: https://stackoverflow.com/questions/32791911/fast-calculation-of-pareto-front-in-python\ndef is_pareto_efficient(costs):\n \"\"\"\n Find the pareto-efficient points given an array of costs.\n\n Parameters\n ----------\n\n costs : np.ndarray\n Array of shape (n_points, n_costs).\n\n Returns\n -------\n\n is_efficient_maek : np.ndarray (dtype:bool)\n Array of which elements in costs are pareto-efficient.\n \"\"\"\n\n is_efficient = np.arange(costs.shape[0])\n n_points = costs.shape[0]\n next_point_index = 0 # Next index in the is_efficient array to search for\n while next_point_index < len(costs):\n nondominated_point_mask = np.any(costs < costs[next_point_index], axis=1)\n nondominated_point_mask[next_point_index] = True\n is_efficient = is_efficient[nondominated_point_mask] # Remove dominated points\n costs = costs[nondominated_point_mask]\n next_point_index = np.sum(nondominated_point_mask[:next_point_index]) + 1\n is_efficient_mask = np.zeros(n_points, dtype=bool)\n is_efficient_mask[is_efficient] = True\n return is_efficient_mask\n\n\ndef setup_output_files(logdir, output_file):\n \"\"\"\n Writes the main output file header and returns the reward, hall of fame, and Pareto front config filenames.\n\n Parameters:\n -----------\n\n logdir : string\n Directory to log to.\n\n output_file : string\n Name of output file.\n\n Returns:\n --------\n\n all_r_output_file : string\n all_r output filename\n\n hof_output_file : string\n hof output filename\n\n pf_output_file : string\n pf output filename\n \"\"\"\n os.makedirs(logdir, exist_ok=True)\n output_file = os.path.join(logdir, output_file)\n prefix, _ = os.path.splitext(output_file)\n all_r_output_file = \"{}_all_r.npy\".format(prefix)\n hof_output_file = \"{}_hof.csv\".format(prefix)\n pf_output_file = \"{}_pf.csv\".format(prefix)\n with open(output_file, 'w') as f:\n # r_best : Maximum across all iterations so far\n # r_max : Maximum across this iteration's batch\n # r_avg_full : Average across this iteration's full batch (before taking epsilon subset)\n # r_avg_sub : Average across this iteration's epsilon-subset batch\n # n_unique_* : Number of unique Programs in batch\n # n_novel_* : Number of never-before-seen Programs per batch\n # a_ent_* : Empirical positional entropy across sequences averaged over positions\n # invalid_avg_* : Fraction of invalid Programs per batch\n headers = [\"base_r_best\",\n \"base_r_max\",\n \"base_r_avg_full\",\n \"base_r_avg_sub\",\n \"r_best\",\n \"r_max\",\n \"r_avg_full\",\n \"r_avg_sub\",\n \"l_avg_full\",\n \"l_avg_sub\",\n \"ewma\",\n \"n_unique_full\",\n \"n_unique_sub\",\n \"n_novel_full\",\n \"n_novel_sub\",\n \"a_ent_full\",\n \"a_ent_sub\",\n \"invalid_avg_full\",\n \"invalid_avg_sub\"]\n f.write(\"{}\\n\".format(\",\".join(headers)))\n\n return all_r_output_file, hof_output_file, pf_output_file\n\n\nclass cached_property(object):\n \"\"\"\n Decorator used for lazy evaluation of an object attribute. The property\n should be non-mutable, since it replaces itself.\n \"\"\"\n\n def __init__(self, getter):\n self.getter = getter\n\n functools.update_wrapper(self, getter)\n\n def __get__(self, obj, cls):\n if obj is None:\n return self\n\n value = self.getter(obj)\n setattr(obj, self.getter.__name__, value)\n return value\n\n\n# Entropy computation in batch\ndef empirical_entropy(labels):\n\n n_labels = len(labels)\n\n if n_labels <= 1:\n return 0\n\n value, counts = np.unique(labels, return_counts=True)\n probs = counts / n_labels\n n_classes = np.count_nonzero(probs)\n\n if n_classes <= 1:\n return 0\n\n ent = 0.\n # Compute entropy\n for i in probs:\n ent -= i * np.log(i)\n\n return ent\n" ]
[ [ "numpy.log", "numpy.unique", "numpy.arange", "numpy.any", "numpy.count_nonzero", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
thiagolcmelo/dynamic
[ "9e4e71dd25ce3c778b17b62ef4062273d244a5ac" ]
[ "core/utils.py" ]
[ "########################################################################\n# Useful functions for performing mathmatical calculations #\n# author: Thiago Melo #\n# creation: 2018-10-30 #\n# update: 2018-10-30 #\n\nimport numpy as np\n\ndef solve_eigenproblem(H):\n \"\"\"\n Find the eigenvalues and eigenvectors for the matrix H\n\n Params\n ------\n H : matrix\n It is expected to be a N x N numpy.complex128 matrix\n \n Return\n ------\n (values, vectors) tuple with eigenvalues and eigenvectors\n \"\"\"\n values, vectors = np.linalg.eig(H)\n idx = np.real(values).argsort()\n return values[idx], vectors.T[idx]" ]
[ [ "numpy.linalg.eig", "numpy.real" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MaxMotovilov/allennlp
[ "d4ee5db1c630d6c631a828ee12fcbf6154de288c" ]
[ "allennlp/tests/modules/maxout_test.py" ]
[ "# pylint: disable=no-self-use,invalid-name\nfrom numpy.testing import assert_almost_equal\nimport pytest\nimport torch\n\nfrom allennlp.common import Params\nfrom allennlp.common.checks import ConfigurationError\nfrom allennlp.modules import Maxout\nfrom allennlp.nn import InitializerApplicator\nfrom allennlp.common.testing import AllenNlpTestCase\n\n\nclass TestMaxout(AllenNlpTestCase):\n def test_init_checks_output_dims_consistency(self):\n with pytest.raises(ConfigurationError):\n Maxout(input_dim=2,\n num_layers=2,\n output_dims=[5, 4, 3],\n pool_sizes=4,\n dropout=0.0)\n\n def test_init_checks_pool_sizes_consistency(self):\n with pytest.raises(ConfigurationError):\n Maxout(input_dim=2,\n num_layers=2,\n output_dims=5,\n pool_sizes=[4, 5, 2],\n dropout=0.0)\n\n def test_init_checks_dropout_consistency(self):\n with pytest.raises(ConfigurationError):\n Maxout(input_dim=2,\n num_layers=3,\n output_dims=5,\n pool_sizes=4,\n dropout=[0.2, 0.3])\n\n def test_forward_gives_correct_output(self):\n params = Params({\n 'input_dim': 2,\n 'output_dims': 3,\n 'pool_sizes': 4,\n 'dropout': 0.0,\n 'num_layers': 2\n })\n maxout = Maxout.from_params(params)\n\n constant_init = lambda tensor: torch.nn.init.constant_(tensor, 1.)\n initializer = InitializerApplicator([(\".*\", constant_init)])\n initializer(maxout)\n\n input_tensor = torch.FloatTensor([[-3, 1]])\n output = maxout(input_tensor).data.numpy()\n assert output.shape == (1, 3)\n # This output was checked by hand\n # The output of the first maxout layer is [-1, -1, -1], since the\n # matrix multiply gives us [-2]*12. Reshaping and maxing\n # produces [-2, -2, -2] and the bias increments these values.\n # The second layer output is [-2, -2, -2], since the matrix\n # matrix multiply gives us [-3]*12. Reshaping and maxing\n # produces [-3, -3, -3] and the bias increments these values.\n assert_almost_equal(output, [[-2, -2, -2]])\n" ]
[ [ "torch.nn.init.constant_", "numpy.testing.assert_almost_equal", "torch.FloatTensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zjuptian/GoogleNet_Modelarts
[ "8ad4146d061c484e8df01bd018747cdd1dca4a42" ]
[ "inception/model.py" ]
[ "# coding=utf-8\n# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\n# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\nimport tensorflow as tf\nfrom . import inception_v1\nfrom . import inception_v4\nfrom tensorflow.contrib import slim as slim\nimport numpy as np\n\nclass Model(object):\n def __init__(self, args, data, hyper_param, layers, logger):\n self.args = args\n self.data = data\n self.hyper_param = hyper_param\n self.layers = layers\n self.logger = logger \n\n def get_estimator_model_func(self, features, labels, mode, params=None):\n labels = tf.reshape(labels, (-1,))\n \n inputs = features\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n\n inputs = tf.cast(inputs, self.args.dtype)\n\n if is_training:\n if self.args.network == \"inception_v1\":\n with slim.arg_scope(inception_v1.inception_v1_arg_scope(weight_decay = self.args.weight_decay)):\n top_layer, end_points = inception_v1.inception_v1(inputs = features, num_classes = 2, dropout_keep_prob = 0.7, is_training = True)\n if self.args.network == \"inception_v4\":\n with slim.arg_scope(inception_v4.inception_v4_arg_scope(weight_decay=self.args.weight_decay)):\n top_layer, end_points = inception_v4.inception_v4(inputs=features, num_classes=2, dropout_keep_prob=0.8, is_training = True)\n else:\n if self.args.network == \"inception_v1\":\n with slim.arg_scope(inception_v1.inception_v1_arg_scope()):\n top_layer, end_points = inception_v1.inception_v1(inputs = features, num_classes = 2, dropout_keep_prob = 1.0, is_training = False)\n if self.args.network == \"inception_v4\":\n with slim.arg_scope(inception_v4.inception_v4_arg_scope()):\n top_layer, end_points = inception_v4.inception_v4(inputs=features, num_classes=2, dropout_keep_prob=1.0, is_training = False)\n\n logits = top_layer\n predicted_classes = tf.argmax(logits, axis=1, output_type=tf.int32)\n logits = tf.cast(logits, tf.float32)\n\n labels_one_hot = tf.one_hot(labels, depth=2)\n\n loss = tf.losses.softmax_cross_entropy(\n logits=logits, onehot_labels=labels_one_hot, label_smoothing=self.args.label_smoothing)\n\n base_loss = tf.identity(loss, name='loss')\n\n l2_loss = tf.add_n([tf.nn.l2_loss(tf.cast(v, tf.float32)) for v in tf.trainable_variables()])\n l2_loss = tf.multiply(l2_loss, self.args.weight_decay)\n total_loss = base_loss + l2_loss\n\n # loss = tf.losses.softmax_cross_entropy(logits, labels_one_hot, label_smoothing=self.args.label_smoothing)\n # loss = tf.identity(loss, name='loss')\n # total_loss = tf.losses.get_total_loss(add_regularization_losses = True)\n\n total_loss = tf.identity(total_loss, name = 'total_loss')\n\n if mode == tf.estimator.ModeKeys.EVAL:\n with tf.device(None):\n metrics = self.layers.get_accuracy( labels, predicted_classes, logits, self.args)\n\n return tf.estimator.EstimatorSpec(\n mode, loss=loss, eval_metric_ops=metrics)\n\n assert (mode == tf.estimator.ModeKeys.TRAIN)\n\n batch_size = tf.shape(inputs)[0]\n\n global_step = tf.train.get_global_step()\n learning_rate = self.hyper_param.get_learning_rate()\n\n momentum = self.args.momentum\n\n opt = tf.train.MomentumOptimizer(\n learning_rate, momentum, use_nesterov=self.args.use_nesterov)\n\n from npu_bridge.estimator.npu.npu_optimizer import NPUDistributedOptimizer\n opt = NPUDistributedOptimizer(opt)\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) or []\n\n with tf.control_dependencies(update_ops):\n gate_gradients = tf.train.Optimizer.GATE_NONE\n grads_and_vars = opt.compute_gradients(total_loss, gate_gradients=gate_gradients)\n train_op = opt.apply_gradients(grads_and_vars, global_step=global_step)\n\n train_op = tf.group(train_op)\n \n return tf.estimator.EstimatorSpec(mode, loss=total_loss, train_op=train_op) \n\n" ]
[ [ "tensorflow.device", "tensorflow.multiply", "tensorflow.control_dependencies", "tensorflow.shape", "tensorflow.get_collection", "tensorflow.cast", "tensorflow.reshape", "tensorflow.identity", "tensorflow.train.get_global_step", "tensorflow.losses.softmax_cross_entropy", "tensorflow.train.MomentumOptimizer", "tensorflow.one_hot", "tensorflow.estimator.EstimatorSpec", "tensorflow.trainable_variables", "tensorflow.argmax", "tensorflow.group" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
ti-ginkgo/regressor-template
[ "1089d7eb8efe7869dae5df54022736213f2badb0" ]
[ "{{cookiecutter.package_name}}/src/exp_000/ishtos_lightning_module.py" ]
[ "import numpy as np\nimport torch\nfrom pytorch_lightning import LightningModule\n\nfrom ishtos_losses import get_loss\nfrom ishtos_metrics import get_metric\nfrom ishtos_models import get_model\nfrom ishtos_optimizers import get_optimizer\nfrom ishtos_schedulers import get_scheduler\n\n\nclass MyLightningModule(LightningModule):\n def __init__(self, config, fold=0, len_train_loader=0):\n super(MyLightningModule, self).__init__()\n self.save_hyperparameters(config)\n\n self.config = config\n self.fold = fold\n self.len_train_loader = len_train_loader\n self.model = get_model(config.model)\n self.loss = get_loss(config.loss)\n self.metric = get_metric(config.metric)\n\n def configure_optimizers(self):\n optimizer = get_optimizer(\n parameters=self.model.parameters(), config=self.config.optimizer\n )\n scheduler = get_scheduler(\n optimizer=optimizer,\n config=self.config.scheduler,\n len_train_loader=self.len_train_loader,\n )\n scheduler_dict = {\n \"scheduler\": scheduler,\n \"interval\": self.config.scheduler.interval,\n \"monitor\": self.config.scheduler.monitor,\n }\n return {\n \"optimizer\": optimizer,\n \"lr_scheduler\": scheduler_dict,\n }\n\n def training_step(self, batch, batch_idx):\n loss, preds, target = self.__step(batch, \"train\")\n return {\"loss\": loss, \"preds\": preds, \"target\": target}\n\n def validation_step(self, batch, batch_idx):\n loss, preds, target = self.__step(batch, \"val\")\n return {\"loss\": loss, \"preds\": preds, \"target\": target}\n\n def __step(self, batch, phase):\n images, target = batch\n if do_mixup(phase, self.current_epoch, self.config):\n images, target_a, target_b, lam = mixup_data(images, target)\n logits = self.model(images).squeeze(1)\n loss = mixup_loss(self.loss, logits, target_a, target_b, lam)\n else:\n logits = self.model(images).squeeze(1)\n for i, loss_weight, loss_func in self.losses:\n if i == 0:\n loss = loss_weight * loss_func(logits, target)\n else:\n loss += loss_weight * loss_func(logits, target)\n\n preds = logits.sigmoid().detach().cpu()\n target = target.detach().cpu()\n return loss, preds, target\n\n def training_epoch_end(self, outputs):\n if self.config.loss.name == \"OUSMLoss\":\n self.loss.update()\n self.__epoch_end(outputs, \"train\")\n\n def validation_epoch_end(self, outputs):\n self.__epoch_end(outputs, \"val\")\n\n def __epoch_end(self, outputs, phase):\n d = dict()\n loss = []\n preds = []\n target = []\n for output in outputs:\n loss.append(output[\"loss\"])\n preds.append(output[\"preds\"])\n target.append(output[\"target\"])\n preds = torch.cat(preds)\n target = torch.cat(target)\n loss = torch.stack(loss).mean().item()\n\n d[f\"{phase}_loss\"] = loss\n for i, (metric_name, metric_func) in enumerate(self.metrics):\n if i == 0:\n d[f\"{phase}_score\"] = metric_func(preds=preds, target=target)\n d[f\"{phase}_{metric_name}\"] = metric_func(preds=preds, target=target)\n self.log_dict(d, prog_bar=True, logger=True, on_step=False, on_epoch=True)\n\n\ndef do_mixup(phase, current_epoch, config):\n return (\n phase == \"train\"\n and config.train.mixup.enable\n and np.random.rand() < config.train.mixup.p\n and current_epoch + config.train.mixup.duration < config.trainer.max_epochs\n )\n\n\ndef mixup_data(x, y, alpha=1.0):\n lam = np.random.beta(alpha, alpha)\n\n batch_size = x.size()[0]\n index = torch.randperm(batch_size)\n\n mixed_x = lam * x + (1 - lam) * x[index, :]\n y_a, y_b = y, y[index]\n return mixed_x, y_a, y_b, lam\n\n\ndef mixup_loss(loss, pred, y_a, y_b, lam):\n return lam * loss(pred, y_a) + (1 - lam) * loss(pred, y_b)\n" ]
[ [ "numpy.random.beta", "torch.cat", "torch.randperm", "numpy.random.rand", "torch.stack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mickael-bdias/OpenCV-projects-with-Python
[ "75e42e9f856650ad997905a85997a817434362fe" ]
[ "Image_Classification/03.ComparisonRGB_HSV.py" ]
[ "#!/usr/bin/env python\n\n\"\"\"03.GreenScreen.py\nComparison between RGB and HSV.\nUsed matplotlib to plot the 6 channels\"\"\"\n\n__author__ = \"Mickaël Dias\"\n__copyright__ = \"Copyright 2021, OpenCV-projects-with-Python\"\n__licence__ = \"MIT\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Mickaël Dias\"\n__email__ = \"[email protected]\"\n__status__ = \"Production\"\n\nimport matplotlib.pyplot as plt\nimport cv2\n\n# Original image and Background image\npath = \"C:/Users/Mickael/PycharmProjects/OpenCV-projects-with-Python/Resources/Images/colors_houses.jpg\"\nimageOriginal = cv2.imread(path)\nprint(\"Original Dimensions: \", imageOriginal.shape)\n\n# RGB channels\nredChannel = imageOriginal[:, :, 0]\ngreenChannel = imageOriginal[:, :, 1]\nblueChannel = imageOriginal[:, :, 2]\n\n# HSV channels\nhsv = cv2.cvtColor(imageOriginal, cv2.COLOR_RGB2HSV)\nhueChannel = hsv[:, :, 0]\nsaturationChannel = hsv[:, :, 1]\nvalueChannel = hsv[:, :, 2]\n\n# Plot RGB and HSV channels\nfig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3, figsize=(20, 10))\n\nax1.set_title('Red')\nax1.imshow(redChannel, cmap='gray')\nax2.set_title('Green')\nax2.imshow(greenChannel, cmap='gray')\nax3.set_title('Blue')\nax3.imshow(blueChannel, cmap='gray')\n\nax4.set_title('Hue')\nax4.imshow(hueChannel, cmap='gray')\nax5.set_title('Saturation')\nax5.imshow(saturationChannel, cmap='gray')\nax6.set_title('Value')\nax6.imshow(valueChannel, cmap='gray')\n\nplt.show()\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.subplots" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Balaji-Ganesh/Furnishing-OpenCV-Basics
[ "54cd8fa09cc6f1298861b12ffb190432f412bd1f" ]
[ "Projects/VirtualCanvas/VirtualCanvas.py" ]
[ "# Import the required libraries\r\nimport cv2\r\nimport numpy as np\r\nimport Projects.VirtualCanvas.utils as utils\r\n\r\n\r\nclass VirtualCanvas:\r\n def __init__(self, num_markers=2, debug_mode=False):\r\n # Mode in which the user would like to run the program..\r\n self.debug_mode = debug_mode # False for normal_run, True for debug_mode\r\n # Get the camera access..\r\n self.capture = cv2.VideoCapture(0)\r\n # Adjust the camera capture properties..\r\n self.capture.set(cv2.CAP_PROP_BRIGHTNESS, 200)\r\n self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, 800)\r\n self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 600)\r\n\r\n # No. of markers the user would like to draw..\r\n self.num_markers = num_markers\r\n self.marker_path_points = [] # of format -> [[x, y], colorId]\r\n\r\n self.markers_HSV, self.marker_colors = utils.load_data(num_markers=num_markers, debug_mode=debug_mode)\r\n if debug_mode: print(\"Data loaded Successfully.. as: markers_HSV = \\n\", self.markers_HSV, \"\\nmarker_colors = \\n\", self.marker_colors)\r\n\r\n def get_camera_feed(self):\r\n \"\"\"\r\n This function will return the frames from the web cam feed\r\n :return:\r\n \"\"\"\r\n # get the frame..from cam feed\r\n read_status, self.frame = self.capture.read()\r\n return self.frame\r\n\r\n def detect_and_draw_as_marker(self, image):\r\n \"\"\"\r\n This function is made for testing purposes.\r\n The part of this function's code is used in some other functions with some optimizations\r\n\r\n :return:\r\n \"\"\"\r\n # Required variables\r\n count = 0\r\n # convert to HSV.. so that we can filter out the image from our captured HSV values for our markers previously..\r\n HSVimg = cv2.cvtColor(src=image, code=cv2.COLOR_BGR2HSV)\r\n # loop through all marker's HSV values\r\n for marker_HSV in self.markers_HSV:\r\n lower_boundary = np.array(marker_HSV[0])\r\n upper_boundary = np.array(marker_HSV[1])\r\n # Get the mask image that satisfies the lower and upper HSV values..\r\n maskImg = cv2.inRange(src=HSVimg, lowerb=lower_boundary, upperb=upper_boundary)\r\n\r\n '''Draw the contours for the mask image detected, marker point for the marker'''\r\n # Get the bounding box corners (In the function call to self.draw_contours(), contours are drawn to original camera feed, if self.debug_mode is set to 1)\r\n x, y, width, height = self.draw_contours(image, maskImg)\r\n if self.debug_mode:\r\n cv2.rectangle(img=image, pt1=(x, y), pt2=(x + width, y + height), color=(255, 0, 255), thickness=3)\r\n # Select the marker point..\r\n marker_point_center = (x + width // 2, y)\r\n # Draw the marker point..\r\n # cv2.circle(img=image, center=marker_point_center, radius=5, color=(2, 255, 10), thickness=cv2.FILLED)\r\n cv2.circle(img=image, center=marker_point_center, radius=5, color=list(self.marker_colors[count]), thickness=cv2.FILLED)\r\n\r\n # Append the trace point of marker..\r\n self.marker_path_points.append([marker_point_center, count])\r\n #print(count, end=\"\\n\")\r\n count += 1\r\n\r\n def draw_contours(self, image, maskImg):\r\n \"\"\"\r\n This function will find the contours for the mask image which is obtained via HSV values filtering.\r\n and it also draws the contours for the markers on color image of camera feed(But can be turned of by commenting the line cv2.drawContours() or if self.debug_mode is set to 0).\r\n :param image: Original color image of camera feed.\r\n :param maskImg: Mask Image (Contains only the markers)\r\n :return: The bounding box corners of the detected markers..\r\n \"\"\"\r\n # Required variables..\r\n x, y, width, height = 0, 0, 0, 0\r\n # Find contours..\r\n contours, hierarchy = cv2.findContours(image=maskImg, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE) # Playable Parameters..\r\n # Draw the contours..\r\n for contour in contours:\r\n # Calculate the area of the contour, so can remove unnecessary contours..\r\n area = cv2.contourArea(contour=contour)\r\n if area > 3000: # Playable adjustment..!! Found Good as 3000 for current light condition.. change this if light condition changes..\r\n # Draw the contours to the image -- actual frame..\r\n if self.debug_mode:\r\n cv2.drawContours(image=image, contours=contour, contourIdx=-1, color=(255, 255, 0), thickness=4)\r\n # Find the perimeter of the markers detected...\r\n perimeter = cv2.arcLength(curve=contour, closed=True)\r\n # Approximating/Finding the corners of the image from the obtained corners..\r\n approx_corners = cv2.approxPolyDP(curve=contour, epsilon=0.02 * perimeter, closed=True)\r\n # Find the bounding box rectangle for the approximated corners..\r\n x, y, width, height = cv2.boundingRect(approx_corners)\r\n # Return the values with which a rectangle can be drawn..\r\n return x, y, width, height\r\n\r\n def get_markers_center(self, image):\r\n \"\"\"\r\n The code in this function is some part of the \"detect_and_draw_as_marker()\"\r\n This function will be called by trace_marker_path()\r\n :return:\r\n \"\"\"\r\n # Required variables..\r\n x, y, width, height = 0, 0, 0, 0\r\n # convert to HSV.. so that we can filter out the image from our captured HSV values for our markers previously..\r\n HSVimg = cv2.cvtColor(src=image, code=cv2.COLOR_BGR2HSV)\r\n # loop through all marker's HSV values\r\n for marker_HSV in self.markers_HSV:\r\n lower_boundary = np.array(marker_HSV[0])\r\n upper_boundary = np.array(marker_HSV[1])\r\n # Get the mask image that satisfies the lower and upper HSV values..\r\n maskImg = cv2.inRange(src=HSVimg, lowerb=lower_boundary, upperb=upper_boundary)\r\n\r\n '''Draw the contours for the mask image detected, marker point for the marker'''\r\n # Get the bounding box corners (In the function call to self.draw_contours(), contours are drawn to original camera feed, if self.debug_mode is set to 1)\r\n x, y, width, height = self.draw_contours(image, maskImg)\r\n if self.debug_mode:\r\n cv2.rectangle(img=image, pt1=(x, y), pt2=(x + width, y + height), color=(0, 0, 0), thickness=3)\r\n # Select the marker point..\r\n # marker_point_center = [x+width//2, y]\r\n return x + width // 2, y\r\n\r\n def trace_marker_path(self, image):\r\n \"\"\"\r\n This function will trace the path of the marker where marker has moved..\r\n :return: Nothing\r\n \"\"\"\r\n for trace_point in self.marker_path_points:\r\n cv2.circle(img=image, center=(trace_point[0]), radius=10, color=self.marker_colors[trace_point[1]], thickness=cv2.FILLED)\r\n\r\n\r\n\r\ndef drawOnCanvas(debug_mode=False):\r\n # Number of markers user would like to choose..\r\n markers_count = 3\r\n while markers_count <= 1:\r\n markers_count = int(input(\"How many markers would you like to use? (>1): \"))\r\n # Create object to class \"Virtual Canvas\"\r\n virtualCanvas = VirtualCanvas(num_markers=markers_count, debug_mode=debug_mode)\r\n while True:\r\n # Get the cam feed..\r\n image = virtualCanvas.get_camera_feed()\r\n # Get the marker drawing points and save it in the marker_path_points..as [center(x, y), marker_color(count)]\r\n virtualCanvas.detect_and_draw_as_marker(image)\r\n # Draw all the path points to resemble like drawing on canvas..\r\n virtualCanvas.trace_marker_path(image)\r\n\r\n # Display the final results..\r\n cv2.imshow(\"Virtual Canvas\", image)\r\n if cv2.waitKey(1) == 27:\r\n break\r\n\r\n\r\ncv2.destroyAllWindows()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # mode = int(input(\"Debug mode -- 1 or Normal Run ---0: \"))\r\n drawOnCanvas(debug_mode=True)\r\n\r\n\"\"\"\r\nLOG: \r\nFinal HSV values as: HUE_min, SAT_min, VAL_min, HUE_max, SAT_max, VAL_max 103 45 0 120 255 255\r\nFinal HSV values as: HUE_min, SAT_min, VAL_min, HUE_max, SAT_max, VAL_max 0 80 148 255 255 255\r\nFinal HSV values as: HUE_min, SAT_min, VAL_min, HUE_max, SAT_max, VAL_max 0 89 178 255 238 255\r\n\r\nfor Dark blue, Orange, Yellow Sparx pens respectively..\r\n\"\"\"\r\n\"\"\"\r\nImprovements:\r\n Add the facility of saving the HSV values -- either via numpy or pkl\r\n\"\"\"\r\n\r\n\"\"\"\r\nBackup code of def detect_and_draw_as_marker(self):\r\n \"\"\"\r\n\"\"\"\r\n This function is made for testing purposes.\r\n The part of this function's code is used in some other functions with some optimizations\r\n\r\n :return:\r\n \"\"\"\r\n\"\"\"\r\n while True:\r\n # Required variables\r\n count = 0\r\n # Get camera feed..\r\n image = self.get_camera_feed()\r\n # convert to HSV.. so that we can filter out the image from our captured HSV values for our markers previously..\r\n HSVimg = cv2.cvtColor(src=image, code=cv2.COLOR_BGR2HSV)\r\n # loop through all marker's HSV values\r\n for marker_HSV in self.markers_HSV:\r\n lower_boundary = np.array(marker_HSV[0])\r\n upper_boundary = np.array(marker_HSV[1])\r\n # Get the mask image that satisfies the lower and upper HSV values..\r\n maskImg = cv2.inRange(src=HSVimg, lowerb=lower_boundary, upperb=upper_boundary)\r\n\r\n '''Draw the contours for the mask image detected, marker point for the marker'''\r\n # Get the bounding box corners (In the function call to self.draw_contours(), contours are drawn to original camera feed, if self.debug_mode is set to 1)\r\n x, y, width, height = self.draw_contours(image, maskImg)\r\n if self.debug_mode:\r\n cv2.rectangle(img=image, pt1=(x, y), pt2=(x+width, y+height), color=(0, 0, 0), thickness=3)\r\n # Select the marker point..\r\n marker_point_center = (x+width//2, y)\r\n # Draw the marker point..\r\n # cv2.circle(img=image, center=marker_point_center, radius=5, color=(2, 255, 10), thickness=cv2.FILLED)\r\n cv2.circle(img=image, center=marker_point_center, radius=5, color=self.marker_colors[count], thickness=cv2.FILLED)\r\n count += 1\r\n cv2.imshow(\"Virtual Canvas\", image)\r\n #print(\"Working....\")\r\n if cv2.waitKey(1) == 27:\r\n break\r\n\"\"\"\r\n\r\n\"\"\"\r\n0 26 255 255 255 255 # orange\r\n101 35 0 255 255 255 # Blue\r\n0 76 25 255 255 255 # yellow\r\n\"\"\"\r\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Cybonic/AttDLNet
[ "8f19ac18316c56b00a448a9e0eaac70cb0853407" ]
[ "dataset_utils/kitti/pcl_parser_test.py" ]
[ "import os\nimport numpy as np\nimport torch\nimport dataset_utils.kitti.utils as utils\nfrom torch.utils.data import Dataset\nfrom common.laserscan import LaserScan\nfrom torch.utils.data import DataLoader, random_split\nfrom random import seed\nimport math\n\nEXTENSIONS_SCAN = ['.bin']\nEXTENSIONS_LABEL = ['.label']\n\n\ndef is_scan(filename):\n return any(filename.endswith(ext) for ext in EXTENSIONS_SCAN)\n\n\ndef is_label(filename):\n return any(filename.endswith(ext) for ext in EXTENSIONS_LABEL)\n\ndef velo_read(scan_path):\n scan = np.fromfile(scan_path, dtype=np.float32)\n scan = scan.reshape((-1, 4))\n\n #scan = scan.reshape((-1,4))\n return(np.array(scan))\n\ndef load_tripletset(triplet_file,root,dataset_name,corr):\n # path to triplet file\n triplet_set_file = os.path.join(root,dataset_name,'tripletset',corr, triplet_file + '.txt')\n #print(\"[INF] Loading triplet file: \" + triplet_set_file)\n assert os.path.isfile(triplet_set_file)\n # load content of the file (i.e. sequence and file names)\n triplet_set = load_triplet_file(triplet_set_file)\n # build root path to the descriptor folder\n idx = [int(i) for i in triplet_set['files']]\n\n return(np.array(idx))\n\ndef load_triplet_file(file):\n output = {}\n for line in open(file):\n inf_type,info = line.strip().split(':')\n if inf_type == 'seq':\n output[inf_type] = info\n else: \n output[inf_type] = info.split(' ')\n return(output)\n\n\ndef data_augment(rotations,anchor_unit,template_unit,label_unit,aug_percentage):\n \n aug_rot = np.array([],dtype=int)\n\n n_samples = int(len(anchor_unit))\n aug_n_samples = int(len(anchor_unit)*aug_percentage) # Total samples to be added\n n_samples_per_rot = int(aug_n_samples/len(rotations)) # Samples per rotations\n \n # original dataset\n aug_rot = 0*np.ones(n_samples) \n aug_anchors = anchor_unit\n aug_template = template_unit\n aug_labels = label_unit\n\n # np.\n for rot in rotations:\n print(\"[INF] Augmenting data:%f\"%(rot))\n idx = np.random.randint(n_samples, size=n_samples_per_rot)\n\n aug_anchors = np.append(aug_anchors,np.array(anchor_unit)[idx])\n aug_template = np.append(aug_template,np.array(template_unit)[idx])\n aug_labels = np.append(aug_labels,np.array(label_unit)[idx])\n aug_rot = np.append(aug_rot,rot*np.ones(n_samples_per_rot))\n \n return(aug_anchors,aug_template,aug_labels,aug_rot)\n\nclass SemanticKitti(Dataset):\n\n def __init__(self, \n root, # directory where data is\n sensor, # sensor to parse scans from\n sequences = [], # sequences for this data (e.g. [1,3,4,6])\n max_points=150000, # max number of points present in dataset\n range_thres = None,\n fraction = -1,\n debug = False): # Limit the range of the scan \n \n self.range_thres = range_thres\n self.rotation = None\n #self.aug_percentage = aug_percentage\n # save deats\n\n self.root = root\n self.sequences = sequences\n \n self.sensor = sensor\n self.sensor_img_H = sensor[\"img_prop\"][\"height\"]\n self.sensor_img_W = sensor[\"img_prop\"][\"width\"]\n self.sensor_img_means = torch.tensor(sensor[\"img_means\"],\n dtype=torch.float)\n self.sensor_img_stds = torch.tensor(sensor[\"img_stds\"],\n dtype=torch.float)\n self.sensor_fov_up = sensor[\"fov_up\"]\n self.sensor_fov_down = sensor[\"fov_down\"]\n self.max_points = max_points\n # self.gt = gt\n np.random.seed(0)\n debug_flag = debug\n\n print(\"[INF] Debug Flag: %d\"%(debug_flag)) \n \n # sanity checks\n\n # make sure directory exists\n if os.path.isdir(self.root):\n print(\"[INF] Sequences folder exists! Using sequences from %s\" % self.root)\n else:\n raise ValueError(\"Sequences folder doesn't exist! Exiting...\")\n\n # make sure sequences is a list\n assert(isinstance(self.sequences, list))\n\n # placeholder for filenames\n self.scan_files = []\n self.template_files = []\n self.labels = []\n self.aug_rot = []\n self.poses = {}\n self.sorted_index = []\n # fill in with names, checking that all sequences are complete\n n_positives = 0\n n_negatives = 0\n n_anchors = 0\n\n print(\"================================================\")\n\n for seq in self.sequences:\n # to string\n seq = '{0:02d}'.format(int(seq))\n corr = 'ex%d'%(int(seq))\n\n pose_path = os.path.join(self.root, \"sequences\", seq,'poses.txt')\n self.poses = utils.poses(pose_path).get_2D_poses()\n \n print(\"[INF] Parsing seq {}\".format(seq))\n\n\n # get paths for each\n scan_path = os.path.join(self.root, \"sequences\", seq, \"velodyne\")\n # get files\n scan_files = np.array([os.path.join(dp, f) for dp, dn, fn in os.walk(\n os.path.expanduser(scan_path)) for f in fn if is_scan(f)])\n\n self.total_idx = np.arange(len(scan_files))\n\n print(\"[INF] Total Seq Files: {}\".format(len(scan_files)))\n self.triplet_flag = True\n\n try:\n self.positive = load_tripletset('positive','data','kitti',corr)\n self.negative = load_tripletset('negative','data','kitti',corr)\n self.anchors = load_tripletset('anchor' ,'data','kitti',corr)\n self.map_ref = []\n \n # self.no_loop_pool = np.in1d(all_idx,self.loop_pool)\n except:\n print(\"[ERR] No Triplet data available!\")\n self.triplet_flag = False\n\n\n # In Validation mode, descriptors are not split into anchors and templates \n # and only \n labels = np.zeros(len(scan_files))\n labels[self.positive] = 1\n labels[self.anchors] = 2\n #scan_files = scan_files\n #sorted_index = np.arange(len(scan_files))\n self.loop_pool = np.array([self.anchors,self.positive]).flatten()\n sorted_index = np.arange(int(len(scan_files)),dtype=int)\n self.no_loop_pool = np.array([idx for idx in sorted_index if idx not in self.loop_pool])\n\n # Fraction\n if fraction > 0 and fraction < 1:\n\n loop_fact = math.ceil(len(self.positive)*(fraction))\n\n # Get Positive and anchor subset\n # loop_sample_idx = np.random.randint(0, len(self.positive), loop_fact, dtype=int)\n\n step = round(len(self.anchors)/loop_fact,0)\n\n loop_sample_idx = np.arange(0,len(self.anchors),step,dtype=int)\n\n self.positive = self.positive[loop_sample_idx]\n self.anchors = self.anchors[loop_sample_idx]\n\n # Get Negative subset \n no_loop_fact = int(len(self.no_loop_pool)*(fraction))\n\n step = len(self.no_loop_pool)/no_loop_fact\n\n no_loop_sample_idx = np.arange(0,len(self.no_loop_pool),step,dtype = int)\n\n self.negative = self.no_loop_pool[no_loop_sample_idx]\n \n # Build a array with all subset indices\n indx = np.concatenate((self.positive,self.anchors,self.negative)).flatten()\n index_sort = np.argsort(indx)\n \n sorted_index = indx[index_sort]\n # Get point cloud files from the subset\n scan_files = scan_files[sorted_index]\n \n # Label processing\n pos_lab = np.ones(len(self.positive))\n an_lab = 2*np.ones(len(self.anchors))\n neg_lab = np.zeros(len(self.negative))\n labels = np.concatenate((pos_lab,an_lab,neg_lab)).flatten()\n labels = labels[index_sort]\n\n n_anchors = len(labels[labels == 2])\n n_positives = len(labels[labels == 1])\n n_negatives = len(labels[labels == 0])\n\n self.labels.extend(labels)\n self.scan_files.extend(scan_files)\n self.sorted_index.extend(sorted_index)\n \n \n\n print(\"[INF] Total Anchors: {}\".format(n_anchors))\n print(\"[INF] Total Negatives: {}\".format(n_negatives))\n print(\"[INF] Total Positives: {}\".format(n_positives))\n print(\"[INF] Total Labels: {}\".format(len(self.labels)))\n\n print(\"================================================\")\n #self.scan_files.extend(scan_files)\n\n def set_rotation_set(self,angles,percentage):\n print(\"[INF] point clouds will be rotated\" )\n aug = data_augment(angles,\n self.anchor_files,\n self.template_files,\n self.labels,\n percentage)\n\n aug_anchors, aug_template, aug_labels, rot = aug\n self.anchor_files = aug_anchors\n self.template_files = aug_template\n self.labels = aug_labels\n self.rotation = percentage\n self.aug_rot = rot\n \n\n # self.aug_rot.extend(aug_rot)\n\n\n def get_param(self):\n param = {}\n param['anch'] = len(self.anchor_files)\n param['temp'] = len(self.template_files)\n labels = np.array(self.labels)\n param['pos'] = len(labels[labels == 1])\n param['neg'] = len(labels[labels == 0])\n return(param)\n \n def get_idx(self):\n indices = {}\n indices['positives'] = self.positive\n indices['negatives'] = self.negative\n indices['anchors'] = self.anchors\n indices['all'] = self.sorted_index\n indices['map'] = self.map_ref\n indices['noloops'] = self.no_loop_pool\n\n indices['poses'] = self.poses\n return(indices)\n\n def get_files(self):\n files = {}\n \n files['scans'] = self.scan_files\n files['anch'] = self.anchors\n files['neg'] = self.negative\n files['pos'] = self.positive\n files['poses'] = self.poses\n \n return(files)\n\n\n def load_files(self,anchor,template,labels,rotation = None):\n self.anchor_files = anchor\n self.template_files = template\n\n self.label = labels \n self.rotate = rotation\n\n def __getitem__(self, index):\n # get item in tensor shape\n \n scan_file = self.scan_files[index]\n\n scan = LaserScan(project=True,\n H=self.sensor_img_H,\n W=self.sensor_img_W,\n fov_up=self.sensor_fov_up,\n fov_down=self.sensor_fov_down)\n # Load point cloud\n scan.open_scan(scan_file)\n # Project point cloud to CNN input format\n projA = scan.points\n\n label = self.labels[index]\n indice = self.sorted_index[index]\n # return\n return projA,label,indice\n\n def __len__(self):\n return len(self.scan_files)\n\n\n def gen_projection(self,scan):\n unproj_n_points = scan.points.shape[0]\n unproj_xyz = torch.full((self.max_points, 3), -1.0, dtype=torch.float)\n unproj_xyz[:unproj_n_points] = torch.from_numpy(scan.points)\n \n\n return(unproj_xyz)\n\n @staticmethod\n def map(label, mapdict):\n # put label from original values to xentropy\n # or vice-versa, depending on dictionary values\n # make learning map a lookup table\n maxkey = 0\n for key, data in mapdict.items():\n if isinstance(data, list):\n nel = len(data)\n else:\n nel = 1\n if key > maxkey:\n maxkey = key\n # +100 hack making lut bigger just in case there are unknown labels\n if nel > 1:\n lut = np.zeros((maxkey + 100, nel), dtype=np.int32)\n else:\n lut = np.zeros((maxkey + 100), dtype=np.int32)\n for key, data in mapdict.items():\n try:\n lut[key] = data\n except IndexError:\n print(\"Wrong key \", key)\n # do the mapping\n return lut[label]\n\n\nclass Parser():\n # standard conv, BN, relu\n def __init__(self,\n dataset, # directory for data\n session , # max points in each scan in entire datase # sequences to train\n debug = False\n ): # shuffle training set?\n super(Parser, self).__init__()\n\n # if I am training, get the dataset\n self.root = dataset['path']['root']\n self.sensor = dataset['sensor']\n self.max_points = dataset['max_points']\n\n self.sequences = session['split']\n self.batch_size = session['batch_size']\n self.workers = session['workers']\n self.shuffle = session['shuffle']\n self.fraction = session['fraction']\n\n # Data loading code\n self.test_dataset = SemanticKitti(root = self.root,\n sensor = self.sensor,\n sequences = self.sequences,\n max_points = self.max_points,\n #gt = gt,\n fraction = self.fraction,\n debug = debug)\n \n self.testloader = torch.utils.data.DataLoader(self.test_dataset,\n batch_size=self.batch_size,\n shuffle= self.shuffle,\n num_workers=self.workers,\n pin_memory=True,\n drop_last=False)\n\n\n def get_triplets(self):\n return(self.test_dataset.get_idx())\n\n def get_set(self):\n return self.testloader\n\n def get_test_size(self):\n return len(self.testloader)\n\n def get_param(self):\n return(self.test_dataset.get_param())\n \n def get_test_files(self):\n return(self.test_dataset.get_files())\n" ]
[ [ "numpy.fromfile", "numpy.random.seed", "torch.full", "torch.utils.data.DataLoader", "torch.from_numpy", "torch.tensor", "numpy.ones", "numpy.concatenate", "numpy.argsort", "numpy.array", "numpy.zeros", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sandeepsoni/MHP
[ "288fb56f4d2bffbda519f87320df9f49fb2465aa" ]
[ "HP/HPUtils.py" ]
[ "from __future__ import division\nimport numpy as np\n\ndef kernel (x,y,b):\n\t\"\"\" calculates the exponentially decay kernel for difference of x-y with bandwidth b\"\"\"\n\treturn np.exp (-b * (x-y))\n\ndef drawExpRV (param, rng):\n\t# using the inverse method\n\t#return (1/float (param)) * np.log (rng.uniform (0,1))\n\n\t# using the built-in numpy function\n\treturn rng.exponential (scale=param)\n\ndef attribute (uniform_rv, iStar, mlambda):\n\t# this is the recommended\n\tS = np.cumsum (mlambda) / iStar\n\treturn (uniform_rv > S).sum()\t\n\ndef attribute2 (uniform_rv, intensities):\n # The more traditional way\n\tS = np.cumsum (intensities) / np.sum (intensities)\n\treturn (uniform_rv > S).sum ()\n\ndef attribute3 (intensities):\n\t# the fast way using numpy\n\tp = intensities / np.sum (intensities)\n\treturn np.random.choice(len(intensities), 1, p=p)\t\n\n\ndef HPIntensities (mu, alpha, omega, history, t):\n\t\"\"\" returns the intensities for all dimensions as a vector at time t\"\"\"\n\tnEvents = len (history)\n\tI = np.copy(mu)\n\tfor i in xrange (nEvents):\n\t\tsrc, ts = history[i]\n\t\tI = I + alpha[src, :] * kernel (t,ts,omega[src,:])\n\n\treturn np.squeeze (I)\n" ]
[ [ "numpy.squeeze", "numpy.cumsum", "numpy.copy", "numpy.exp", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
danilkuzin/GP-EnKF
[ "215623e0f322ddae9757854e7278b60e11e570bf" ]
[ "gpenkf/experiments/real_house_prices/run.py" ]
[ "from gpenkf.experiments.experiment_runner import ExperimentRunner\nfrom gpenkf.core.parameters import Parameters\nfrom gpenkf.experiments.real_house_prices.house_data import HouseData\n\nimport numpy as np\n\nif __name__==\"__main__\":\n sample_size=1000\n data_provider = HouseData(sample_size=sample_size, validation_size=5000)\n data_provider.prepare()\n\n borders = np.array([[50, 55], [-6., 2.]])\n grid_size = 50\n\n x2 = np.linspace(borders[0, 0], borders[0, 1], grid_size)\n x1 = np.linspace(borders[1, 0], borders[1, 1], grid_size)\n x = np.stack(np.meshgrid(x1, x2), -1).reshape(-1, 2)\n grid_size =np.power(grid_size, x.shape[1])\n\n parameters = Parameters(T=50, sample_size=sample_size, grid_size=grid_size, inducing_points_locations=x, ensemble_size=500, sigma_eta=0.1,\n sigma_y=.1, init_cov=1, initial_log_gp_params=[0, 0, 0], initial_log_sigma=0,\n log_sigma_unlearnt=0, gp_hyperparams_dimensionality=3)\n\n runner = ExperimentRunner(data_provider=data_provider,\n parameters=parameters,\n algorithms=['learn_enkf_gp', 'learn_enkf_liuwest_gp', 'learn_enkf_augmented_gp'])\n runner.run()\n runner.save_results('results')" ]
[ [ "numpy.meshgrid", "numpy.array", "numpy.linspace", "numpy.power" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
BismarckBamfo/ocr-paper
[ "56a60486fb25613fc18ac984c6ca22a4475b3c4b" ]
[ "inference/utils.py" ]
[ "from __future__ import print_function\n\nimport torch\nimport pickle\nimport numpy as np\nimport math\nimport cv2\nfrom PIL import Image, JpegImagePlugin\nfrom scipy import ndimage\nimport hashlib\nimport sys, os\nfrom zipfile import ZipFile\nfrom imgproc import loadImage\n\nif sys.version_info[0] == 2:\n from six.moves.urllib.request import urlretrieve\nelse:\n from urllib.request import urlretrieve\n\ndef consecutive(data, mode ='first', stepsize=1):\n group = np.split(data, np.where(np.diff(data) != stepsize)[0]+1)\n group = [item for item in group if len(item)>0]\n\n if mode == 'first': result = [l[0] for l in group]\n elif mode == 'last': result = [l[-1] for l in group]\n return result\n\ndef word_segmentation(mat, separator_idx = {'th': [1,2],'en': [3,4]}, separator_idx_list = [1,2,3,4]):\n result = []\n sep_list = []\n start_idx = 0\n sep_lang = ''\n for sep_idx in separator_idx_list:\n if sep_idx % 2 == 0: mode ='first'\n else: mode ='last'\n a = consecutive( np.argwhere(mat == sep_idx).flatten(), mode)\n new_sep = [ [item, sep_idx] for item in a]\n sep_list += new_sep\n sep_list = sorted(sep_list, key=lambda x: x[0])\n\n for sep in sep_list:\n for lang in separator_idx.keys():\n if sep[1] == separator_idx[lang][0]: # start lang\n sep_lang = lang\n sep_start_idx = sep[0]\n elif sep[1] == separator_idx[lang][1]: # end lang\n if sep_lang == lang: # check if last entry if the same start lang\n new_sep_pair = [lang, [sep_start_idx+1, sep[0]-1]]\n if sep_start_idx > start_idx:\n result.append( ['', [start_idx, sep_start_idx-1] ] )\n start_idx = sep[0]+1\n result.append(new_sep_pair)\n sep_lang = ''# reset\n\n if start_idx <= len(mat)-1:\n result.append( ['', [start_idx, len(mat)-1] ] )\n return result\n\n# code is based from https://github.com/githubharald/CTCDecoder/blob/master/src/BeamSearch.py\nclass BeamEntry:\n \"information about one single beam at specific time-step\"\n def __init__(self):\n self.prTotal = 0 # blank and non-blank\n self.prNonBlank = 0 # non-blank\n self.prBlank = 0 # blank\n self.prText = 1 # LM score\n self.lmApplied = False # flag if LM was already applied to this beam\n self.labeling = () # beam-labeling\n self.simplified = True # To run simplyfiy label\n\nclass BeamState:\n \"information about the beams at specific time-step\"\n def __init__(self):\n self.entries = {}\n\n def norm(self):\n \"length-normalise LM score\"\n for (k, _) in self.entries.items():\n labelingLen = len(self.entries[k].labeling)\n self.entries[k].prText = self.entries[k].prText ** (1.0 / (labelingLen if labelingLen else 1.0))\n\n def sort(self):\n \"return beam-labelings, sorted by probability\"\n beams = [v for (_, v) in self.entries.items()]\n sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText)\n return [x.labeling for x in sortedBeams]\n\n def wordsearch(self, classes, ignore_idx, maxCandidate, dict_list):\n beams = [v for (_, v) in self.entries.items()]\n sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText)\n if len(sortedBeams) > maxCandidate: sortedBeams = sortedBeams[:maxCandidate]\n\n for j, candidate in enumerate(sortedBeams):\n idx_list = candidate.labeling\n text = ''\n for i,l in enumerate(idx_list):\n if l not in ignore_idx and (not (i > 0 and idx_list[i - 1] == idx_list[i])):\n text += classes[l]\n\n if j == 0: best_text = text\n if text in dict_list:\n #print('found text: ', text)\n best_text = text\n break\n else:\n pass\n #print('not in dict: ', text)\n return best_text\n\ndef applyLM(parentBeam, childBeam, classes, lm):\n \"calculate LM score of child beam by taking score from parent beam and bigram probability of last two chars\"\n if lm and not childBeam.lmApplied:\n c1 = classes[parentBeam.labeling[-1] if parentBeam.labeling else classes.index(' ')] # first char\n c2 = classes[childBeam.labeling[-1]] # second char\n lmFactor = 0.01 # influence of language model\n bigramProb = lm.getCharBigram(c1, c2) ** lmFactor # probability of seeing first and second char next to each other\n childBeam.prText = parentBeam.prText * bigramProb # probability of char sequence\n childBeam.lmApplied = True # only apply LM once per beam entry\n\ndef simplify_label(labeling, blankIdx = 0):\n labeling = np.array(labeling)\n\n # collapse blank\n idx = np.where(~((np.roll(labeling,1) == labeling) & (labeling == blankIdx)))[0]\n labeling = labeling[idx]\n\n # get rid of blank between different characters\n idx = np.where( ~((np.roll(labeling,1) != np.roll(labeling,-1)) & (labeling == blankIdx)) )[0]\n\n if len(labeling) > 0:\n last_idx = len(labeling)-1\n if last_idx not in idx: idx = np.append(idx, [last_idx])\n labeling = labeling[idx]\n\n return tuple(labeling)\n\ndef fast_simplify_label(labeling, c, blankIdx=0):\n\n # Adding BlankIDX after Non-Blank IDX\n if labeling and c == blankIdx and labeling[-1] != blankIdx:\n newLabeling = labeling + (c,)\n\n # Case when a nonBlankChar is added after BlankChar |len(char) - 1\n elif labeling and c != blankIdx and labeling[-1] == blankIdx:\n\n # If Blank between same character do nothing | As done by Simplify label\n if labeling[-2] == c:\n newLabeling = labeling + (c,)\n\n # if blank between different character, remove it | As done by Simplify Label\n else:\n newLabeling = labeling[:-1] + (c,)\n\n # if consecutive blanks : Keep the original label\n elif labeling and c == blankIdx and labeling[-1] == blankIdx:\n newLabeling = labeling\n\n # if empty beam & first index is blank\n elif not labeling and c == blankIdx:\n newLabeling = labeling\n\n # if empty beam & first index is non-blank\n elif not labeling and c != blankIdx:\n newLabeling = labeling + (c,)\n\n elif labeling and c != blankIdx:\n newLabeling = labeling + (c,)\n\n # Cases that might still require simplyfying\n else:\n newLabeling = labeling + (c,)\n newLabeling = simplify_label(newLabeling, blankIdx)\n\n return newLabeling\n\ndef addBeam(beamState, labeling):\n \"add beam if it does not yet exist\"\n if labeling not in beamState.entries:\n beamState.entries[labeling] = BeamEntry()\n\ndef ctcBeamSearch(mat, classes, ignore_idx, lm, beamWidth=25, dict_list = []):\n blankIdx = 0\n maxT, maxC = mat.shape\n\n # initialise beam state\n last = BeamState()\n labeling = ()\n last.entries[labeling] = BeamEntry()\n last.entries[labeling].prBlank = 1\n last.entries[labeling].prTotal = 1\n\n # go over all time-steps\n for t in range(maxT):\n curr = BeamState()\n # get beam-labelings of best beams\n bestLabelings = last.sort()[0:beamWidth]\n # go over best beams\n for labeling in bestLabelings:\n # probability of paths ending with a non-blank\n prNonBlank = 0\n # in case of non-empty beam\n if labeling:\n # probability of paths with repeated last char at the end\n prNonBlank = last.entries[labeling].prNonBlank * mat[t, labeling[-1]]\n\n # probability of paths ending with a blank\n prBlank = (last.entries[labeling].prTotal) * mat[t, blankIdx]\n\n # add beam at current time-step if needed\n prev_labeling = labeling\n if not last.entries[labeling].simplified:\n labeling = simplify_label(labeling, blankIdx)\n\n # labeling = simplify_label(labeling, blankIdx)\n addBeam(curr, labeling)\n\n # fill in data\n curr.entries[labeling].labeling = labeling\n curr.entries[labeling].prNonBlank += prNonBlank\n curr.entries[labeling].prBlank += prBlank\n curr.entries[labeling].prTotal += prBlank + prNonBlank\n curr.entries[labeling].prText = last.entries[prev_labeling].prText\n # beam-labeling not changed, therefore also LM score unchanged from\n\n #curr.entries[labeling].lmApplied = True # LM already applied at previous time-step for this beam-labeling\n\n # extend current beam-labeling\n # char_highscore = np.argpartition(mat[t, :], -5)[-5:] # run through 5 highest probability\n char_highscore = np.where(mat[t, :] >= 0.5/maxC)[0] # run through all probable characters\n for c in char_highscore:\n #for c in range(maxC - 1):\n # add new char to current beam-labeling\n # newLabeling = labeling + (c,)\n # newLabeling = simplify_label(newLabeling, blankIdx)\n newLabeling = fast_simplify_label(labeling, c, blankIdx)\n\n # if new labeling contains duplicate char at the end, only consider paths ending with a blank\n if labeling and labeling[-1] == c:\n prNonBlank = mat[t, c] * last.entries[prev_labeling].prBlank\n else:\n prNonBlank = mat[t, c] * last.entries[prev_labeling].prTotal\n\n # add beam at current time-step if needed\n addBeam(curr, newLabeling)\n\n # fill in data\n curr.entries[newLabeling].labeling = newLabeling\n curr.entries[newLabeling].prNonBlank += prNonBlank\n curr.entries[newLabeling].prTotal += prNonBlank\n\n # apply LM\n #applyLM(curr.entries[labeling], curr.entries[newLabeling], classes, lm)\n\n # set new beam state\n\n last = curr\n\n # normalise LM scores according to beam-labeling-length\n last.norm()\n\n if dict_list == []:\n bestLabeling = last.sort()[0] # get most probable labeling\n res = ''\n for i,l in enumerate(bestLabeling):\n # removing repeated characters and blank.\n if l not in ignore_idx and (not (i > 0 and bestLabeling[i - 1] == bestLabeling[i])):\n res += classes[l]\n else:\n res = last.wordsearch(classes, ignore_idx, 20, dict_list)\n return res\n\n\nclass AttnLabelConverter(object):\n \"\"\" Convert between text-label and text-index \"\"\"\n\n def __init__(self, character, separator_list = {}, dict_pathlist = {}):\n # character (str): set of the possible characters.\n # [GO] for the start token of the attention decoder. [s] for end-of-sentence token.\n dict_character = list(character)\n list_token = ['[GO]', '[s]'] # ['[s]','[UNK]','[PAD]','[GO]']\n \n self.character = list_token + dict_character\n\n self.dict = {}\n for i, char in enumerate(self.character):\n # print(i, char)\n self.dict[char] = i\n\n def encode(self, text, batch_max_length=25):\n \"\"\" convert text-label into text-index.\n input:\n text: text labels of each image. [batch_size]\n batch_max_length: max length of text label in the batch. 25 by default\n\n output:\n text : the input of attention decoder. [batch_size x (max_length+2)] +1 for [GO] token and +1 for [s] token.\n text[:, 0] is [GO] token and text is padded with [GO] token after [s] token.\n length : the length of output of attention decoder, which count [s] token also. [3, 7, ....] [batch_size]\n \"\"\"\n length = [len(s) + 1 for s in text] # +1 for [s] at end of sentence.\n # batch_max_length = max(length) # this is not allowed for multi-gpu setting\n batch_max_length += 1\n # additional +1 for [GO] at first step. batch_text is padded with [GO] token after [s] token.\n batch_text = torch.LongTensor(len(text), batch_max_length + 1).fill_(0)\n for i, t in enumerate(text):\n text = list(t)\n text.append('[s]')\n text = [self.dict[char] for char in text]\n batch_text[i][1:1 + len(text)] = torch.LongTensor(text) # batch_text[:, 0] = [GO] token\n return (batch_text.to(device), torch.IntTensor(length).to(device))\n\n def decode_greedy(self, text_index, length):\n \"\"\" convert text-index into text-label. \"\"\"\n texts = []\n for index, l in enumerate(length):\n text = ''.join([self.character[i] for i in text_index])\n texts.append(text)\n return texts\n\n\n\n\n\nclass CTCLabelConverter(object):\n \"\"\" Convert between text-label and text-index \"\"\"\n\n def __init__(self, character, separator_list = {}, dict_pathlist = {}):\n # character (str): set of the possible characters.\n dict_character = list(character)\n\n self.dict = {}\n for i, char in enumerate(dict_character):\n self.dict[char] = i + 1\n\n self.character = ['[blank]'] + dict_character # dummy '[blank]' token for CTCLoss (index 0)\n\n self.separator_list = separator_list\n separator_char = []\n for lang, sep in separator_list.items():\n separator_char += sep\n self.ignore_idx = [0] + [i+1 for i,item in enumerate(separator_char)]\n\n ####### latin dict\n if len(separator_list) == 0:\n dict_list = []\n for lang, dict_path in dict_pathlist.items():\n try:\n with open(dict_path, \"r\", encoding = \"utf-8-sig\") as input_file:\n word_count = input_file.read().splitlines()\n dict_list += word_count\n except:\n pass\n else:\n dict_list = {}\n for lang, dict_path in dict_pathlist.items():\n with open(dict_path, \"r\", encoding = \"utf-8-sig\") as input_file:\n word_count = input_file.read().splitlines()\n dict_list[lang] = word_count\n\n self.dict_list = dict_list\n\n def encode(self, text, batch_max_length=25):\n \"\"\"convert text-label into text-index.\n input:\n text: text labels of each image. [batch_size]\n\n output:\n text: concatenated text index for CTCLoss.\n [sum(text_lengths)] = [text_index_0 + text_index_1 + ... + text_index_(n - 1)]\n length: length of each text. [batch_size]\n \"\"\"\n length = [len(s) for s in text]\n text = ''.join(text)\n text = [self.dict[char] for char in text]\n\n return (torch.IntTensor(text), torch.IntTensor(length))\n\n def decode_greedy(self, text_index, length):\n \"\"\" convert text-index into text-label. \"\"\"\n texts = []\n index = 0\n for l in length:\n t = text_index[index:index + l]\n # Returns a boolean array where true is when the value is not repeated\n a = np.insert(~((t[1:]==t[:-1])),0,True)\n # Returns a boolean array where true is when the value is not in the ignore_idx list\n b = ~np.isin(t,np.array(self.ignore_idx))\n # Combine the two boolean array\n c = a & b\n # Gets the corresponding character according to the saved indexes\n text = ''.join(np.array(self.character)[t[c.nonzero()]])\n texts.append(text)\n index += l\n return texts\n\n def decode_beamsearch(self, mat, beamWidth=5):\n texts = []\n for i in range(mat.shape[0]):\n t = ctcBeamSearch(mat[i], self.character, self.ignore_idx, None, beamWidth=beamWidth)\n texts.append(t)\n return texts\n\n def decode_wordbeamsearch(self, mat, beamWidth=5):\n texts = []\n argmax = np.argmax(mat, axis = 2)\n\n for i in range(mat.shape[0]):\n string = ''\n # without separators - use space as separator\n if len(self.separator_list) == 0:\n space_idx = self.dict[' ']\n\n data = np.argwhere(argmax[i]!=space_idx).flatten()\n group = np.split(data, np.where(np.diff(data) != 1)[0]+1)\n group = [ list(item) for item in group if len(item)>0]\n\n for j, list_idx in enumerate(group):\n matrix = mat[i, list_idx,:]\n t = ctcBeamSearch(matrix, self.character, self.ignore_idx, None,\\\n beamWidth=beamWidth, dict_list=self.dict_list)\n if j == 0: string += t\n else: string += ' '+t\n\n # with separators\n else:\n words = word_segmentation(argmax[i])\n\n for word in words:\n matrix = mat[i, word[1][0]:word[1][1]+1,:]\n if word[0] == '': dict_list = []\n else: dict_list = self.dict_list[word[0]]\n t = ctcBeamSearch(matrix, self.character, self.ignore_idx, None, beamWidth=beamWidth, dict_list=dict_list)\n string += t\n texts.append(string)\n return texts\n\ndef four_point_transform(image, rect):\n (tl, tr, br, bl) = rect\n\n widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))\n widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))\n maxWidth = max(int(widthA), int(widthB))\n\n # compute the height of the new image, which will be the\n # maximum distance between the top-right and bottom-right\n # y-coordinates or the top-left and bottom-left y-coordinates\n heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))\n heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))\n maxHeight = max(int(heightA), int(heightB))\n\n dst = np.array([[0, 0],[maxWidth - 1, 0],[maxWidth - 1, maxHeight - 1],[0, maxHeight - 1]], dtype = \"float32\")\n\n # compute the perspective transform matrix and then apply it\n M = cv2.getPerspectiveTransform(rect, dst)\n warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))\n\n return warped\n\ndef group_text_box(polys, slope_ths = 0.1, ycenter_ths = 0.5, height_ths = 0.5, width_ths = 1.0, add_margin = 0.05, sort_output = True):\n # poly top-left, top-right, low-right, low-left\n horizontal_list, free_list,combined_list, merged_list = [],[],[],[]\n\n for poly in polys:\n slope_up = (poly[3]-poly[1])/np.maximum(10, (poly[2]-poly[0]))\n slope_down = (poly[5]-poly[7])/np.maximum(10, (poly[4]-poly[6]))\n if max(abs(slope_up), abs(slope_down)) < slope_ths:\n x_max = max([poly[0],poly[2],poly[4],poly[6]])\n x_min = min([poly[0],poly[2],poly[4],poly[6]])\n y_max = max([poly[1],poly[3],poly[5],poly[7]])\n y_min = min([poly[1],poly[3],poly[5],poly[7]])\n horizontal_list.append([x_min, x_max, y_min, y_max, 0.5*(y_min+y_max), y_max-y_min])\n else:\n height = np.linalg.norm([poly[6]-poly[0],poly[7]-poly[1]])\n width = np.linalg.norm([poly[2]-poly[0],poly[3]-poly[1]])\n\n margin = int(1.44*add_margin*min(width, height))\n\n theta13 = abs(np.arctan( (poly[1]-poly[5])/np.maximum(10, (poly[0]-poly[4]))))\n theta24 = abs(np.arctan( (poly[3]-poly[7])/np.maximum(10, (poly[2]-poly[6]))))\n # do I need to clip minimum, maximum value here?\n x1 = poly[0] - np.cos(theta13)*margin\n y1 = poly[1] - np.sin(theta13)*margin\n x2 = poly[2] + np.cos(theta24)*margin\n y2 = poly[3] - np.sin(theta24)*margin\n x3 = poly[4] + np.cos(theta13)*margin\n y3 = poly[5] + np.sin(theta13)*margin\n x4 = poly[6] - np.cos(theta24)*margin\n y4 = poly[7] + np.sin(theta24)*margin\n\n free_list.append([[x1,y1],[x2,y2],[x3,y3],[x4,y4]])\n if sort_output:\n horizontal_list = sorted(horizontal_list, key=lambda item: item[4])\n\n # combine box\n new_box = []\n for poly in horizontal_list:\n\n if len(new_box) == 0:\n b_height = [poly[5]]\n b_ycenter = [poly[4]]\n new_box.append(poly)\n else:\n # comparable height and comparable y_center level up to ths*height\n if abs(np.mean(b_ycenter) - poly[4]) < ycenter_ths*np.mean(b_height):\n b_height.append(poly[5])\n b_ycenter.append(poly[4])\n new_box.append(poly)\n else:\n b_height = [poly[5]]\n b_ycenter = [poly[4]]\n combined_list.append(new_box)\n new_box = [poly]\n combined_list.append(new_box)\n\n # merge list use sort again\n for boxes in combined_list:\n if len(boxes) == 1: # one box per line\n box = boxes[0]\n margin = int(add_margin*min(box[1]-box[0],box[5]))\n merged_list.append([box[0]-margin,box[1]+margin,box[2]-margin,box[3]+margin])\n else: # multiple boxes per line\n boxes = sorted(boxes, key=lambda item: item[0])\n\n merged_box, new_box = [],[]\n for box in boxes:\n if len(new_box) == 0:\n b_height = [box[5]]\n x_max = box[1]\n new_box.append(box)\n else:\n if (abs(np.mean(b_height) - box[5]) < height_ths*np.mean(b_height)) and ((box[0]-x_max) < width_ths *(box[3]-box[2])): # merge boxes\n b_height.append(box[5])\n x_max = box[1]\n new_box.append(box)\n else:\n b_height = [box[5]]\n x_max = box[1]\n merged_box.append(new_box)\n new_box = [box]\n if len(new_box) >0: merged_box.append(new_box)\n\n for mbox in merged_box:\n if len(mbox) != 1: # adjacent box in same line\n # do I need to add margin here?\n x_min = min(mbox, key=lambda x: x[0])[0]\n x_max = max(mbox, key=lambda x: x[1])[1]\n y_min = min(mbox, key=lambda x: x[2])[2]\n y_max = max(mbox, key=lambda x: x[3])[3]\n\n box_width = x_max - x_min\n box_height = y_max - y_min\n margin = int(add_margin * (min(box_width, box_height)))\n\n merged_list.append([x_min-margin, x_max+margin, y_min-margin, y_max+margin])\n else: # non adjacent box in same line\n box = mbox[0]\n\n box_width = box[1] - box[0]\n box_height = box[3] - box[2]\n margin = int(add_margin * (min(box_width, box_height)))\n\n merged_list.append([box[0]-margin,box[1]+margin,box[2]-margin,box[3]+margin])\n # may need to check if box is really in image\n return merged_list, free_list\n\ndef calculate_ratio(width,height):\n '''\n Calculate aspect ratio for normal use case (w>h) and vertical text (h>w)\n '''\n ratio = width/height\n if ratio<1.0:\n ratio = 1./ratio\n return ratio\n\ndef compute_ratio_and_resize(img,width,height,model_height):\n '''\n Calculate ratio and resize correctly for both horizontal text\n and vertical case\n '''\n ratio = width/height\n if ratio<1.0:\n ratio = calculate_ratio(width,height)\n img = cv2.resize(img,(model_height,int(model_height*ratio)), interpolation=Image.ANTIALIAS)\n else:\n img = cv2.resize(img,(int(model_height*ratio),model_height),interpolation=Image.ANTIALIAS)\n return img,ratio\n\n\ndef get_image_list(horizontal_list, free_list, img, model_height = 64, sort_output = True):\n image_list = []\n maximum_y,maximum_x = img.shape\n\n max_ratio_hori, max_ratio_free = 1,1\n for box in free_list:\n rect = np.array(box, dtype = \"float32\")\n transformed_img = four_point_transform(img, rect)\n ratio = calculate_ratio(transformed_img.shape[1],transformed_img.shape[0])\n new_width = int(model_height*ratio)\n if new_width == 0:\n pass\n else:\n crop_img,ratio = compute_ratio_and_resize(transformed_img,transformed_img.shape[1],transformed_img.shape[0],model_height)\n image_list.append( (box,crop_img) ) # box = [[x1,y1],[x2,y2],[x3,y3],[x4,y4]]\n max_ratio_free = max(ratio, max_ratio_free)\n\n\n max_ratio_free = math.ceil(max_ratio_free)\n\n for box in horizontal_list:\n x_min = max(0,box[0])\n x_max = min(box[1],maximum_x)\n y_min = max(0,box[2])\n y_max = min(box[3],maximum_y)\n crop_img = img[y_min : y_max, x_min:x_max]\n width = x_max - x_min\n height = y_max - y_min\n ratio = calculate_ratio(width,height)\n new_width = int(model_height*ratio)\n if new_width == 0:\n pass\n else:\n crop_img,ratio = compute_ratio_and_resize(crop_img,width,height,model_height)\n image_list.append( ( [[x_min,y_min],[x_max,y_min],[x_max,y_max],[x_min,y_max]] ,crop_img) )\n max_ratio_hori = max(ratio, max_ratio_hori)\n\n max_ratio_hori = math.ceil(max_ratio_hori)\n max_ratio = max(max_ratio_hori, max_ratio_free)\n max_width = math.ceil(max_ratio)*model_height\n\n if sort_output:\n image_list = sorted(image_list, key=lambda item: item[0][0][1]) # sort by vertical position\n return image_list, max_width\n\ndef download_and_unzip(url, filename, model_storage_directory, verbose=True):\n zip_path = os.path.join(model_storage_directory, 'temp.zip')\n reporthook = printProgressBar(prefix='Progress:', suffix='Complete', length=50) if verbose else None\n urlretrieve(url, zip_path, reporthook=reporthook)\n with ZipFile(zip_path, 'r') as zipObj:\n zipObj.extract(filename, model_storage_directory)\n os.remove(zip_path)\n\ndef calculate_md5(fname):\n hash_md5 = hashlib.md5()\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\ndef diff(input_list):\n return max(input_list)-min(input_list)\n\ndef get_paragraph(raw_result, x_ths=1, y_ths=0.5, mode = 'ltr'):\n # create basic attributes\n box_group = []\n for box in raw_result:\n all_x = [int(coord[0]) for coord in box[0]]\n all_y = [int(coord[1]) for coord in box[0]]\n min_x = min(all_x)\n max_x = max(all_x)\n min_y = min(all_y)\n max_y = max(all_y)\n height = max_y - min_y\n box_group.append([box[1], min_x, max_x, min_y, max_y, height, 0.5*(min_y+max_y), 0]) # last element indicates group\n # cluster boxes into paragraph\n current_group = 1\n while len([box for box in box_group if box[7]==0]) > 0:\n box_group0 = [box for box in box_group if box[7]==0] # group0 = non-group\n # new group\n if len([box for box in box_group if box[7]==current_group]) == 0:\n box_group0[0][7] = current_group # assign first box to form new group\n # try to add group\n else:\n current_box_group = [box for box in box_group if box[7]==current_group]\n mean_height = np.mean([box[5] for box in current_box_group])\n min_gx = min([box[1] for box in current_box_group]) - x_ths*mean_height\n max_gx = max([box[2] for box in current_box_group]) + x_ths*mean_height\n min_gy = min([box[3] for box in current_box_group]) - y_ths*mean_height\n max_gy = max([box[4] for box in current_box_group]) + y_ths*mean_height\n add_box = False\n for box in box_group0:\n same_horizontal_level = (min_gx<=box[1]<=max_gx) or (min_gx<=box[2]<=max_gx)\n same_vertical_level = (min_gy<=box[3]<=max_gy) or (min_gy<=box[4]<=max_gy)\n if same_horizontal_level and same_vertical_level:\n box[7] = current_group\n add_box = True\n break\n # cannot add more box, go to next group\n if add_box==False:\n current_group += 1\n # arrage order in paragraph\n result = []\n for i in set(box[7] for box in box_group):\n current_box_group = [box for box in box_group if box[7]==i]\n mean_height = np.mean([box[5] for box in current_box_group])\n min_gx = min([box[1] for box in current_box_group])\n max_gx = max([box[2] for box in current_box_group])\n min_gy = min([box[3] for box in current_box_group])\n max_gy = max([box[4] for box in current_box_group])\n\n text = ''\n while len(current_box_group) > 0:\n highest = min([box[6] for box in current_box_group])\n candidates = [box for box in current_box_group if box[6]<highest+0.4*mean_height]\n # get the far left\n if mode == 'ltr':\n most_left = min([box[1] for box in candidates])\n for box in candidates:\n if box[1] == most_left: best_box = box\n elif mode == 'rtl':\n most_right = max([box[2] for box in candidates])\n for box in candidates:\n if box[2] == most_right: best_box = box\n text += ' '+best_box[0]\n current_box_group.remove(best_box)\n\n result.append([ [[min_gx,min_gy],[max_gx,min_gy],[max_gx,max_gy],[min_gx,max_gy]], text[1:]])\n\n return result\n\n\ndef printProgressBar(prefix='', suffix='', decimals=1, length=100, fill='█'):\n \"\"\"\n Call in a loop to create terminal progress bar\n @params:\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent complete (Int)\n length - Optional : character length of bar (Int)\n fill - Optional : bar fill character (Str)\n printEnd - Optional : end character (e.g. \"\\r\", \"\\r\\n\") (Str)\n \"\"\"\n def progress_hook(count, blockSize, totalSize):\n progress = count * blockSize / totalSize\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(progress * 100)\n filledLength = int(length * progress)\n bar = fill * filledLength + '-' * (length - filledLength)\n print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end='')\n\n return progress_hook\n\ndef reformat_input(image):\n if type(image) == str:\n if image.startswith('http://') or image.startswith('https://'):\n tmp, _ = urlretrieve(image , reporthook=printProgressBar(prefix = 'Progress:', suffix = 'Complete', length = 50))\n img_cv_grey = cv2.imread(tmp, cv2.IMREAD_GRAYSCALE)\n os.remove(tmp)\n else:\n img_cv_grey = cv2.imread(image, cv2.IMREAD_GRAYSCALE)\n image = os.path.expanduser(image)\n img = loadImage(image) # can accept URL\n elif type(image) == bytes:\n nparr = np.frombuffer(image, np.uint8)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img_cv_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n elif type(image) == np.ndarray:\n if len(image.shape) == 2: # grayscale\n img_cv_grey = image\n img = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)\n elif len(image.shape) == 3 and image.shape[2] == 1:\n img_cv_grey = np.squeeze(image)\n img = cv2.cvtColor(img_cv_grey, cv2.COLOR_GRAY2BGR)\n elif len(image.shape) == 3 and image.shape[2] == 3: # BGRscale\n img = image\n img_cv_grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n elif len(image.shape) == 3 and image.shape[2] == 4: # RGBAscale\n img = image[:,:,:3]\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n img_cv_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n elif type(image) == JpegImagePlugin.JpegImageFile:\n image_array = np.array(image)\n img = cv2.cvtColor(image_array, cv2.COLOR_RGB2BGR)\n img_cv_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n else:\n raise ValueError('Invalid input type. Supporting format = string(file path or url), bytes, numpy array')\n\n return img, img_cv_grey\n\n\ndef reformat_input_batched(image, n_width=None, n_height=None):\n \"\"\"\n reformats an image or list of images or a 4D numpy image array &\n returns a list of corresponding img, img_cv_grey nd.arrays\n image:\n [file path, numpy-array, byte stream object,\n list of file paths, list of numpy-array, 4D numpy array,\n list of byte stream objects]\n \"\"\"\n if ((isinstance(image, np.ndarray) and len(image.shape) == 4) or isinstance(image, list)):\n # process image batches if image is list of image np arr, paths, bytes\n img, img_cv_grey = [], []\n for single_img in image:\n clr, gry = reformat_input(single_img)\n if n_width is not None and n_height is not None:\n clr = cv2.resize(clr, (n_width, n_height))\n gry = cv2.resize(gry, (n_width, n_height))\n img.append(clr)\n img_cv_grey.append(gry)\n img, img_cv_grey = np.array(img), np.array(img_cv_grey)\n # ragged tensors created when all input imgs are not of the same size\n if len(img.shape) == 1 and len(img_cv_grey.shape) == 1:\n raise ValueError(\"The input image array contains images of different sizes. \" +\n \"Please resize all images to same shape or pass n_width, n_height to auto-resize\")\n else:\n img, img_cv_grey = reformat_input(image)\n return img, img_cv_grey\n\n\n\ndef make_rotated_img_list(rotationInfo, img_list):\n\n result_img_list = img_list[:]\n\n # add rotated images to original image_list\n max_ratio=1\n \n for angle in rotationInfo:\n for img_info in img_list : \n rotated = ndimage.rotate(img_info[1], angle, reshape=True) \n height,width = rotated.shape\n ratio = calculate_ratio(width,height)\n max_ratio = max(max_ratio,ratio)\n result_img_list.append((img_info[0], rotated))\n return result_img_list\n\n\ndef set_result_with_confidence(results):\n \"\"\" Select highest confidence augmentation for TTA\n Given a list of lists of results (outer list has one list per augmentation,\n inner lists index the images being recognized), choose the best result \n according to confidence level.\n Each \"result\" is of the form (box coords, text, confidence)\n A final_result is returned which contains one result for each image\n \"\"\"\n final_result = []\n for col_ix in range(len(results[0])):\n # Take the row_ix associated with the max confidence\n best_row = max(\n [(row_ix, results[row_ix][col_ix][2]) for row_ix in range(len(results))],\n key=lambda x: x[1])[0]\n final_result.append(results[best_row][col_ix])\n\n return final_result\n\nclass AttrDict(dict):\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self\n\nclass Averager(object):\n \"\"\"Compute average for torch.Tensor, used for loss average.\"\"\"\n\n def __init__(self):\n self.reset()\n\n def add(self, v):\n count = v.data.numel()\n v = v.data.sum()\n self.n_count += count\n self.sum += v\n\n def reset(self):\n self.n_count = 0\n self.sum = 0\n\n def val(self):\n res = 0\n if self.n_count != 0:\n res = self.sum / float(self.n_count)\n return res\n" ]
[ [ "numpy.sqrt", "numpy.squeeze", "numpy.mean", "numpy.where", "numpy.roll", "numpy.sin", "numpy.frombuffer", "numpy.argmax", "numpy.diff", "numpy.insert", "torch.LongTensor", "scipy.ndimage.rotate", "numpy.append", "numpy.array", "numpy.maximum", "numpy.linalg.norm", "numpy.cos", "numpy.argwhere", "torch.IntTensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
aferrall/redner
[ "be52e4105140f575f153d640ba889eb6e6015616" ]
[ "tests/test_teapot_reflectance.py" ]
[ "import pyredner\nimport numpy as np\nimport torch\nimport scipy\nimport scipy.ndimage\n\n# Optimize for material parameters and camera pose\n\n# Use GPU if available\npyredner.set_use_gpu(torch.cuda.is_available())\n\n# Load the scene from a Mitsuba scene file\nscene = pyredner.load_mitsuba('scenes/teapot.xml')\n\n# The last material is the teapot material, set it to the target\nscene.materials[-1].diffuse_reflectance = \\\n pyredner.Texture(torch.tensor([0.3, 0.2, 0.2], device = pyredner.get_device()))\nscene.materials[-1].specular_reflectance = \\\n pyredner.Texture(torch.tensor([0.6, 0.6, 0.6], device = pyredner.get_device()))\nscene.materials[-1].roughness = \\\n pyredner.Texture(torch.tensor([0.05], device = pyredner.get_device()))\nargs = pyredner.RenderFunction.serialize_scene(\\\n scene = scene,\n num_samples = 1024,\n max_bounces = 2)\n\n# Alias of the render function\nrender = pyredner.RenderFunction.apply\n# Render our target. The first argument is the seed for RNG in the renderer.\nimg = render(0, *args)\npyredner.imwrite(img.cpu(), 'results/test_teapot_reflectance/target.exr')\npyredner.imwrite(img.cpu(), 'results/test_teapot_reflectance/target.png')\ntarget = pyredner.imread('results/test_teapot_reflectance/target.exr')\nif pyredner.get_use_gpu():\n target = target.cuda(device = pyredner.get_device())\n\n# Perturb the scene, this is our initial guess\ncam = scene.camera\ncam_position = cam.position\ncam_translation = torch.tensor([-0.2, 0.2, -0.2], requires_grad = True)\ndiffuse_reflectance = torch.tensor([0.3, 0.3, 0.3],\n device = pyredner.get_device(), requires_grad = True)\nspecular_reflectance = torch.tensor([0.5, 0.5, 0.5],\n device = pyredner.get_device(), requires_grad = True)\nroughness = torch.tensor([0.2],\n device = pyredner.get_device(), requires_grad = True)\nscene.materials[-1].diffuse_reflectance = pyredner.Texture(diffuse_reflectance)\nscene.materials[-1].specular_reflectance = pyredner.Texture(specular_reflectance)\nscene.materials[-1].roughness = pyredner.Texture(roughness)\nscene.camera = pyredner.Camera(position = cam_position + cam_translation,\n look_at = cam.look_at + cam_translation,\n up = cam.up,\n fov = cam.fov,\n clip_near = cam.clip_near,\n resolution = cam.resolution,\n fisheye = False)\nargs = pyredner.RenderFunction.serialize_scene(\\\n scene = scene,\n num_samples = 1024,\n max_bounces = 2)\n# Render the initial guess\nimg = render(1, *args)\npyredner.imwrite(img.cpu(), 'results/test_teapot_reflectance/init.png')\ndiff = torch.abs(target - img)\npyredner.imwrite(diff.cpu(), 'results/test_teapot_reflectance/init_diff.png')\n\nlr_base = 1e-2\nlr = lr_base\noptimizer = torch.optim.Adam([diffuse_reflectance,\n specular_reflectance,\n roughness,\n cam_translation], lr=lr)\nnum_iteration = 400\nfor t in range(num_iteration):\n print('iteration:', t)\n optimizer.zero_grad()\n # Forward pass: render the image\n # need to rerun Camera constructor for autodiff \n scene.camera = pyredner.Camera(position = cam_position + cam_translation,\n look_at = cam.look_at + cam_translation,\n up = cam.up,\n fov = cam.fov,\n clip_near = cam.clip_near,\n resolution = cam.resolution,\n fisheye = False)\n args = pyredner.RenderFunction.serialize_scene(\\\n scene = scene,\n num_samples = 4,\n max_bounces = 2)\n img = render(t+1, *args)\n pyredner.imwrite(img.cpu(), 'results/test_teapot_reflectance/iter_{}.png'.format(t))\n #loss = (img - target).pow(2).sum()\n\n diff = img - target\n dirac = np.zeros([7,7], dtype = np.float32)\n dirac[3,3] = 1.0\n dirac = torch.from_numpy(dirac)\n f = np.zeros([3, 3, 7, 7], dtype = np.float32)\n gf = scipy.ndimage.filters.gaussian_filter(dirac, 1.0)\n f[0, 0, :, :] = gf\n f[1, 1, :, :] = gf\n f[2, 2, :, :] = gf\n f = torch.from_numpy(f)\n if pyredner.get_use_gpu():\n f = f.cuda(device = pyredner.get_device())\n m = torch.nn.AvgPool2d(2)\n r = 256\n diff_0 = (img - target).view(1, r, r, 3).permute(0, 3, 2, 1)\n diff_1 = m(torch.nn.functional.conv2d(diff_0, f, padding=3))\n diff_2 = m(torch.nn.functional.conv2d(diff_1, f, padding=3))\n diff_3 = m(torch.nn.functional.conv2d(diff_2, f, padding=3))\n diff_4 = m(torch.nn.functional.conv2d(diff_3, f, padding=3))\n diff_5 = m(torch.nn.functional.conv2d(diff_4, f, padding=3))\n loss = diff_0.pow(2).sum() / (r*r) + \\\n diff_1.pow(2).sum() / ((r/2)*(r/2)) + \\\n diff_2.pow(2).sum() / ((r/4)*(r/4)) + \\\n diff_3.pow(2).sum() / ((r/8)*(r/8)) + \\\n diff_4.pow(2).sum() / ((r/16)*(r/16)) + \\\n diff_5.pow(2).sum() / ((r/32)*(r/32))\n\n print('loss:', loss.item())\n\n loss.backward()\n print('diffuse_reflectance.grad:', diffuse_reflectance.grad)\n print('specular_reflectance.grad:', specular_reflectance.grad)\n print('roughness.grad:', roughness.grad)\n print('cam_translation.grad:', cam_translation.grad)\n\n # HACK: gradient clipping to deal with outlier gradients\n torch.nn.utils.clip_grad_norm_(roughness, 10)\n torch.nn.utils.clip_grad_norm_(cam_translation, 10)\n\n optimizer.step()\n\n print('diffuse_reflectance:', diffuse_reflectance)\n print('specular_reflectance:', specular_reflectance)\n print('roughness:', roughness)\n print('cam_translation:', cam_translation)\n\n # Linearly reduce the learning rate\n #lr = lr_base * float(num_iteration - t) / float(num_iteration)\n #for param_group in optimizer.param_groups:\n # param_group['lr'] = lr\n\nargs = pyredner.RenderFunction.serialize_scene(\\\n scene = scene,\n num_samples = 1024,\n max_bounces = 2)\nimg = render(num_iteration + 2, *args)\npyredner.imwrite(img.cpu(), 'results/test_teapot_reflectance/final.exr')\npyredner.imwrite(img.cpu(), 'results/test_teapot_reflectance/final.png')\npyredner.imwrite(torch.abs(target - img).cpu(), 'results/test_teapot_reflectance/final_diff.png')\n\nfrom subprocess import call\ncall([\"ffmpeg\", \"-framerate\", \"24\", \"-i\",\n \"results/test_teapot_reflectance/iter_%d.png\", \"-vb\", \"20M\",\n \"results/test_teapot_reflectance/out.mp4\"])\n" ]
[ [ "torch.optim.Adam", "torch.abs", "torch.nn.functional.conv2d", "torch.from_numpy", "torch.tensor", "torch.nn.utils.clip_grad_norm_", "torch.nn.AvgPool2d", "scipy.ndimage.filters.gaussian_filter", "torch.cuda.is_available", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "0.15", "1.4", "0.16", "1.0", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "0.10", "0.17", "1.3" ], "tensorflow": [] } ]
akthiersch-01/DATS6103-Project-Team1
[ "0abf4114f85c500a2740c097f9abe435df1a5b37" ]
[ "Diabetes_Project 2.py" ]
[ "#%%\n#Import packages\nimport numpy as np\nimport pandas as pd\nimport os\nimport mlxtend\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport math \nimport scipy.stats as stats\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix \nfrom sklearn.metrics import classification_report\nfrom sklearn.linear_model import LogisticRegression\nfrom mlxtend.plotting import plot_decision_regions\nfrom sklearn import linear_model\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom statsmodels.stats.weightstats import ztest as ztest\n\n#%%\n#Let's define some key functions here that'll help us throughout the rest of this\n\n#Violin plot function\ndef violin_plot_func(data, cat_col, cont_col):\n '''\n Function will take in a dataset and two column names, one categorical and one continuous\n Data: name of pandas dataframe containing the columns\n cat_col: name of column that will be used to split the violin plots\n cont_col: continuous function'''\n for i in range(len(data[cat_col].unique())):\n globals()['group%s' % i] = data[data[cat_col]==i]\n cat_list = []\n for i in range(len(data[cat_col].unique())):\n cat_list.append(list(globals()['group%s' % i][cont_col]))\n pos = np.arange(1,len(data[cat_col].unique())+1)\n pos_list = np.ndarray.tolist(pos)\n plt.violinplot(cat_list, positions = pos_list)\n plt.xlabel(cat_col)\n plt.ylabel(cont_col)\n plt.show()\n\n#Scatter plot function\n\n\n#Contingency table/heat map functions - non-proportional\ndef categorical_contigency_base(group1, group2):\n '''\n Function will combine two categorical variables into a contingency table, and then output a heatmap showing both the numbers and a color scheme to represent equality across the cells. Includes margins\n input group1, group2\n group1: categorical variable\n group2: categorical variable\n output: heatmap showing the contingency table with appropriate coloring\n Group here refers to categorical, but not individual level'''\n data_contingency = pd.crosstab(group1, group2, margins = True, margins_name = 'Total')\n print(data_contingency)\n data_contingency=pd.crosstab(group1, group2, margins = False, margins_name = 'Total')\n f, ax = plt.subplots(figsize=(9, 6))\n sns.heatmap(data_contingency, annot=True, fmt=\"d\", linewidths=.5, ax=ax)\n plt.show()\n return\n\n#Contingency table/heat map functions - overall proportional\ndef categorical_contigency_prop_whole(group1, group2):\n '''\n Function will combine two categorical variables into a contingency table, and then output a heatmap showing both the numbers and a color scheme to represent equality across the cells. Includes margins\n input group1, group2\n group1: categorical variable\n group2: categorical variable\n output: heatmap showing the contingency table with appropriate coloring\n Group here refers to categorical, but not individual level\n If there is an error, try switching group1 and group2'''\n data_contingency = pd.crosstab(group1, group2, margins = True, margins_name = 'Total')\n columns = group1.unique()\n rows = group2.unique()\n df = pd.DataFrame()\n for i in rows:\n for j in columns:\n proportion = data_contingency[i][j]/data_contingency['Total'][\"Total\"]\n df.loc[i,j]=proportion\n df=df.transpose()\n f, ax = plt.subplots(figsize=(9, 6))\n sns.heatmap(df, annot=True, fmt=\"f\", linewidths=.5, ax=ax)\n plt.show()\n return\n\n#Contingency table/heat map functions - column proportional\ndef categorical_contigency_prop_col(group1, group2):\n '''\n Function will combine two categorical variables into a contingency table, and then output a heatmap showing both the numbers and a color scheme to represent equality across the cells. Includes margins\n input group1, group2\n group1: categorical variable\n group2: categorical variable\n output: heatmap showing the contingency table with appropriate coloring\n Group here refers to categorical, but not individual level'''\n data_contingency = pd.crosstab(group1, group2, margins = True, margins_name = 'Total')\n columns = group1.unique()\n rows = group2.unique()\n df = pd.DataFrame()\n for i in rows:\n for j in columns:\n proportion = data_contingency[i][j]/data_contingency[i][\"Total\"]\n df.loc[i,j]=proportion\n df=df.transpose()\n f, ax = plt.subplots(figsize=(9, 6))\n sns.heatmap(df, annot=True, fmt=\"f\", linewidths=.5, ax=ax)\n plt.show()\n return\n\n\n#Contingency table/heat map functions - row proportional\ndef categorical_contigency_prop_row(group1, group2):\n '''\n Function will combine two categorical variables into a contingency table, and then output a heatmap showing both the numbers and a color scheme to represent equality across the cells. Includes margins\n input group1, group2\n group1: categorical variable\n group2: categorical variable\n output: heatmap showing the contingency table with appropriate coloring\n Group here refers to categorical, but not individual level'''\n data_contingency = pd.crosstab(group1, group2, margins = True, margins_name = 'Total')\n columns = group1.unique()\n rows = group2.unique()\n df = pd.DataFrame()\n for i in rows:\n for j in columns:\n proportion = data_contingency[i][j]/data_contingency['Total'][j]\n df.loc[i,j]=proportion\n df=df.transpose()\n f, ax = plt.subplots(figsize=(9, 6))\n sns.heatmap(df, annot=True, fmt=\"f\", linewidths=.5, ax=ax)\n plt.show()\n return\n\n#Chi-square test function (for testing impact of categorical data on our outcome variables)\ndef chi_square_test(group1, group2, alpha = 0.05, decimals = 3):\n '''\n Function will combine two categorical variables into a contingency table, and then output a two sided hypothesis test for independence with the chi-square statistic, p-value, and hypothesis test conclusion\n group1: categorical variable\n group2: categorical variable\n alpha: cutoff for p-value, number between 0 and 1, defaults to 0.05 or a 5% cutoff\n decimals: preferred rounding number for chi-square and p-value\n output: chi-square statistic, p-value, and hypothesis test conclusion\n Group here refers to categorical, but not individual level'''\n data_contingency = pd.crosstab(group1, group2, margins = True, margins_name = 'Total')\n chi_square = 0\n columns = group1.unique()\n rows = group2.unique()\n for i in rows:\n for j in columns:\n O = data_contingency[i][j]\n E = data_contingency[i]['Total'] * data_contingency['Total'][j] / data_contingency['Total']['Total']\n chi_square += (O-E)**2/E\n p_value = 1 - stats.chi2.cdf(chi_square, (len(rows)-1)*(len(columns)-1))\n conclusion = \"Failed to reject the null hypothesis.\"\n if p_value <= alpha:\n conclusion = \"Null Hypothesis is rejected.\"\n \n print(\"chisquare-score is:\", round(chi_square,decimals), \" and p value is:\", round(p_value,decimals))\n return(conclusion)\n\n#two sample Z-test function (for testing impact of continuous data based on diabetes_012)\ndef two_sample_test(group1, group2, alpha = 0.05, decimals = 3):\n '''\n input group1, group 2, alpha, decimals\n group 1: qualitative variable corresponding to the first group (ie female)\n group 2: qualitative variable corresponding to the second group (ie male)\n alpha: cutoff for p-value, number between 0 and 1, defaults to 0.05 or a 5% cutoff\n decimals: preferred rounding number for z-score and p-value\n outputs: z_score and p_value, plus hypothesis testing determination\n Note: If there are more than 2 levels of a category, it is necessary to run the function for each respective pair of values\n '''\n ztest_vals = ztest(group1, group2)\n z_stat = round(ztest_vals[0],decimals)\n p_value = round(ztest_vals[1],decimals)\n if p_value < 0.05:\n \n print (f\"Your z-score was {z_stat} and your p-value was {p_value}, which is less than 0.05. We therefore reject our null hypothesis\")\n else:\n print (f\"Your z-score was {z_stat} and your p-value was {p_value}, which is greater than 0.05. We therefore fail to reject our null hypothesis\")\n return \n\n\n\n\n#%%\n#Read in csv\ndiabetes = pd.read_csv('diabetes_012_health_indicators_BRFSS2015.csv')\n\n#Testing the functions work\n# categorical_contigency_base(diabetes['Diabetes_012'], diabetes['HighBP'])\n# categorical_contigency_prop_whole(diabetes['Diabetes_012'], diabetes['HighBP'])\n# categorical_contigency_prop_col(diabetes['Diabetes_012'], diabetes['HighBP'])\n# categorical_contigency_prop_row(diabetes['Diabetes_012'], diabetes['HighBP'])\n# chi_square_test(diabetes['Diabetes_012'], diabetes['HighBP'])\n# violin_plot_func(diabetes, 'Diabetes_012', 'Age')\n# two_sample_test(diabetes[diabetes['Diabetes_012']==0]['Age'], diabetes[diabetes['Diabetes_012']==1]['Age'])\n# %%\n#Let's add basic summary information here (proportions, averages, etc.)\n\n#%%\n#Let's add some summary visualizations here using our few continuous variables. We can put Diabetes_012 as the color and use shape for some other things, or we can make violin plots with diabetes_012 as the splits and maybe do double splits\n\n#%%\n#Let's do some contingency tables/heat maps here and could consider proportions.\n\n#%%\n#Test/Train split - we have sufficient data to do a 9/1 or a 4/1 (probably a 4/1 since pre-diabetes is a relatively small category). Make sure we set the random state here so we can repeat it\n#%%\n#First, let's build a basic logistic regression, we'll need to either use sklearn or the function Prof. Lo gave us in quiz 3 for a multinomial response variable\n\n#Model Building - Logistic\n\n#Model summary information (including pseudo-R^2)\n#Loop with different cutoff values showing score and confusion matrix\n\n#ROC-AUC\n\n\n#%%\n#Start building more complicated models\n#Model Building - Trees, SVM, etc.\n\n#Information regarding fit and accuracy\n\n\n#%%\n#Comparison of all models to determine which variables had the largest impacts and which model was best" ]
[ [ "pandas.crosstab", "pandas.read_csv", "matplotlib.pyplot.subplots", "pandas.DataFrame", "matplotlib.pyplot.violinplot", "numpy.ndarray.tolist", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Fusion-Data-Platform/fdp
[ "d87a52207238f168ed69b9f96dc8f20f4481366d" ]
[ "fdp/methods/diiid/bes/utilities.py" ]
[ "import numpy as np\n\ndef shift_dc_signal(obj, data):\n if obj.isSignal() and obj._parent._name=='slow':\n data = data - np.mean(data[0:100])\n return data" ]
[ [ "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
liewmanchoi/NaiveMLA
[ "fea7d6ce9650fb5ff7e31140fd584792dd0d7a2a" ]
[ "unsupervised_learning/kmeans.py" ]
[ "# -*- coding: utf-8 -*-\n# __author__ = wangsheng\n# __copyright__ = \"Copyright 2018, Trump Organization\"\n# __email__ = \"[email protected]\"\n# __status__ = \"experiment\"\n# __time__ = 2018/12/9 10:05\n# __file__ = kmeans.py\n\nimport numpy as np\n\n\nclass KMeans(object):\n def __init__(self, n_clusters: int = 8, max_iter: int = 300):\n self._n_clusters: int = n_clusters\n self._max_iter: int = max_iter\n self._cluster_centers: np.ndarray = None\n self._labels: np.ndarray = None\n\n @property\n def cluster_centers_(self) -> np.ndarray:\n return self._cluster_centers\n\n @property\n def labels_(self) -> np.ndarray:\n return self._labels\n\n def fit(self, X: np.ndarray, y: np.ndarray = None) -> \"KMeans\":\n mask = np.random.choice(X.shape[0], self._n_clusters, replace=False)\n self._cluster_centers = X[mask]\n\n iters = 0\n while iters < self._max_iter:\n iters += 1\n prev_cluster_centers = self._cluster_centers\n\n self._get_labels(X)\n self._update_cluster_centers(X)\n\n diff = np.sum(prev_cluster_centers - self._cluster_centers)\n if diff == 0:\n break\n\n return self\n\n def predict(self, X: np.ndarray) -> np.ndarray:\n labels = np.argmin(self._update_distance(X), axis=1)\n return labels\n\n def fit_predict(self, X: np.ndarray, y: np.ndarray = None) -> np.ndarray:\n self.fit(X)\n return self._labels\n\n def _update_distance(self, X: np.ndarray) -> np.ndarray:\n distance_to_centers = np.ndarray(shape=(X.shape[0], self._n_clusters))\n for idx, cluster_center in enumerate(self._cluster_centers):\n distance_array = np.sum(np.square(X - cluster_center), axis=1)\n distance_to_centers[:, idx] = distance_array\n\n return distance_to_centers\n\n def _get_labels(self, X: np.ndarray) -> None:\n self._labels = np.argmin(self._update_distance(X), axis=1)\n\n def _update_cluster_centers(self, X: np.ndarray) -> None:\n for idx in range(self._n_clusters):\n mask = self._labels == idx\n self._cluster_centers[idx] = np.mean(X[mask], axis=0)\n" ]
[ [ "numpy.square", "numpy.random.choice", "numpy.ndarray", "numpy.mean", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
soulsheng/lanenet-lane-detection
[ "f7bc580a73e686a77a5506dbfc57ed424f0715b5" ]
[ "semantic_segmentation_zoo/cnn_basenet.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 17-9-18 下午3:59\n# @Author : MaybeShewill-CV\n# @Site : https://github.com/MaybeShewill-CV/lanenet-lane-detection\n# @File : cnn_basenet.py\n# @IDE: PyCharm Community Edition\n\"\"\"\nThe base convolution neural networks mainly implement some useful cnn functions\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\n\n\nclass CNNBaseModel(object):\n \"\"\"\n Base model for other specific cnn ctpn_models\n \"\"\"\n\n def __init__(self):\n pass\n\n @staticmethod\n def conv2d(inputdata, out_channel, kernel_size, padding='SAME',\n stride=1, w_init=None, b_init=None,\n split=1, use_bias=True, data_format='NHWC', name=None):\n \"\"\"\n Packing the tensorflow conv2d function.\n :param name: op name\n :param inputdata: A 4D tensorflow tensor which ust have known number of channels, but can have other\n unknown dimensions.\n :param out_channel: number of output channel.\n :param kernel_size: int so only support square kernel convolution\n :param padding: 'VALID' or 'SAME'\n :param stride: int so only support square stride\n :param w_init: initializer for convolution weights\n :param b_init: initializer for bias\n :param split: split channels as used in Alexnet mainly group for GPU memory save.\n :param use_bias: whether to use bias.\n :param data_format: default set to NHWC according tensorflow\n :return: tf.Tensor named ``output``\n \"\"\"\n with tf.variable_scope(name):\n in_shape = inputdata.get_shape().as_list()\n channel_axis = 3 if data_format == 'NHWC' else 1\n in_channel = in_shape[channel_axis]\n assert in_channel is not None, \"[Conv2D] Input cannot have unknown channel!\"\n assert in_channel % split == 0\n assert out_channel % split == 0\n\n padding = padding.upper()\n\n if isinstance(kernel_size, list):\n filter_shape = [kernel_size[0], kernel_size[1]] + [in_channel / split, out_channel]\n else:\n filter_shape = [kernel_size, kernel_size] + [in_channel / split, out_channel]\n\n if isinstance(stride, list):\n strides = [1, stride[0], stride[1], 1] if data_format == 'NHWC' \\\n else [1, 1, stride[0], stride[1]]\n else:\n strides = [1, stride, stride, 1] if data_format == 'NHWC' \\\n else [1, 1, stride, stride]\n\n if w_init is None:\n w_init = tf.contrib.layers.variance_scaling_initializer()\n if b_init is None:\n b_init = tf.constant_initializer()\n\n w = tf.get_variable('W', filter_shape, initializer=w_init)\n b = None\n\n if use_bias:\n b = tf.get_variable('b', [out_channel], initializer=b_init)\n\n if split == 1:\n conv = tf.nn.conv2d(inputdata, w, strides, padding, data_format=data_format)\n else:\n inputs = tf.split(inputdata, split, channel_axis)\n kernels = tf.split(w, split, 3)\n outputs = [tf.nn.conv2d(i, k, strides, padding, data_format=data_format)\n for i, k in zip(inputs, kernels)]\n conv = tf.concat(outputs, channel_axis)\n\n ret = tf.identity(tf.nn.bias_add(conv, b, data_format=data_format)\n if use_bias else conv, name=name)\n\n return ret\n\n @staticmethod\n def depthwise_conv(input_tensor, kernel_size, name, depth_multiplier=1,\n padding='SAME', stride=1):\n \"\"\"\n\n :param input_tensor:\n :param kernel_size:\n :param name:\n :param depth_multiplier:\n :param padding:\n :param stride:\n :return:\n \"\"\"\n with tf.variable_scope(name_or_scope=name):\n in_shape = input_tensor.get_shape().as_list()\n in_channel = in_shape[3]\n padding = padding.upper()\n\n depthwise_filter_shape = [kernel_size, kernel_size] + [in_channel, depth_multiplier]\n w_init = tf.contrib.layers.variance_scaling_initializer()\n\n depthwise_filter = tf.get_variable(\n name='depthwise_filter_w', shape=depthwise_filter_shape,\n initializer=w_init\n )\n\n result = tf.nn.depthwise_conv2d(\n input=input_tensor,\n filter=depthwise_filter,\n strides=[1, stride, stride, 1],\n padding=padding,\n name='depthwise_conv_output'\n )\n return result\n\n @staticmethod\n def relu(inputdata, name=None):\n \"\"\"\n\n :param name:\n :param inputdata:\n :return:\n \"\"\"\n return tf.nn.relu(features=inputdata, name=name)\n\n @staticmethod\n def sigmoid(inputdata, name=None):\n \"\"\"\n\n :param name:\n :param inputdata:\n :return:\n \"\"\"\n return tf.nn.sigmoid(x=inputdata, name=name)\n\n @staticmethod\n def maxpooling(inputdata, kernel_size, stride=None, padding='VALID',\n data_format='NHWC', name=None):\n \"\"\"\n\n :param name:\n :param inputdata:\n :param kernel_size:\n :param stride:\n :param padding:\n :param data_format:\n :return:\n \"\"\"\n padding = padding.upper()\n\n if stride is None:\n stride = kernel_size\n\n if isinstance(kernel_size, list):\n kernel = [1, kernel_size[0], kernel_size[1], 1] if data_format == 'NHWC' else \\\n [1, 1, kernel_size[0], kernel_size[1]]\n else:\n kernel = [1, kernel_size, kernel_size, 1] if data_format == 'NHWC' \\\n else [1, 1, kernel_size, kernel_size]\n\n if isinstance(stride, list):\n strides = [1, stride[0], stride[1], 1] if data_format == 'NHWC' \\\n else [1, 1, stride[0], stride[1]]\n else:\n strides = [1, stride, stride, 1] if data_format == 'NHWC' \\\n else [1, 1, stride, stride]\n\n return tf.nn.max_pool(value=inputdata, ksize=kernel, strides=strides, padding=padding,\n data_format=data_format, name=name)\n\n @staticmethod\n def avgpooling(inputdata, kernel_size, stride=None, padding='VALID',\n data_format='NHWC', name=None):\n \"\"\"\n\n :param name:\n :param inputdata:\n :param kernel_size:\n :param stride:\n :param padding:\n :param data_format:\n :return:\n \"\"\"\n if stride is None:\n stride = kernel_size\n\n kernel = [1, kernel_size, kernel_size, 1] if data_format == 'NHWC' \\\n else [1, 1, kernel_size, kernel_size]\n\n strides = [1, stride, stride, 1] if data_format == 'NHWC' else [1, 1, stride, stride]\n\n return tf.nn.avg_pool(value=inputdata, ksize=kernel, strides=strides, padding=padding,\n data_format=data_format, name=name)\n\n @staticmethod\n def globalavgpooling(inputdata, data_format='NHWC', name=None):\n \"\"\"\n\n :param name:\n :param inputdata:\n :param data_format:\n :return:\n \"\"\"\n assert inputdata.shape.ndims == 4\n assert data_format in ['NHWC', 'NCHW']\n\n axis = [1, 2] if data_format == 'NHWC' else [2, 3]\n\n return tf.reduce_mean(input_tensor=inputdata, axis=axis, name=name)\n\n @staticmethod\n def layernorm(inputdata, epsilon=1e-5, use_bias=True, use_scale=True,\n data_format='NHWC', name=None):\n \"\"\"\n :param name:\n :param inputdata:\n :param epsilon: epsilon to avoid divide-by-zero.\n :param use_bias: whether to use the extra affine transformation or not.\n :param use_scale: whether to use the extra affine transformation or not.\n :param data_format:\n :return:\n \"\"\"\n shape = inputdata.get_shape().as_list()\n ndims = len(shape)\n assert ndims in [2, 4]\n\n mean, var = tf.nn.moments(inputdata, list(range(1, len(shape))), keep_dims=True)\n\n if data_format == 'NCHW':\n channnel = shape[1]\n new_shape = [1, channnel, 1, 1]\n else:\n channnel = shape[-1]\n new_shape = [1, 1, 1, channnel]\n if ndims == 2:\n new_shape = [1, channnel]\n\n if use_bias:\n beta = tf.get_variable('beta', [channnel], initializer=tf.constant_initializer())\n beta = tf.reshape(beta, new_shape)\n else:\n beta = tf.zeros([1] * ndims, name='beta')\n if use_scale:\n gamma = tf.get_variable('gamma', [channnel], initializer=tf.constant_initializer(1.0))\n gamma = tf.reshape(gamma, new_shape)\n else:\n gamma = tf.ones([1] * ndims, name='gamma')\n\n return tf.nn.batch_normalization(inputdata, mean, var, beta, gamma, epsilon, name=name)\n\n @staticmethod\n def instancenorm(inputdata, epsilon=1e-5, data_format='NHWC', use_affine=True, name=None):\n \"\"\"\n\n :param name:\n :param inputdata:\n :param epsilon:\n :param data_format:\n :param use_affine:\n :return:\n \"\"\"\n shape = inputdata.get_shape().as_list()\n if len(shape) != 4:\n raise ValueError(\"Input data of instancebn layer has to be 4D tensor\")\n\n if data_format == 'NHWC':\n axis = [1, 2]\n ch = shape[3]\n new_shape = [1, 1, 1, ch]\n else:\n axis = [2, 3]\n ch = shape[1]\n new_shape = [1, ch, 1, 1]\n if ch is None:\n raise ValueError(\"Input of instancebn require known channel!\")\n\n mean, var = tf.nn.moments(inputdata, axis, keep_dims=True)\n\n if not use_affine:\n return tf.divide(inputdata - mean, tf.sqrt(var + epsilon), name='output')\n\n beta = tf.get_variable('beta', [ch], initializer=tf.constant_initializer())\n beta = tf.reshape(beta, new_shape)\n gamma = tf.get_variable('gamma', [ch], initializer=tf.constant_initializer(1.0))\n gamma = tf.reshape(gamma, new_shape)\n return tf.nn.batch_normalization(inputdata, mean, var, beta, gamma, epsilon, name=name)\n\n @staticmethod\n def dropout(inputdata, keep_prob, noise_shape=None, name=None):\n \"\"\"\n\n :param name:\n :param inputdata:\n :param keep_prob:\n :param noise_shape:\n :return:\n \"\"\"\n return tf.nn.dropout(inputdata, keep_prob=keep_prob, noise_shape=noise_shape, name=name)\n\n @staticmethod\n def fullyconnect(inputdata, out_dim, w_init=None, b_init=None,\n use_bias=True, name=None):\n \"\"\"\n Fully-Connected layer, takes a N>1D tensor and returns a 2D tensor.\n It is an equivalent of `tf.layers.dense` except for naming conventions.\n\n :param inputdata: a tensor to be flattened except for the first dimension.\n :param out_dim: output dimension\n :param w_init: initializer for w. Defaults to `variance_scaling_initializer`.\n :param b_init: initializer for b. Defaults to zero\n :param use_bias: whether to use bias.\n :param name:\n :return: tf.Tensor: a NC tensor named ``output`` with attribute `variables`.\n \"\"\"\n shape = inputdata.get_shape().as_list()[1:]\n if None not in shape:\n inputdata = tf.reshape(inputdata, [-1, int(np.prod(shape))])\n else:\n inputdata = tf.reshape(inputdata, tf.stack([tf.shape(inputdata)[0], -1]))\n\n if w_init is None:\n w_init = tf.contrib.layers.variance_scaling_initializer()\n if b_init is None:\n b_init = tf.constant_initializer()\n\n ret = tf.layers.dense(inputs=inputdata, activation=lambda x: tf.identity(x, name='output'),\n use_bias=use_bias, name=name,\n kernel_initializer=w_init, bias_initializer=b_init,\n trainable=True, units=out_dim)\n return ret\n\n @staticmethod\n def layerbn(inputdata, is_training, name, scale=True):\n \"\"\"\n\n :param inputdata:\n :param is_training:\n :param name:\n :param scale:\n :return:\n \"\"\"\n\n return tf.layers.batch_normalization(inputs=inputdata, training=is_training, name=name, scale=scale)\n\n @staticmethod\n def layergn(inputdata, name, group_size=32, esp=1e-5):\n \"\"\"\n\n :param inputdata:\n :param name:\n :param group_size:\n :param esp:\n :return:\n \"\"\"\n with tf.variable_scope(name):\n inputdata = tf.transpose(inputdata, [0, 3, 1, 2])\n n, c, h, w = inputdata.get_shape().as_list()\n group_size = min(group_size, c)\n inputdata = tf.reshape(inputdata, [-1, group_size, c // group_size, h, w])\n mean, var = tf.nn.moments(inputdata, [2, 3, 4], keep_dims=True)\n inputdata = (inputdata - mean) / tf.sqrt(var + esp)\n\n # 每个通道的gamma和beta\n gamma = tf.Variable(tf.constant(1.0, shape=[c]), dtype=tf.float32, name='gamma')\n beta = tf.Variable(tf.constant(0.0, shape=[c]), dtype=tf.float32, name='beta')\n gamma = tf.reshape(gamma, [1, c, 1, 1])\n beta = tf.reshape(beta, [1, c, 1, 1])\n\n # 根据论文进行转换 [n, c, h, w, c] 到 [n, h, w, c]\n output = tf.reshape(inputdata, [-1, c, h, w])\n output = output * gamma + beta\n output = tf.transpose(output, [0, 2, 3, 1])\n\n return output\n\n @staticmethod\n def squeeze(inputdata, axis=None, name=None):\n \"\"\"\n\n :param inputdata:\n :param axis:\n :param name:\n :return:\n \"\"\"\n return tf.squeeze(input=inputdata, axis=axis, name=name)\n\n @staticmethod\n def deconv2d(inputdata, out_channel, kernel_size, padding='SAME',\n stride=1, w_init=None, b_init=None,\n use_bias=True, activation=None, data_format='channels_last',\n trainable=True, name=None):\n \"\"\"\n Packing the tensorflow conv2d function.\n :param name: op name\n :param inputdata: A 4D tensorflow tensor which ust have known number of channels, but can have other\n unknown dimensions.\n :param out_channel: number of output channel.\n :param kernel_size: int so only support square kernel convolution\n :param padding: 'VALID' or 'SAME'\n :param stride: int so only support square stride\n :param w_init: initializer for convolution weights\n :param b_init: initializer for bias\n :param activation: whether to apply a activation func to deconv result\n :param use_bias: whether to use bias.\n :param data_format: default set to NHWC according tensorflow\n :return: tf.Tensor named ``output``\n \"\"\"\n with tf.variable_scope(name):\n in_shape = inputdata.get_shape().as_list()\n channel_axis = 3 if data_format == 'channels_last' else 1\n in_channel = in_shape[channel_axis]\n assert in_channel is not None, \"[Deconv2D] Input cannot have unknown channel!\"\n\n padding = padding.upper()\n\n if w_init is None:\n w_init = tf.contrib.layers.variance_scaling_initializer()\n if b_init is None:\n b_init = tf.constant_initializer()\n\n ret = tf.layers.conv2d_transpose(inputs=inputdata, filters=out_channel,\n kernel_size=kernel_size,\n strides=stride, padding=padding,\n data_format=data_format,\n activation=activation, use_bias=use_bias,\n kernel_initializer=w_init,\n bias_initializer=b_init, trainable=trainable,\n name=name)\n return ret\n\n @staticmethod\n def dilation_conv(input_tensor, k_size, out_dims, rate, padding='SAME',\n w_init=None, b_init=None, use_bias=False, name=None):\n \"\"\"\n\n :param input_tensor:\n :param k_size:\n :param out_dims:\n :param rate:\n :param padding:\n :param w_init:\n :param b_init:\n :param use_bias:\n :param name:\n :return:\n \"\"\"\n with tf.variable_scope(name):\n in_shape = input_tensor.get_shape().as_list()\n in_channel = in_shape[3]\n assert in_channel is not None, \"[Conv2D] Input cannot have unknown channel!\"\n\n padding = padding.upper()\n\n if isinstance(k_size, list):\n filter_shape = [k_size[0], k_size[1]] + [in_channel, out_dims]\n else:\n filter_shape = [k_size, k_size] + [in_channel, out_dims]\n\n if w_init is None:\n w_init = tf.contrib.layers.variance_scaling_initializer()\n if b_init is None:\n b_init = tf.constant_initializer()\n\n w = tf.get_variable('W', filter_shape, initializer=w_init)\n b = None\n\n if use_bias:\n b = tf.get_variable('b', [out_dims], initializer=b_init)\n\n conv = tf.nn.atrous_conv2d(value=input_tensor, filters=w, rate=rate,\n padding=padding, name='dilation_conv')\n\n if use_bias:\n ret = tf.add(conv, b)\n else:\n ret = conv\n\n return ret\n\n @staticmethod\n def spatial_dropout(input_tensor, keep_prob, is_training, name, seed=1234):\n \"\"\"\n 空间dropout实现\n :param input_tensor:\n :param keep_prob:\n :param is_training:\n :param name:\n :param seed:\n :return:\n \"\"\"\n\n def f1():\n input_shape = input_tensor.get_shape().as_list()\n noise_shape = tf.constant(value=[input_shape[0], 1, 1, input_shape[3]])\n return tf.nn.dropout(input_tensor, keep_prob, noise_shape, seed=seed, name=\"spatial_dropout\")\n\n def f2():\n return input_tensor\n\n with tf.variable_scope(name_or_scope=name):\n\n output = tf.cond(is_training, f1, f2)\n\n return output\n\n @staticmethod\n def lrelu(inputdata, name, alpha=0.2):\n \"\"\"\n\n :param inputdata:\n :param alpha:\n :param name:\n :return:\n \"\"\"\n with tf.variable_scope(name):\n return tf.nn.relu(inputdata) - alpha * tf.nn.relu(-inputdata)\n" ]
[ [ "tensorflow.cond", "tensorflow.get_variable", "tensorflow.concat", "tensorflow.zeros", "tensorflow.nn.max_pool", "tensorflow.layers.conv2d_transpose", "tensorflow.nn.depthwise_conv2d", "tensorflow.nn.atrous_conv2d", "tensorflow.nn.conv2d", "tensorflow.layers.batch_normalization", "tensorflow.contrib.layers.variance_scaling_initializer", "tensorflow.nn.moments", "tensorflow.squeeze", "tensorflow.add", "tensorflow.nn.dropout", "tensorflow.nn.batch_normalization", "tensorflow.nn.sigmoid", "tensorflow.shape", "tensorflow.identity", "tensorflow.nn.avg_pool", "tensorflow.split", "tensorflow.nn.bias_add", "tensorflow.nn.relu", "tensorflow.transpose", "tensorflow.constant", "tensorflow.reduce_mean", "tensorflow.reshape", "tensorflow.ones", "tensorflow.constant_initializer", "numpy.prod", "tensorflow.variable_scope", "tensorflow.sqrt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
anandkrishnakumar/ICLV-estimation
[ "e9d5fa2a6d350c130a765da0a07dd929af3aeb7c" ]
[ "dgp.py" ]
[ "import numpy as np\nimport sklearn.datasets\n\n#------------------------------DGP FOR ALL LATENT VARIABLES-------------------\ndef dgp():\n N = 1000\n # alternative specific constants\n ASC = np.array([0, -0.6, 0.8])\n beta = np.array([-1.2, 0.8])\n X = np.random.normal(size=(N, 3, 2))\n \n ### LATENT VARIABLES\n b = np.array([0.5, 0.8, 1.5, 0.3, 1.8, 0.5, 1.0])\n B = np.zeros((6, 4))\n li = b[[0, 1, 2, 3, 4, 5, 6, 3, 4, 5, 6]]\n row_indices = [0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]\n col_indices = [0, 0, 3, 1, 3, 1, 3, 2, 3, 2, 3]\n B[row_indices, col_indices] = li\n w = np.random.normal(size=(N, 4))\n w[:, -1] = np.random.binomial(1, 0.5, size=N)\n # first three are alternative-specific\n # fourth attribute is individual-specific\n Psi = np.eye(6)\n z = np.empty((N, 6))\n for n in range(N):\n z[n] = B @ w[n] + np.random.multivariate_normal(np.zeros(6), Psi)\n tau = np.zeros((3, 6))\n tau[0, :2] = [-0.4, 0.5] # 0 # np.random.normal(size=2)\n tau[1, 2:4] = [0.5, -0.6] # np.random.normal(size=2)\n tau[2, 4:] = [0.5, 0.6] # np.random.normal(size=2)\n \n ### INDICATORS\n Lambda = np.zeros((9, 6))\n lambda_ = np.array([0.7, 0.5, 1.0, 0.7, 0.5, 0.8, 1.0, 1.0])\n li = lambda_[[0, 1, 2, 3, 4, 5, 6, 7, 4, 5, 6, 7]]\n row_indices = [0, 0, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8]\n col_indices = [0, 1, 0, 1, 2, 3, 2, 3, 4, 5, 4, 5]\n Lambda[row_indices, col_indices] = li\n I = np.empty((N, 9))\n Theta = np.eye(9)\n for n in range(N):\n I[n] = Lambda @ z[n].flatten() + np.random.multivariate_normal(np.zeros(9), Theta)\n \n ### MAKING CHOICES\n Y = np.zeros((N, 3))\n U = np.zeros((N, 3))\n for n in range(N):\n for j in range(3):\n U[n, j] = ASC[j] + X[n, j] @ beta + tau[j] @ z[n]\n U[n, j] += np.random.gumbel(0, 1)\n Y[n, np.argmax(U[n])] = 1\n \n \n ### SAVING\n np.savetxt(\"z.txt\", z)\n np.savetxt(\"Psi.txt\", Psi)\n np.savetxt(\"B.txt\", B)\n np.savetxt(\"Theta.txt\", Theta)\n np.savetxt(\"Lambda.txt\", Lambda)\n np.savetxt(\"beta.txt\", beta)\n np.savetxt(\"tau.txt\", tau)\n \n np.savetxt(\"I.txt\", I)\n np.savetxt(\"w.txt\", w)\n np.savetxt(\"Y.txt\", Y)\n np.savetxt(\"X.txt\", X.reshape(N, 3*2)) # reshaped because 3D arrays can't be saved\n np.savetxt(\"ASC.txt\", ASC)\n \n return 0.25" ]
[ [ "numpy.random.gumbel", "numpy.eye", "numpy.random.normal", "numpy.argmax", "numpy.random.binomial", "numpy.array", "numpy.zeros", "numpy.empty", "numpy.savetxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Rickitik/evidently
[ "a35aa45c2afa3fe6b2efa0e7d03280f8e6142eb3" ]
[ "tests/analyzers/test_categorical_target_drift_analyzer.py" ]
[ "import pytest\nimport numpy as np\nfrom pandas import DataFrame\nfrom pytest import approx\n\nfrom evidently import ColumnMapping\nfrom evidently.analyzers.cat_target_drift_analyzer import CatTargetDriftAnalyzer\nfrom evidently.options import DataDriftOptions, OptionsProvider\n\n\[email protected]\ndef analyzer() -> CatTargetDriftAnalyzer:\n options_provider: OptionsProvider = OptionsProvider()\n options_provider.add(DataDriftOptions(confidence=0.5))\n analyzer = CatTargetDriftAnalyzer()\n analyzer.options_provider = options_provider\n return analyzer\n\n\ndef test_different_target_column_name(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'another_target': ['a'] * 10 + ['b'] * 10\n })\n df2 = DataFrame({\n 'another_target': ['a'] * 10 + ['b'] * 10\n })\n\n result = analyzer.calculate(df1, df2, ColumnMapping(target='another_target'))\n assert result.target_metrics is not None\n assert result.target_metrics.column_name == 'another_target'\n assert result.prediction_metrics is None\n\n\ndef test_basic_structure_no_drift(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'target': ['a'] * 10 + ['b'] * 10\n })\n df2 = DataFrame({\n 'target': ['a'] * 10 + ['b'] * 10\n })\n\n result = analyzer.calculate(df1, df2, ColumnMapping())\n assert result.target_metrics is not None\n assert result.target_metrics.column_name == 'target'\n assert result.target_metrics.drift == approx(1)\n assert result.prediction_metrics is None\n\n\ndef test_computing_some_drift(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'target': ['a'] * 10 + ['b'] * 10\n })\n df2 = DataFrame({\n 'target': ['a'] * 6 + ['b'] * 15\n })\n\n result = analyzer.calculate(df1, df2, ColumnMapping())\n assert result.target_metrics is not None\n assert result.target_metrics.column_name == 'target'\n assert result.target_metrics.drift == approx(0.1597, abs=1e-4)\n assert result.prediction_metrics is None\n\n\ndef test_small_sample_size(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'target': ['a', 'b']\n })\n df2 = DataFrame({\n 'target': ['b']\n })\n\n result = analyzer.calculate(df1, df2, ColumnMapping())\n assert result.target_metrics is not None\n assert result.target_metrics.column_name == 'target'\n assert result.target_metrics.drift == approx(0.386, abs=1e-2)\n assert result.prediction_metrics is None\n\n\ndef test_different_labels_1(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'target': ['a', 'b']\n })\n df2 = DataFrame({\n 'target': ['c']\n })\n\n # FIXME: RuntimeWarning: divide by zero encountered in true_divide\n result = analyzer.calculate(df1, df2, ColumnMapping())\n assert result.target_metrics is not None\n assert result.target_metrics.column_name == 'target'\n assert result.target_metrics.drift == approx(0., abs=1e-2)\n assert result.prediction_metrics is None\n\n\ndef test_different_labels_2(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'target': ['c'] * 10\n })\n df2 = DataFrame({\n 'target': ['a', 'b'] * 10\n })\n\n # FIXME: RuntimeWarning: divide by zero encountered in true_divide\n result = analyzer.calculate(df1, df2, ColumnMapping())\n assert result.target_metrics is not None\n assert result.target_metrics.column_name == 'target'\n assert result.target_metrics.drift == approx(0., abs=1e-2)\n assert result.prediction_metrics is None\n\n\ndef test_computation_of_categories_as_numbers(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'target': [0, 1] * 10\n })\n df2 = DataFrame({\n 'target': [1] * 5\n })\n\n # FIXME: RuntimeWarning: divide by zero encountered in true_divide\n result = analyzer.calculate(df1, df2, ColumnMapping())\n assert result.target_metrics is not None\n assert result.target_metrics.column_name == 'target'\n assert result.target_metrics.drift == approx(0.04122, abs=1e-3)\n assert result.prediction_metrics is None\n\n\ndef test_computing_of_target_and_prediction(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'target': ['a', 'b'] * 10,\n 'prediction': ['b', 'c'] * 10\n })\n df2 = DataFrame({\n 'target': ['b', 'c'] * 5,\n 'prediction': ['a', 'b'] * 5\n })\n\n result = analyzer.calculate(df1, df2, ColumnMapping())\n assert result.target_metrics is not None\n assert result.target_metrics.column_name == 'target'\n assert result.target_metrics.drift == approx(0., abs=1e-3)\n assert result.prediction_metrics is not None\n assert result.prediction_metrics.column_name == 'prediction'\n\n\ndef test_computing_of_only_prediction(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'another_prediction': ['b', 'c'] * 10\n })\n df2 = DataFrame({\n 'another_prediction': ['a', 'b'] * 5\n })\n # FIXME: wtf: RuntimeWarning: divide by zero encountered in true_divide ?\n result = analyzer.calculate(df1, df2, ColumnMapping(prediction='another_prediction'))\n assert result.prediction_metrics is not None\n assert result.prediction_metrics.column_name == 'another_prediction'\n assert result.prediction_metrics.drift == approx(0., abs=1e-3)\n\n\ndef test_computing_with_nans(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'target': ['a'] * 10 + ['b'] * 10 + [np.nan] * 2 + [np.inf] * 2,\n 'prediction': ['a'] * 10 + ['b'] * 10 + [np.nan] * 2 + [np.inf] * 2\n })\n df2 = DataFrame({\n 'target': ['a'] * 3 + ['b'] * 7 + [np.nan] * 2,\n 'prediction': ['a'] * 3 + ['b'] * 7 + [np.nan] * 2\n })\n\n result = analyzer.calculate(df1, df2, ColumnMapping())\n assert result.target_metrics is not None\n assert result.prediction_metrics is not None\n assert result.target_metrics.drift == approx(0.29736, abs=1e-4)\n assert result.prediction_metrics.drift == approx(0.29736, abs=1e-4)\n\n df3 = DataFrame({\n 'target': ['a'] * 3 + ['b'] * 7 + [np.nan] * 20,\n 'prediction': ['a'] * 3 + ['b'] * 7 + [np.nan] * 20\n })\n result = analyzer.calculate(df1, df3, ColumnMapping())\n assert result.target_metrics is not None\n assert result.prediction_metrics is not None\n assert result.target_metrics.drift == approx(0.29736, abs=1e-4)\n assert result.prediction_metrics.drift == approx(0.29736, abs=1e-4)\n\n\ndef test_computing_uses_a_custom_function(analyzer: CatTargetDriftAnalyzer) -> None:\n df1 = DataFrame({\n 'some_column': ['a'] * 10 + ['b'] * 10\n })\n df2 = DataFrame({\n 'some_column': ['a'] * 6 + ['b'] * 15\n })\n\n options = DataDriftOptions()\n options.cat_target_stattest_func = lambda x, y, threshold: (np.pi, False)\n analyzer.options_provider.add(options)\n result = analyzer.calculate(df1, df2, ColumnMapping(target='some_column'))\n assert result.target_metrics is not None\n assert result.target_metrics.drift == approx(np.pi, abs=1e-4)\n assert result.target_metrics.column_name == 'some_column'\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
tehilaogen/IML.HUJI
[ "2d3a11a87e9ffc114474362867e2b451bdc7dd02" ]
[ "exercises/fit_gaussian_estimators.py" ]
[ "from IMLearn.learners import UnivariateGaussian, MultivariateGaussian\nimport numpy as np\nimport plotly.graph_objects as go\nimport plotly.io as pio\npio.templates.default = \"simple_white\"\n\n\ndef test_univariate_gaussian():\n # Question 1 - Draw samples and print fitted model\n mean = 10\n var = 1\n X = np.random.normal(mean,var,1000)\n Qu1 = UnivariateGaussian()\n Qu1.fit(X)\n print(Qu1.mu_, Qu1.var_)\n\n # Question 2 - Empirically showing sample mean is consistent\n Qu2 = UnivariateGaussian()\n distance = []\n i = 10\n while i <= 1000:\n Y = X[:i]\n Qu2.fit(Y) \n abs_dist = np.abs(Qu2.mu_ - mean)\n distance.append(abs_dist)\n i += 10\n \n axis_x = np.linspace(10,1000,100).astype(int)\n \n go.Figure([go.Scatter(x=axis_x, y=distance, mode='markers+lines')],\n layout=go.Layout(title=r\"$\\text{Absolute Distance Between The Estimated- And True Value of The Expectation, As a Function of The Sample Size}$\", \n xaxis_title=\"$m\\\\text{ - number of samples}$\", \n yaxis_title=\"r$\\distance\\mu$\",\n height=300)).show()\n \n # Question 3 - Plotting Empirical PDF of fitted model\n axis_x = X\n axis_y = Qu1.pdf(X)\n go.Figure([go.Scatter(x=axis_x, y=distance, mode='markers')],\n layout=go.Layout(title=r\"$\\text{Empirical PDF Function Under The Fitted Model}$\", \n xaxis_title=\"$m\\\\text{ - samples}$\", \n yaxis_title=\"r$\\PDF of X$\",\n height=300)).show()\n\n\ndef test_multivariate_gaussian():\n # Question 4 - Draw samples and print fitted model\n mu = [0, 0, 4, 0]\n cov = [[1, 0.2, 0, 0.5], [0.2, 2, 0, 0], [0, 0, 1, 0], [0.5, 0, 0, 1]]\n X = np.random.multivariate_normal(mu, cov, 1000)\n Qu4 = MultivariateGaussian()\n Qu4.fit(X)\n print(\"mu:\", Qu4.mu_)\n print(\"cov:\", Qu4.cov_)\n\n # Question 5 - Likelihood evaluation\n raise NotImplementedError()\n\n # Question 6 - Maximum likelihood\n raise NotImplementedError()\n\n\nif __name__ == '__main__':\n np.random.seed(0)\n test_univariate_gaussian()\n test_multivariate_gaussian()\n" ]
[ [ "numpy.abs", "numpy.random.seed", "numpy.linspace", "numpy.random.multivariate_normal", "numpy.random.normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
william-yan/CSU_notes
[ "c2b7fb3dea5a6435bf9dbadaad479b06c9297fcb" ]
[ "Yan/code/Spline/demo.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue May 14 09:21:32 2019\r\n\r\n@author: Yan\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom pylab import mpl\r\n\"\"\"\r\n二次样条实现:\r\n函数x的自变量为:3, 4.5, 7, 9\r\n 因变量为:2.5, 1 2.5, 0.5\r\n\"\"\"\r\nx = [3, 4.5, 7, 9]\r\ny = [2.5, 1, 2.5, 0.5]\r\n \r\n\"\"\"一共有三个区间,用二次样条求解,需要有9个方程\"\"\"\r\n \r\n \r\n\"\"\"\r\n功能:完后对二次样条函数求解方程参数的输入\r\n参数:要进行二次样条曲线计算的自变量\r\n返回值:方程的参数\r\n\"\"\"\r\ndef calculateEquationParameters(x):\r\n #parameter为二维数组,用来存放参数,sizeOfInterval是用来存放区间的个数\r\n parameter = []\r\n sizeOfInterval=len(x)-1;\r\n i = 1\r\n #首先输入方程两边相邻节点处函数值相等的方程为2n-2个方程\r\n while i < len(x)-1:\r\n data = init(sizeOfInterval*3)\r\n data[(i-1)*3]=x[i]*x[i]\r\n data[(i-1)*3+1]=x[i]\r\n data[(i-1)*3+2]=1\r\n data1 =init(sizeOfInterval*3)\r\n data1[i * 3] = x[i] * x[i]\r\n data1[i * 3 + 1] = x[i]\r\n data1[i * 3 + 2] = 1\r\n temp=data[1:]\r\n parameter.append(temp)\r\n temp=data1[1:]\r\n parameter.append(temp)\r\n i += 1\r\n #输入端点处的函数值。为两个方程,加上前面的2n-2个方程,一共2n个方程\r\n data = init(sizeOfInterval*3-1)\r\n data[0] = x[0]\r\n data[1] = 1\r\n parameter.append(data)\r\n data = init(sizeOfInterval *3)\r\n data[(sizeOfInterval-1)*3+0] = x[-1] * x[-1]\r\n data[(sizeOfInterval-1)*3+1] = x[-1]\r\n data[(sizeOfInterval-1)*3+2] = 1\r\n temp=data[1:]\r\n parameter.append(temp)\r\n #端点函数值相等为n-1个方程。加上前面的方程为3n-1个方程,最后一个方程为a1=0总共为3n个方程\r\n i=1\r\n while i < len(x) - 1:\r\n data = init(sizeOfInterval * 3)\r\n data[(i - 1) * 3] =2*x[i]\r\n data[(i - 1) * 3 + 1] =1\r\n data[i*3]=-2*x[i]\r\n data[i*3+1]=-1\r\n temp=data[1:]\r\n parameter.append(temp)\r\n i += 1\r\n return parameter\r\n \r\n\"\"\"\r\n对一个size大小的元组初始化为0\r\n\"\"\"\r\ndef init(size):\r\n j = 0;\r\n data = []\r\n while j < size:\r\n data.append(0)\r\n j += 1\r\n return data\r\n \r\n \r\n\"\"\"\r\n功能:计算样条函数的系数。\r\n参数:parametes为方程的系数,y为要插值函数的因变量。\r\n返回值:二次插值函数的系数。\r\n\"\"\"\r\n \r\ndef solutionOfEquation(parametes,y):\r\n sizeOfInterval = len(x) - 1;\r\n result = init(sizeOfInterval*3-1)\r\n i=1\r\n while i<sizeOfInterval:\r\n result[(i-1)*2]=y[i]\r\n result[(i-1)*2+1]=y[i]\r\n i+=1\r\n result[(sizeOfInterval-1)*2]=y[0]\r\n result[(sizeOfInterval-1)*2+1]=y[-1]\r\n a = np.array(calculateEquationParameters(x))\r\n b = np.array(result)\r\n return np.linalg.solve(a,b)\r\n \r\n\"\"\"\r\n功能:根据所给参数,计算二次函数的函数值:\r\n参数:parameters为二次函数的系数,x为自变量\r\n返回值:为函数的因变量\r\n\"\"\"\r\ndef calculate(paremeters,x):\r\n result=[]\r\n for data_x in x:\r\n result.append(paremeters[0]*data_x*data_x+paremeters[1]*data_x+paremeters[2])\r\n return result\r\n \r\n \r\n\"\"\"\r\n功能:将函数绘制成图像\r\n参数:data_x,data_y为离散的点.new_data_x,new_data_y为由拉格朗日插值函数计算的值。x为函数的预测值。\r\n返回值:空\r\n\"\"\"\r\ndef Draw(data_x,data_y,new_data_x,new_data_y):\r\n plt.plot(new_data_x, new_data_y, label=\"拟合曲线\", color=\"black\")\r\n plt.scatter(data_x,data_y, label=\"离散数据\",color=\"red\")\r\n mpl.rcParams['font.sans-serif'] = ['SimHei']\r\n mpl.rcParams['axes.unicode_minus'] = False\r\n plt.title(\"二次样条函数\")\r\n plt.legend(loc=\"upper left\")\r\n plt.show()\r\n \r\nresult=solutionOfEquation(calculateEquationParameters(x),y)\r\nnew_data_x1=np.arange(3, 4.5, 0.1)\r\nnew_data_y1=calculate([0,result[0],result[1]],new_data_x1)\r\nnew_data_x2=np.arange(4.5, 7, 0.1)\r\nnew_data_y2=calculate([result[2],result[3],result[4]],new_data_x2)\r\nnew_data_x3=np.arange(7, 9.5, 0.1)\r\nnew_data_y3=calculate([result[5],result[6],result[7]],new_data_x3)\r\nnew_data_x=[]\r\nnew_data_y=[]\r\nnew_data_x.extend(new_data_x1)\r\nnew_data_x.extend(new_data_x2)\r\nnew_data_x.extend(new_data_x3)\r\nnew_data_y.extend(new_data_y1)\r\nnew_data_y.extend(new_data_y2)\r\nnew_data_y.extend(new_data_y3)\r\nprint(result)\r\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.linalg.solve", "matplotlib.pyplot.scatter", "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.plot", "numpy.array", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ElmiraGhorbani/align_iranian_national_id_card
[ "b1806deb269558ab70ff613911365f79b527632d" ]
[ "rotate_crop_with_HoughLines.py" ]
[ "# MIT License\n#\n# Copyright (c) 2019 https://github.com/ElmiiiRaa/align_iranian_national_id_card\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.\n#author : Elmira Ghorbani\n#email:[email protected]\n\nimport cv2\nimport numpy as np\nimport math\nimport operator\nimport random\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\n\n\ncards_cropped_by_eyes_path = 'outputs/cards_cropped_by_eyes/'\ncards_cropped_rotated_path = 'outputs/cards_cropped_rotated'\ncards_rotated_path = 'outputs/rotated_cards_by_HoughLines'\n\nfiles = [f for f in listdir(cards_cropped_by_eyes_path) if isfile(join(cards_cropped_by_eyes_path, f))]\n\ndef rotate(image, theta):\n \n (h, w) = image.shape[:2]\n center = (w / 2, h / 2)\n M = cv2.getRotationMatrix2D(center, theta, 1)\n rotated = cv2.warpAffine(image, M, (int(w), int(h)), cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255))\n return rotated\n\n\n\ndef dot(vA, vB):\n return vA[0]*vB[0]+vA[1]*vB[1]\n\n\n\ndef ang(lineA, lineB):\n # Get nicer vector form\n vA = [(lineA[0][0]-lineA[1][0]), (lineA[0][1]-lineA[1][1])]\n vB = [(lineB[0][0]-lineB[1][0]), (lineB[0][1]-lineB[1][1])]\n # Get dot prod\n dot_prod = dot(vA, vB)\n # Get magnitudes\n magA = dot(vA, vA)**0.5\n magB = dot(vB, vB)**0.5\n # Get cosine value\n cos_ = dot_prod/magA/magB\n # Get angle in radians and then convert to degrees\n angle = math.acos(dot_prod/magB/magA)\n # Basically doing angle <- angle mod 360\n ang_deg = math.degrees(angle)%360\n\n #mydegrees = math.degrees(myradians)\n #myradians = math.radians(mydegrees)\n\n if ang_deg-180>=0:\n # As in if statement\n return 360 - ang_deg\n else: \n\n return math.radians(ang_deg)\n\ndef crop(x1,x2,x3,x4,y1,y2,y3,y4,img):\n \n x1 = x1\n x2 = x2\n\n x3 = x3\n x4 = x4\n\n y1 = y1\n y2 = y2\n\n y3 = y3\n y4 = y4\n\n top_left_x = min([x1,x2,x3,x4])\n top_left_y = min([y1,y2,y3,y4])\n bot_right_x = max([x1,x2,x3,x4])\n bot_right_y = max([y1,y2,y3,y4])\n\n rotated = img\n\n cropped=rotated[top_left_y:bot_right_y, top_left_x:bot_right_x]\n crop_h , crop_w = cropped.shape[:2]\n rotated_h , rotated_w = rotated.shape[:2]\n\n if crop_h < 500 or crop_w <900:\n\n return rotated\n else:\n return cropped\n\n\ndef HoughLines():\n\n for file in files:\n img = cv2.imread(cards_cropped_by_eyes_path + file)\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n kernel = np.ones((5,5),np.float32)/25\n gray = cv2.filter2D(gray,-1,kernel)\n edges = cv2.Canny(gray,400,600,apertureSize = 5)\n cv2.imwrite(file,edges)\n\n \"\"\"\n cv2.imshow('image',cv2.resize(edges,(1000,630)))\n cv2.waitKey(0)\n\n \"\"\"\n lines = cv2.HoughLines(edges,1,np.pi/180,15)\n\n pointsListX1 =[]\n pointsListX2 =[]\n pointsListY1 =[]\n pointsListY2 =[]\n anglesList = []\n for i in range(8):\n for rho,theta in lines[i]:\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a*rho\n y0 = b*rho\n x1 = int(x0 + 1000*(-b))\n y1 =int(y0 + 1000*(a))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(a))\n angle = np.arctan2(y2 - y1, x2 - x1) * 180. / np.pi\n \n #draw whole detected line\n #cv2.line(img,(x1 ,y1),( x2,y2),(62,0,255),2)\n if x1<0:\n pointsListX1.append(x1)\n pointsListY1.append(y1)\n pointsListX2.append(x2)\n pointsListY2.append(y2)\n anglesList.append(angle)\n\n #print(x1 ,y1 ,' ', x2 ,y2 ,' ',angle )\n\n #bottom line\n index, value = max(enumerate(pointsListY1), key=operator.itemgetter(1))\n\n # draw bottom line\n #cv2.line(img,(pointsListX1[index] ,pointsListY1[index] ),( pointsListX2[index] ,pointsListY2[index]),(255,0,255),2)\n sub_y_frist_line = pointsListY2[index] - pointsListY1[index]\n\n #print(pointsListY1 , pointsListY2,anglesList)\n #print(sub_y_frist_line)\n\n #top line\n temp = []\n\n for indy in range(len(pointsListY2)):\n sub = pointsListY2[indy] - pointsListY1[indy] \n sub_y_2 = pointsListY2[index] - pointsListY2[indy]\n sub_y_1 = pointsListY1[index] - pointsListY1[indy]\n \n # print(sub,sub_y_1 ,sub_y_2)\n\n if sub_y_frist_line == 1:\n if sub > 1 and anglesList[indy] > 0 and anglesList[indy] > anglesList[index] and sub_y_2 >500 and sub_y_1 >500 :\n second_index=indy\n #print(indy)\n break\n else:\n if sub == 1 and anglesList[indy] > 0 and sub_y_2 >400 and sub_y_1 >400 :\n second_index=indy\n #print(indy)\n break\n \n elif sub_y_frist_line<0: \n tempL=[]\n for i in range(len(pointsListY1)):\n if pointsListY1[i] > 0 and pointsListY1[i] < pointsListY1[index] and anglesList[i] >= anglesList[index]:\n tempL.append(pointsListY1[i])\n indx, value = min(enumerate(tempL), key=operator.itemgetter(1))\n second_index=pointsListY1.index(value)\n \n\n else:\n if sub == 1 and anglesList[indy] > 0 and sub_y_2 > 0 and sub_y_1 > 0 :\n temp.append(pointsListY1[indy])\n ind, val = max(enumerate(temp), key=operator.itemgetter(1))\n second_index = pointsListY1.index(val)\n #print(second_index)\n \n #draw top line \n #cv2.line(img,(pointsListX1[second_index] ,pointsListY1[second_index] ),( pointsListX2[second_index] ,pointsListY2[second_index]),(255,0,255),2)\n # print( 'angles: (top , bottom) :', anglesList[second_index], anglesList[index])\n\n lineA =[[pointsListX1[index],pointsListY1[index] ],[pointsListX2[index],pointsListY2[index]]]\n lineB =[[pointsListX1[second_index],pointsListX1[second_index]],[pointsListX2[second_index],pointsListY2[second_index]]]\n angle =ang(lineA , lineB) \n #print(angle)\n\n if anglesList[index]== anglesList[second_index]:\n rotated=rotate(img , -(anglesList[index]-angle))\n\n else:\n rotated=rotate(img , (anglesList[second_index]-angle))\n\n save_cards_rotated_path = os.path.join(cards_rotated_path, file)\n cv2.imwrite(save_cards_rotated_path,rotated)\n\n #cv2.imshow('rotated',cv2.resize(rotated,(1000,630)))\n #cv2.waitKey(0)\n \n crop_img = crop(pointsListX1[index] ,pointsListX1[second_index] ,pointsListX2[index] ,pointsListX2[second_index] ,pointsListY1[index] ,pointsListY1[second_index] ,pointsListY2[index] ,pointsListY2[second_index],rotated) \n # cv2.imshow('crop',cv2.resize(crp,(1000,630)))\n save_crop_rotated_card = os.path.join(cards_cropped_rotated_path, file)\n cv2.imwrite(save_crop_rotated_card,crop_img)\n cv2.waitKey(0) \n" ]
[ [ "numpy.arctan2", "numpy.sin", "numpy.cos", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lunarknight00/Global_warming_data_app
[ "ea4d0f8d66e60671d8b4a41996cdf97e5666f6ee" ]
[ "old_plot.py" ]
[ "from flask import Flask,jsonify,request\nfrom .database import *\nimport json\nimport pandas as pd\nimport bokeh\n\nfrom requests import get\nfrom bokeh.plotting import figure, output_file, show\nfrom bokeh.palettes import inferno\nfrom bokeh.embed import components\n\n# api like data fetch func, not sure is working \ndef get_country_data(name):\n connect(host='mongodb://admin:[email protected]:15370/ass_3')\n connect('region')\n for e in Region.objects:\n country = e.to_json()\n country = json.loads(country)\n for country_name in country['country_in_region']:\n if country_name['_id'].lower() == name.lower():\n return jsonify(country)\n\n# use requests to fecth sigle country data,input value is country\ndef fetch_country_data(name):\n url = 'http://127.0.0.1:5000/admin/country'\n # name is the courntry name user input in the webpage\n query = {'country_name':name}\n response = get(url,params=query)\n return response.json()\n\n# use requests ,input value is region\ndef fetch_region_data(name):\n url = 'http://127.0.0.1:5000/admin/region'\n region = 'East Asia & Pacific'\n query = {'region_name':name}\n response = get(url,params=query)\n return response.json()\n\n\n# helper function\n\n# preprocess the json dictionary\n# input a counntry name and a json dict\n# output a tuple country name and a panadas data frame\ndef country_preprocess(country,dic):\n first_keys = [i for i in dic.keys()]\n for k in dic[first_keys[1]]:\n if k['_id'] == country:\n data = k['statistic']\n return (country,CO2_year(pd.DataFrame(data)))\n\n# co2 line pandas datetime change preprocess\n# output a two column data frame\n\ndef CO2_year(df):\n processed = df.iloc[:,1:3]\n processed['_id'] = pd.to_datetime(processed['_id'])\n print(processed)\n return processed\n\n\n\n### plot line change of one country\n\ndef plot_country(country,dic):\n name,processed = country_preprocess(country,dic)\n p = figure(plot_width=1000, plot_height=600, x_axis_type=\"datetime\",y_range = (0,10000))\n p.line(processed['_id'], processed['co2_emission'], color='navy', alpha=0.5,name=country)\n return p\n\n\n### plot multiplr lines in a region\n\n# helper function\n\ndef _country_preprocess(statistics,country):\n data = CO2_year(pd.DataFrame(statistics,columns = ['GDP','_id','co2_emission']))\n data.columns = ['year',country]\n return data\n \n\ndef region_preprocess(data,region):\n result = list()\n first_keys = [i for i in data.keys()]\n for d in data[first_keys[1]]:\n result.append(_country_preprocess(d['statistic'],d['_id']))\n return result\n\n\n# @app.route(\"/admin/plot\",methods = ['GET'])\ndef plot_region(data,region):\n nums = len(region_preprocess(data,region))\n processed = region_preprocess(data,region)\n countries = [processed[i].columns[1] for i in range(nums)]\n date_column = processed[0]['year']\n co2 = [processed[i][processed[i].columns[1]] for i in range(nums)]\n \n #initialize the figure\n numlines=len(co2)\n mypalette=inferno(numlines)\n \n p = figure(plot_width=1200, plot_height=600,x_axis_type=\"datetime\",title=\"CO2 emissions\")\n\n p.grid.grid_line_alpha=0.3\n p.xaxis.axis_label = 'Date'\n p.yaxis.axis_label = 'Co2 emissions'\n\n for i in range(len(countries)):\n p.line(date_column,co2[i],color=mypalette[i],legend = countries[i])\n p.legend.location = \"top_left\"\n return p\n\n# return one country statistics as chart\n\ndef co2_stat(country,dic):\n name,processed = country_preprocess(country,dic)\n processed.columns = ['year',name]\n return processed.describe()\n\n\n'''\nimplement example\n# Index page\[email protected]('/')\ndef index():\n\t# Determine the selected feature\n\tcurrent_feature_name = request.args.get(\"feature_name\")\n\tif current_feature_name == None:\n\t\tcurrent_feature_name = \"Sepal Length\"\n\t# Create the plot\n\tplot = create_figure(current_feature_name, 10)\n\t\t\n\t# Embed plot into HTML via Flask Render\n\tscript, div = components(plot)\n\treturn render_template(\"iris_index1.html\", script=script, div=div,\n\t\tfeature_names=feature_names, current_feature_name=current_feature_name)\n<html>\n<head>\n<link\n href=\"http://cdn.pydata.org/bokeh/release/bokeh-0.12.5.min.css\"\n rel=\"stylesheet\" type=\"text/css\">\n<link\n href=\"http://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.5.min.css\"\n rel=\"stylesheet\" type=\"text/css\">\n<script src=\"http://cdn.pydata.org/bokeh/release/bokeh-0.12.5.min.js\"></script>\n<script src=\"http://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.5.min.js\"></script>\n</head>\n<body>\n<H1>Iris Histogram</H1>\n<form action=\"/\">\n<select name=\"feature_name\">\n\t{% for feature in feature_names %}\n\t\t{% if feature == current_feature_name %}\n\t\t\t<option selected value=\"{{ feature }}\">{{ feature }}</option> \n\t\t{% else %} \n\t\t\t<option value=\"{{ feature }}\">{{ feature }}</option> \n\t\t{% endif %}\n\t{% endfor %}\n</select>\n<input type=\"submit\">\n</form>\n{{ script|safe }}\n{{ div|safe }}\n</body>\n</html>\n'''" ]
[ [ "pandas.to_datetime", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
mic-tae/leaf-audio
[ "0ebef7691754b7cbd407d2d1b9e7319cccb79427" ]
[ "example/train_test.py" ]
[ "# coding=utf-8\n# Copyright 2021 Google LLC.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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# python3\n\"\"\"Basic test case for running a single training step.\"\"\"\n\nimport os.path\n\nfrom absl import flags\nfrom absl import logging\nfrom absl.testing import parameterized\nimport gin\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\n\nfrom example import train\n\nFLAGS = flags.FLAGS\nCONFIG_FOLDER = os.path.join(os.path.dirname(__file__), 'configs/')\nDEFAULT_CONFIG = 'leaf'\n\n\ndef _parse_gin_config(config=DEFAULT_CONFIG, override=None):\n filename = os.path.join(CONFIG_FOLDER, config + '.gin')\n with open(filename, 'rt') as file_handle:\n gin.parse_config(file_handle)\n gin.parse_config(\"\"\"\n ConvNet.filters = [64, 128]\n \"\"\")\n if override is not None:\n gin.parse_config(override)\n\n\nclass TrainTest(parameterized.TestCase, tf.test.TestCase):\n\n def setUp(self):\n super().setUp()\n gin.clear_config()\n\n @parameterized.named_parameters(\n ('leaf', 'leaf'),\n ('leaf_custom', 'leaf_custom'),\n ('mel', 'mel'),\n ('sincnet', 'sincnet'),\n ('sincnet_plus', 'sincnet_plus'),\n ('tfbanks', 'tfbanks'),\n )\n def test_config(self, config):\n _parse_gin_config(config=config)\n self._run_single_epoch()\n\n def _run_single_epoch(self):\n num_examples = 100\n\n def as_dataset(self, *args, **kwargs):\n return tf.data.Dataset.from_generator(\n lambda: ({\n 'audio': np.ones(shape=(16000,), dtype=np.uint16),\n 'label': i % 12,\n } for i in range(num_examples)),\n output_types=self.info.features.dtype,\n output_shapes=self.info.features.shape,\n )\n\n model_dir = self.create_tempdir().full_path\n with tfds.testing.mock_data(\n num_examples=num_examples, as_dataset_fn=as_dataset):\n train.train(\n workdir=model_dir,\n dataset='speech_commands',\n num_epochs=1,\n )\n\n files_in_model_dir = tf.io.gfile.listdir(model_dir)\n logging.info('files_in_model_dir: %s', files_in_model_dir)\n some_expected_files = ['checkpoint.index', 'checkpoint.data-00000-of-00001']\n self.assertAllInSet(some_expected_files, files_in_model_dir)\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "tensorflow.io.gfile.listdir", "tensorflow.test.main", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
finbarrtimbers/pytorch-distillation
[ "76a4b335adbdffb56f104a81594e9abad398e0a5" ]
[ "networks.py" ]
[ "import torch\nimport torch.nn as nn\nimport torchvision.datasets as dsets\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\n\n# Image Preprocessing\ntransform = transforms.Compose([\n transforms.Scale(40),\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(32),\n transforms.ToTensor()])\n\n# 3x3 Convolution\ndef conv3x3(in_channels, out_channels, stride=1):\n return nn.Conv2d(in_channels, out_channels, kernel_size=3,\n stride=stride, padding=1, bias=False)\n\n\n# Residual Block\nclass ResidualBlock(nn.Module):\n def __init__(self, in_channels, out_channels, stride=1, downsample=None):\n super(ResidualBlock, self).__init__()\n self.conv1 = conv3x3(in_channels, out_channels, stride)\n self.bn1 = nn.BatchNorm2d(out_channels)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(out_channels, out_channels)\n self.bn2 = nn.BatchNorm2d(out_channels)\n self.downsample = downsample\n\n def forward(self, x):\n residual = x\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.conv2(out)\n out = self.bn2(out)\n if self.downsample:\n residual = self.downsample(x)\n out += residual\n out = self.relu(out)\n return out\n\nclass ResNet(nn.Module):\n def __init__(self, block, layers, num_classes=10):\n super(ResNet, self).__init__()\n self.in_channels = 16\n self.conv = conv3x3(3, 16)\n self.bn = nn.BatchNorm2d(16)\n self.relu = nn.ReLU(inplace=True)\n self.layer1 = self.make_layer(block, 16, layers[0])\n self.layer2 = self.make_layer(block, 32, layers[0], 2)\n self.layer3 = self.make_layer(block, 64, layers[1], 2)\n self.avg_pool = nn.AvgPool2d(8)\n self.fc = nn.Linear(64, num_classes)\n\n def make_layer(self, block, out_channels, blocks, stride=1):\n downsample = None\n if (stride != 1) or (self.in_channels != out_channels):\n downsample = nn.Sequential(\n conv3x3(self.in_channels, out_channels, stride=stride),\n nn.BatchNorm2d(out_channels))\n layers = []\n layers.append(block(self.in_channels, out_channels, stride, downsample))\n self.in_channels = out_channels\n for i in range(1, blocks):\n layers.append(block(out_channels, out_channels))\n return nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.conv(x)\n out = self.bn(out)\n out = self.relu(out)\n out = self.layer1(out)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.avg_pool(out)\n out = out.view(out.size(0), -1)\n out = self.fc(out)\n return out\n\ndeep_resnet = ResNet(ResidualBlock, [2, 2, 2, 2, 2])\nshallow_resnet = ResNet(ResidualBlock, [2, 2])\n" ]
[ [ "torch.nn.Sequential", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.AvgPool2d", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
LeungTsang/Dense-RepPoints
[ "8169da58aac7b1418627e43618e8584b39bbb9e5" ]
[ "mmdet/core/bbox/assigners/point_box_assigner.py" ]
[ "import torch\n\nfrom .assign_result import AssignResult\nfrom .base_assigner import BaseAssigner\n\n\nclass PointBoxAssigner(BaseAssigner):\n \"\"\"Assign a corresponding gt bbox or background to each point.\n\n Each proposals will be assigned with `0`, or a positive integer\n indicating the ground truth index.\n\n - 0: negative sample, no assigned gt\n - positive integer: positive sample, index (1-based) of assigned gt\n\n \"\"\"\n\n def __init__(self, scale=4, pos_num=3):\n self.scale = scale\n self.pos_num = pos_num\n\n def assign(self, points, gt_bboxes, gt_bboxes_ignore=None, gt_labels=None):\n \"\"\"Assign gt to bboxes.\n\n This method assign a gt bbox to every point, each bbox\n will be assigned with 0, or a positive number.\n 0 means negative sample, positive number is the index (1-based) of\n assigned gt.\n The assignment is done in following steps, the order matters.\n\n 1. assign every points to 0\n 2. for each gt box, we find the k most closest points to the\n box center and assign the gt bbox to those points, we also record\n the minimum distance from each point to the closest gt box. When we\n assign the bbox to the points, we check whether its distance to the\n points is closest.\n\n Args:\n points (Tensor): points to be assigned, shape(n, 3) while last\n dimension stands for (x, y, stride).\n gt_bboxes (Tensor): Groundtruth boxes, shape (k, 4).\n gt_bboxes_ignore (Tensor, optional): Ground truth bboxes that are\n labelled as `ignored`, e.g., crowd boxes in COCO.\n gt_labels (Tensor, optional): Label of gt_bboxes, shape (k, ).\n\n Returns:\n :obj:`AssignResult`: The assign result.\n \"\"\"\n if points.shape[0] == 0 or gt_bboxes.shape[0] == 0:\n raise ValueError('No gt or bboxes')\n points_range = torch.arange(points.shape[0])\n points_xy = points[:, :2]\n points_stride = points[:, 2]\n points_lvl = torch.log2(points_stride).int() # [3...,4...,5...,6...,7...]\n lvl_min, lvl_max = points_lvl.min(), points_lvl.max()\n num_gts, num_points = gt_bboxes.shape[0], points.shape[0]\n\n # assign gt box\n gt_bboxes_x = 0.5 * (gt_bboxes[:, 0] + gt_bboxes[:, 2])\n gt_bboxes_y = 0.5 * (gt_bboxes[:, 1] + gt_bboxes[:, 3])\n gt_bboxes_xy = torch.stack([gt_bboxes_x, gt_bboxes_y], -1)\n gt_bboxes_w = gt_bboxes[:, 2] - gt_bboxes[:, 0]\n gt_bboxes_h = gt_bboxes[:, 3] - gt_bboxes[:, 1]\n gt_bboxes_wh = torch.stack([gt_bboxes_w, gt_bboxes_h], -1)\n gt_bboxes_wh = torch.clamp(gt_bboxes_wh, min=1e-6)\n gt_bboxes_lvl = (0.5 * (torch.log2(gt_bboxes_w / self.scale) + torch.log2(gt_bboxes_h / self.scale))).int()\n gt_bboxes_lvl = torch.clamp(gt_bboxes_lvl, min=lvl_min, max=lvl_max)\n\n # stores the assigned gt index of each point\n assigned_gt_inds = points.new_zeros((num_points,), dtype=torch.long)\n # stores the assigned gt dist (to this point) of each point\n assigned_gt_dist = points.new_full((num_points,), float('inf'))\n\n for idx in range(num_gts):\n gt_lvl = gt_bboxes_lvl[idx]\n # get the index of points in this level\n lvl_idx = gt_lvl == points_lvl\n points_index = points_range[lvl_idx]\n # get the points in this level\n lvl_points = points_xy[lvl_idx, :]\n # get the center point of gt\n gt_point = gt_bboxes_xy[[idx], :]\n # get width and height of gt\n gt_wh = gt_bboxes_wh[[idx], :]\n # compute the distance between gt center and all points in this level\n points_gt_dist = ((lvl_points - gt_point) / gt_wh).norm(dim=1)\n # find the nearest k points to gt center in this level\n min_dist, min_dist_index = torch.topk(-points_gt_dist, self.pos_num)\n # the index of nearest k points to gt center in this level\n min_dist_points_index = points_index[min_dist_index]\n less_than_recorded_index = min_dist < assigned_gt_dist[min_dist_points_index]\n min_dist_points_index = min_dist_points_index[less_than_recorded_index]\n # assign the result\n assigned_gt_inds[min_dist_points_index] = idx + 1\n assigned_gt_dist[min_dist_points_index] = min_dist[less_than_recorded_index]\n\n if gt_labels is not None:\n assigned_labels = assigned_gt_inds.new_zeros((num_points,))\n pos_inds = torch.nonzero(assigned_gt_inds > 0).squeeze()\n if pos_inds.numel() > 0:\n assigned_labels[pos_inds] = gt_labels[\n assigned_gt_inds[pos_inds] - 1]\n else:\n assigned_labels = None\n\n return AssignResult(\n num_gts, assigned_gt_inds, None, labels=assigned_labels)\n" ]
[ [ "torch.topk", "torch.log2", "torch.nonzero", "torch.arange", "torch.stack", "torch.clamp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bintsi/ICAM
[ "17548567d0c77e315b3bad44f85472c164712d1b" ]
[ "utils.py" ]
[ "##################################################\n# Authors:\n# {Christian F. Baumgartner} ([email protected]),\n# {Lisa M. Koch} ([email protected])\n# https://github.com/baumgach/vagan-code\n##################################################\n\nimport nibabel as nib\nimport numpy as np\nimport os\n\n\ndef ncc(a, v, zero_norm=True):\n\n a = a.flatten()\n v = v.flatten()\n\n if zero_norm:\n\n a = (a - np.mean(a)) / (np.std(a) * len(a))\n v = (v - np.mean(v)) / np.std(v)\n\n else:\n\n a = (a) / (np.std(a) * len(a))\n v = (v) / np.std(v)\n\n return np.correlate(a, v)\n\n\ndef norm_l2(a, v):\n\n a = a.flatten()\n v = v.flatten()\n\n a = (a - np.mean(a)) / (np.std(a) * len(a))\n v = (v - np.mean(v)) / np.std(v)\n\n return np.mean(np.sqrt(a**2 + v**2))\n\n\ndef all_argmax(arr, axis=None):\n\n return np.argwhere(arr == np.amax(arr, axis=axis))\n\n\ndef makefolder(folder):\n '''\n Helper function to make a new folder if doesn't exist\n :param folder: path to new folder\n :return: True if folder created, False if folder already exists\n '''\n if not os.path.exists(folder):\n os.makedirs(folder)\n return True\n return False\n\n\ndef load_nii(img_path):\n '''\n Shortcut to load a nifti file\n '''\n\n nimg = nib.load(img_path)\n return nimg.get_data(), nimg.affine, nimg.header\n\n\ndef save_nii(img_path, data, affine, header):\n '''\n Shortcut to save a nifty file\n '''\n\n nimg = nib.Nifti1Image(data, affine=affine, header=header)\n nimg.to_filename(img_path)\n\n\ndef create_and_save_nii(data, img_path):\n\n img = nib.Nifti1Image(data, np.eye(4))\n nib.save(img, img_path)\n\n\nclass Bunch:\n # Useful shortcut for making struct like contructs\n # Example:\n # mystruct = Bunch(a=1, b=2)\n # print(mystruct.a)\n # >>> 1\n def __init__(self, **kwds):\n self.__dict__.update(kwds)\n\n\ndef convert_to_uint8(image):\n image = image - image.min()\n image = 255.0*np.divide(image.astype(np.float32), image.max())\n return image.astype(np.uint8)\n\n\ndef normalise_image(image):\n '''\n make image zero mean and unit standard deviation\n '''\n\n img_o = np.float32(image.copy())\n m = np.mean(img_o)\n s = np.std(img_o)\n return np.divide((img_o - m), s)\n\n\ndef map_image_to_intensity_range(image, min_o, max_o, percentiles=0):\n\n # If percentile = 0 uses min and max. Percentile >0 makes normalisation more robust to outliers.\n\n if image.dtype in [np.uint8, np.uint16, np.uint32]:\n assert min_o >= 0, 'Input image type is uintXX but you selected a negative min_o: %f' % min_o\n\n if image.dtype == np.uint8:\n assert max_o <= 255, 'Input image type is uint8 but you selected a max_o > 255: %f' % max_o\n\n min_i = np.percentile(image, 0 + percentiles)\n max_i = np.percentile(image, 100 - percentiles)\n\n image = (np.divide((image - min_i), max_i - min_i) * (max_o - min_o) + min_o).copy()\n\n image[image > max_o] = max_o\n image[image < min_o] = min_o\n\n return image\n\n\ndef normalise_images(X):\n '''\n Helper for making the images zero mean and unit standard deviation i.e. `white`\n '''\n\n X_white = np.zeros(X.shape, dtype=np.float32)\n\n for ii in range(X.shape[0]):\n\n Xc = X[ii, :, :, :]\n mc = Xc.mean()\n sc = Xc.std()\n\n Xc_white = np.divide((Xc - mc), sc)\n\n X_white[ii, :, :, :] = Xc_white\n\n return X_white.astype(np.float32)\n" ]
[ [ "numpy.amax", "numpy.sqrt", "numpy.eye", "numpy.percentile", "numpy.std", "numpy.mean", "numpy.correlate", "numpy.zeros", "numpy.divide" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EvilBoom/DNA
[ "9615a1c611aa426e03cd680b91b02f8cc646fef0" ]
[ "attention/pytorch_attention/dataloaders.py" ]
[ "# _*_ coding: utf-8 _*_\n# @Time : 2021/12/6 15:16\n# @Author : 张宝宇\n# @Version:V 1.0\n# @File : dataloaders.py\n# @desc :\nimport torch.utils.data as data\n\nfrom att_data import AttDataset\n\n\ndef att_dataloader(u_data=None, label=None, batch_size=None, shuffle=None, num_workers=0):\n dataset = AttDataset(u_data, label)\n data_loader = data.DataLoader(dataset=dataset,\n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=num_workers\n )\n return data_loader\n" ]
[ [ "torch.utils.data.DataLoader" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
HumbertoDiego/django-ajustamento-redes-nivelamento
[ "47912ccb4ba9fc29709add18bab688af50cfb582" ]
[ "ajunivel/NivParamet.py" ]
[ "# -*- coding: utf-8 -*-\r\nimport matplotlib\r\nmatplotlib.use(\"agg\")\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.stats import chi2\r\nfrom numpy import size, array, linspace, zeros, size\r\nfrom numpy.linalg import inv\r\nfrom math import sqrt\r\nfrom pandas import DataFrame\r\nimport io\r\nimport base64\r\n\r\ndef parametrico(c, x , auto, dp_na_4col):\r\n ############ 1ª etapa - leitura do arquivo texto\r\n print(DataFrame(c))\r\n ############ 2ª etapa - pré processamento\r\n # gravando os dados em variáveis separadas\r\n re = []\r\n vante =[]\r\n observado = []\r\n dist = []\r\n dpinjuc = []\r\n aviso = ''\r\n for i in range(0, size(c, 0)): # converter numeros com virg para numeros com ponto\r\n re.append(str(c[i][0]).replace(',','.')) # 1ª col são estações a ré\r\n vante.append(str(c[i][1]).replace(',','.')) # 2ª col são estações a vante\r\n observado.append(str(c[i][2]).replace(',','.')) # 3ª col são os desniveis observados\r\n print(observado[i])\r\n if c[i][0] == 0:\r\n dpinjuc.append(str(c[i][3]).replace(',','.'))\r\n dist.append(0)\r\n auto = False\r\n aviso = 'Aviso: Desvio Padrão convertido para manual devido a presença de Injuções'\r\n else:\r\n dpinjuc.append(0)\r\n dist.append(str(c[i][3]).replace(',','.'))\r\n observado = array(observado, float)\r\n dist = array(dist, float)\r\n dpinjuc = array(dpinjuc, float)\r\n\r\n RNsinvantes = []\r\n Pontos = []\r\n for i in range(0, len(vante)):\r\n try:\r\n array(vante[i], float)\r\n RNsinvantes.append(vante[i])\r\n except ValueError:\r\n RNsinvantes.append(0)\r\n Pontos.append(vante[i])\r\n\r\n RNsinres =[]\r\n for i in range(0, len(re)):\r\n try:\r\n array(re[i], float)\r\n RNsinres.append(re[i])\r\n except ValueError:\r\n RNsinres.append(0)\r\n Pontos.append(re[i])\r\n RNsinvantes = array(RNsinvantes, float)\r\n RNsinres = array(RNsinres, float)\r\n\r\n # qtPontos (parametros) = Qt de colunas da matriz A (u)\r\n qtPontos = len(set(Pontos))\r\n # qtEq = Qt de linhas da matriz A (n)\r\n qtEq = len(observado)\r\n # Graus de liberdade - Degrees of freedom - df\r\n df = qtEq - qtPontos\r\n # Lb = formado pelos termos independentes da equacao\r\n L0 = RNsinres - RNsinvantes\r\n Lb = observado + L0\r\n\r\n # Em vanteere: float devem ser trocadas por zero\r\n vanteere = re + vante\r\n for i in vanteere:\r\n try:\r\n array(i, float)\r\n local = vanteere.index(i)\r\n vanteere[local] = 0\r\n except ValueError:\r\n pass\r\n # Em vanteere: strings devem ser trocadas por Ids(1,2,3...)\r\n k = 1\r\n Incognitas =[]\r\n for i in vanteere:\r\n if type(i) == str:\r\n Incognitas.append(i)\r\n while i in vanteere:\r\n local = vanteere.index(i)\r\n vanteere[local] = k\r\n k = k+1\r\n res = array(vanteere[:qtEq],float)\r\n vantes = array(vanteere[qtEq:],float)\r\n\r\n ### Modelagem Matemática: Método paramétrico de ajuste dos parâmetros X=(h1,h2,h3,...)\r\n ## A*X = Lb + V e Xa = inv(A'*P*A)*(A'*P*L)\r\n A= montA(vantes, res)\r\n # Montagem da matriz P de pesos\r\n sigmapriori = 1 ## em [mm^2]\r\n if dp_na_4col:\r\n auto = False\r\n SigmaLb , dp = montSigmaLb_dp_na_4col(dist, dpinjuc)\r\n else:\r\n SigmaLb , dp = montSigmaLb(dist, x, dpinjuc)\r\n pesos = sigmapriori*SigmaLb\r\n # X=inv(A'PA)A'PLb\r\n X= Xa_parametrico(A,pesos,Lb)\r\n # V=A*X-Lb [m]\r\n V=A.dot(X)-Lb\r\n\r\n ####################################### Estatistics #######################################################\r\n #################################### Teste chi^2 ##########################################################\r\n # sigma posterioti = V'PV/gl\r\n sigmaposteriori= V.transpose().dot(pesos).dot(V)/(df) ## em [m^2]\r\n quicalc = sigmaposteriori*df/sigmapriori\r\n signif = 0.05\r\n quitabmax = chi2.ppf(1-signif/2, df)\r\n quitabmin = chi2.ppf(signif/2, df)\r\n quicalcideal = (quitabmax + quitabmin)/2\r\n # automatizacao do teste Chi²\r\n if auto:\r\n if quicalc>quicalcideal:\r\n while (quicalc-quicalcideal>0.5):\r\n SigmaLb , dp = montSigmaLb(dist, x, dpinjuc)\r\n # nãp precisa repetir a fórmula X=inv(A'PA)A'PLb pq X é cte independente de variações lineares em Pesos\r\n # se X, A, Lb são ctes então V=A.dot(X)-Lb é cte\r\n quicalc = V.transpose().dot(SigmaLb).dot(V)\r\n x = x+1\r\n else:\r\n while (quicalcideal-quicalc>0.1):\r\n print(x)\r\n SigmaLb , dp = montSigmaLb(dist, x, dpinjuc)\r\n # nãp precisa repetir a fórmula X=inv(A'PA)A'PLb pq X é cte independente de variações lineares em Pesos\r\n # se X, A, Lb são ctes então V=A.dot(X)-Lb é cte\r\n quicalc = V.transpose().dot(SigmaLb).dot(V)\r\n x = x - 0.1\r\n sigmaposteriori= V.transpose().dot(SigmaLb).dot(V)/(df) ## em [m^2]\r\n pesos = sigmapriori*SigmaLb\r\n if quicalc>quitabmax or quicalc<quitabmin:\r\n aviso2 = 'Aviso: Aumentar o desvio padrão inicial => Diminuir o Valor X^2 de teste'\r\n\r\n # # La=A*X ou La=Lb+V\r\n La=A.dot(X)\r\n La = La - L0\r\n dp = array(dp, float)\r\n var = dp*dp\r\n\r\n ####################################### MVC ##############################################\r\n SigmaXa = estatistics_sigmaXa(sigmaposteriori, A, pesos) ## em [m^2]\r\n SigmaLa = estatistics_sigmaLa(sigmaposteriori, A, pesos) ## em [m^2]\r\n SigmaV = estatistics_sigmaV(sigmapriori, A, pesos) ## em [m^2]\r\n desvio_hi = get_dp_hi(SigmaXa) ## em [m]\r\n desvio_vi = get_dp_vi(SigmaV) ## em [m]\r\n\r\n ####################################### Teste Baarda ######################################\r\n wi = Wi(V, desvio_vi)\r\n a0 = signif/qtEq\r\n aceitabaarda = sqrt(chi2.pdf(a0, 1))\r\n aceitar = []\r\n for i in range(0, len(wi)):\r\n if wi[i]<aceitabaarda and wi[i]>-aceitabaarda:\r\n aceitar.append('aceito')\r\n else:\r\n aceitar.append('ñ aceito')\r\n ####################################### Grafico Analise Qui-quadrado ############################\r\n base64_fdpqui= grafico_teste_hipotesebicaudal(quicalc, signif, df)\r\n\r\n dicionario = dict(c=c, qtPontos=qtPontos, qtEq=qtEq, df=df, Lb=Lb, Incognitas=Incognitas, x=x, A=A, dp=dp, aviso=aviso, var=var, pesos=pesos, X=X,\r\n V=V, La=La, sigmaposteriori=sigmaposteriori, sigmapriori=1, SigmaXa=SigmaXa, desvio_hi=desvio_hi, desvio_vi=desvio_vi, wi=wi,\r\n a0=a0, aceitabaarda=aceitabaarda, aceitar=aceitar,SigmaLa=SigmaLa, SigmaV=SigmaV, signif=signif, quitabmaxbicaudal = quitabmax,\r\n quitabminbicaudal = quitabmin, quicalc = quicalc, dp_na_4col=dp_na_4col,base64_fdpqui=base64_fdpqui)\r\n #print(dicionario)\r\n return dicionario\r\n\r\ndef grafico_teste_hipotesebicaudal(quicalc, signif, df):\r\n x = []\r\n x.append(linspace(0, chi2.ppf(signif/2, df), 100))\r\n x.append(linspace(chi2.ppf(signif/2, df), chi2.ppf(signif/2, df) + 0.2*(chi2.ppf(1-(signif/2), df)-chi2.ppf(signif/2, df)), 100))\r\n x.append(linspace(chi2.ppf(signif/2, df) + 0.2*(chi2.ppf(1-(signif/2), df)-chi2.ppf(signif/2, df)),\r\n chi2.ppf(signif/2, df) + 0.4*(chi2.ppf(1-(signif/2), df)-chi2.ppf(signif/2, df)), 100))\r\n x.append(linspace(chi2.ppf(signif/2, df) + 0.4*(chi2.ppf(1-(signif/2), df)-chi2.ppf(signif/2, df)),\r\n chi2.ppf(signif/2, df) + 0.6*(chi2.ppf(1-(signif/2), df)-chi2.ppf(signif/2, df)), 100))\r\n x.append(linspace(chi2.ppf(signif/2, df) + 0.6*(chi2.ppf(1-(signif/2), df)-chi2.ppf(signif/2, df)),\r\n chi2.ppf(signif/2, df) + 0.8*(chi2.ppf(1-(signif/2), df)-chi2.ppf(signif/2, df)), 100))\r\n x.append(linspace(chi2.ppf(signif/2, df) + 0.8*(chi2.ppf(1-(signif/2), df)-chi2.ppf(signif/2, df)), chi2.ppf(1-(signif/2), df), 100))\r\n x.append(linspace(chi2.ppf(1-(signif/2), df), chi2.ppf(0.99, df), 100))\r\n\r\n\r\n if df ==1:\r\n maxY = 2\r\n else:\r\n maxY = 1.02 * max(chi2.pdf(x[0], df).tolist() + chi2.pdf(x[1], df).tolist() + chi2.pdf(x[2], df).tolist() + chi2.pdf(x[3], df).tolist() +\r\n chi2.pdf(x[4], df).tolist() + chi2.pdf(x[5], df).tolist())\r\n fig, ax = plt.subplots(1, 1)\r\n ax.plot(x[0], chi2.pdf(x[0], df), 'b-', lw=3, alpha=0.7)\r\n ax.plot(x[1], chi2.pdf(x[1], df), 'b-', lw=3, alpha=0.7)\r\n ax.plot(x[2], chi2.pdf(x[2], df), 'b-', lw=3, alpha=0.7)\r\n ax.plot(x[3], chi2.pdf(x[3], df), 'b-', lw=3, alpha=0.7)\r\n ax.plot(x[4], chi2.pdf(x[4], df), 'b-', lw=3, alpha=0.7)\r\n ax.plot(x[5], chi2.pdf(x[5], df), 'b-', lw=3, alpha=0.7)\r\n ax.plot(x[6], chi2.pdf(x[6], df), 'b-', lw=3, alpha=0.7)\r\n\r\n ax.fill_between(x[0], 0, maxY, facecolor='red', alpha=0.8)\r\n ax.fill_between(x[1], 0, maxY, facecolor='yellow', alpha=0.6)\r\n ax.fill_between(x[2], 0, maxY, facecolor='green', alpha=0.6)\r\n ax.fill_between(x[2], 0, maxY, facecolor='yellow', alpha=0.6)\r\n ax.fill_between(x[3], 0, maxY, facecolor='green', alpha=0.6)\r\n ax.fill_between(x[4], 0, maxY, facecolor='green', alpha=0.6)\r\n ax.fill_between(x[4], 0, maxY, facecolor='yellow', alpha=0.6)\r\n ax.fill_between(x[5], 0, maxY, facecolor='yellow', alpha=0.6)\r\n ax.fill_between(x[6], 0, maxY, facecolor='red', alpha=0.8)\r\n\r\n plt.axvline(quicalc, color='k', linewidth='2')\r\n\r\n if df ==1:\r\n limit = [0, 6, 0, maxY]\r\n else:\r\n limit = [0, chi2.ppf(0.99, df), 0, maxY]\r\n plt.axis(limit)\r\n plt.grid(True)\r\n plt.xlabel('Significância')\r\n plt.ylabel('Chi^2(signif, %s gl)' %df)\r\n #path2 = os.path.join(os.getcwd(),'ajunivel','static','images','fdpqui.png')\r\n #print(path2)\r\n #plt.savefig(path2)\r\n my_stringIObytes = io.BytesIO()\r\n plt.savefig(my_stringIObytes, format='jpg')\r\n plt.close()\r\n my_stringIObytes.seek(0)\r\n my_base64_jpgData = base64.b64encode(my_stringIObytes.read())\r\n #print(my_base64_jpgData)\r\n return my_base64_jpgData.decode(\"utf-8\")\r\n\r\ndef txt2matrix(filename):\r\n f=open(filename, 'r')\r\n c=[]\r\n for line in f:\r\n c.append(line.split())\r\n d = array(c, float)\r\n return d\r\n\r\ndef montSigmaLb(dist, X, dpinjuc):\r\n P = zeros((size(dist, 0), size(dist, 0)), float)\r\n dp = []\r\n for i in range(size(dist, 0)):\r\n if dist[i] == 0:\r\n dp.append(dpinjuc[i])\r\n else:\r\n dp.append(X*sqrt(dist[i])/1000) # dp em m\r\n for i in range(size(dist, 0)):\r\n P[i, i] = 1/(dp[i]*dp[i]) # sigmaprio convertido pra metro^2\r\n return P, dp\r\n\r\ndef montSigmaLb_dp_na_4col(dist, dpinjuc):\r\n P = zeros((size(dist, 0), size(dist, 0)), float)\r\n dp = dist + dpinjuc\r\n for i in range(size(dp, 0)):\r\n P[i, i] = 1/(dp[i]*dp[i]) # sigmaprio convertido pra metro^2\r\n return P, dp\r\n\r\ndef montA(vante, re):\r\n re =array(re,int)\r\n vante=array(vante,int)\r\n qtPontos = int(max(vante.tolist() + re.tolist()))\r\n qtEq = len(re)\r\n print(\"aqui\",qtPontos,qtEq)\r\n print(\"aqui\",int(qtPontos),qtEq)\r\n A= zeros((qtEq,qtPontos),float)\r\n for i in range(0,qtEq):\r\n if re[i]!=0:\r\n print(re[i])\r\n A[i][re[i] - 1]=-1\r\n for i in range(0,qtEq):\r\n if vante[i]!=0:\r\n A[i][vante[i] - 1]=1\r\n return A\r\n\r\ndef Xa_parametrico(A,P,Lb):\r\n # Retorna o resultado de Xa = inv(A'*P*A)*A'*P*Lb\r\n print(\"A = \", DataFrame(A))\r\n x = A.transpose().dot(P).dot(A)\r\n print(\"A'PA = \", DataFrame(x))\r\n x = inv(x)\r\n print(\"inv(A'PA) = \",DataFrame(x))\r\n x = x.dot(A.transpose().dot(P).dot(Lb))\r\n print(\"inv(A'PA)A'PLb = \",DataFrame(x))\r\n return x\r\n\r\ndef estatistics_sigmaXa(sigma2prio,A,P):\r\n # SigmaXa - MVC do valores de X\r\n # x = A.transpose().dot(P).dot(A)\r\n # print DataFrame(A.transpose().dot(P).dot(A))\r\n # print det(A.transpose().dot(P).dot(A))\r\n # x = inv(x)\r\n return sigma2prio*inv(A.transpose().dot(P).dot(A))\r\n\r\ndef estatistics_sigmaLa(sigma2,A,P):\r\n # SimgaLa - MVC dos valores de La\r\n N = inv(A.transpose().dot(P).dot(A))\r\n return (A.dot(N).dot(A.transpose()))\r\n\r\ndef estatistics_sigmaV(sigma2,A,P):\r\n # SimgaV - MVC dos residuos\r\n N = inv(A.transpose().dot(P).dot(A))\r\n return sigma2*(inv(P) - A.dot(N).dot(A.transpose()))\r\n\r\ndef Wi(V, desvio_vi):\r\n wi = []\r\n try:\r\n for i in range(0,len(V)):\r\n wi.append(V[i]/desvio_vi[i])\r\n except:\r\n for i in range(0, len(V)):\r\n wi.append(None)\r\n return wi\r\n\r\ndef get_dp_hi(SigmaXa):\r\n desvio_hi=[]\r\n try:\r\n for i in range(0,len(SigmaXa)):\r\n desvio_hi.append(sqrt(SigmaXa[i][i]))\r\n except ValueError:\r\n for i in range(0, len(SigmaXa)):\r\n desvio_hi.append(None)\r\n return desvio_hi\r\n\r\ndef get_dp_vi(SigmaV):\r\n desvio_vi=[]\r\n try:\r\n for i in range(0,len(SigmaV)):\r\n desvio_vi.append(sqrt(SigmaV[i][i]))\r\n except ValueError:\r\n for i in range(0, len(SigmaV)):\r\n desvio_vi.append(None)\r\n return desvio_vi\r\n" ]
[ [ "scipy.stats.chi2.ppf", "matplotlib.pyplot.axvline", "scipy.stats.chi2.pdf", "numpy.linalg.inv", "matplotlib.use", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "pandas.DataFrame", "numpy.size", "matplotlib.pyplot.grid", "matplotlib.pyplot.axis", "matplotlib.pyplot.close", "matplotlib.pyplot.xlabel", "numpy.array", "numpy.zeros", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
trisct/DIST-Renderer
[ "18e8494f07bfa6487710afacda563a899d74e5d2" ]
[ "core_orthogonal_archived/sdfrenderer/renderer_orthogonal.py" ]
[ "import os, sys\nimport torch\nimport torch.nn as nn\nimport numpy as np\nsys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))\nfrom core.utils.decoder_utils_plaintest import decode_sdf, decode_sdf_gradient\nfrom core.visualize.profiler import Profiler\nfrom core.utils.render_utils import depth2normal\nimport copy\nimport time\nimport matplotlib.pyplot as plt\n\nclass SDFRenderer(object):\n def __init__(self, decoder, img_hw=None, march_step=50, buffer_size=5, ray_marching_ratio=1.5, max_sample_dist=0.2, radius=1.0, threshold=5e-5, use_gpu=True, is_eval=True):\n self.decoder = decoder\n print(f'[In renderer] Setting device to {next(self.decoder.parameters()).device}')\n self.device = next(self.decoder.parameters()).device\n if is_eval:\n self.decoder.eval()\n self.march_step = march_step\n self.buffer_size = buffer_size\n self.max_sample_dist = max_sample_dist\n self.ray_marching_ratio = ray_marching_ratio\n self.radius = radius\n self.threshold = threshold\n\n self.img_hw = img_hw\n\n print(f'[In renderer] showing candidate devices at line 40...')\n self.imgmap_init = self.init_imgmap(self.img_hw)\n self.imgmap_init.requires_grad=False\n\n\n if use_gpu:\n if torch.cuda.device_count() == 0:\n raise ValueError('No GPU device found.')\n self.imgmap_init = self.imgmap_init.to(self.device) # (H*W)\n\n def get_grid_and_rays(self):\n print(f'Getting camera pos and rays')\n x = torch.linspace(-1, 1, self.img_hw[1], device=self.device)\n y = torch.linspace(-1, 1, self.img_hw[0], device=self.device)\n grid_y, grid_x = torch.meshgrid(y, x)\n grid_z = torch.ones_like(grid_x, device=self.device) * -1\n grid = torch.stack([grid_x, grid_y, grid_z], dim=0).reshape(3,-1) # [3, H*W]\n #print(f'[In render_depth] grid = {grid.shape}')\n \n cam_rays = torch.zeros(3, 1, device=self.device)\n cam_rays[2] = 1.\n cam_rays = cam_rays.expand(3, self.img_hw[0]*self.img_hw[1])\n #print(f'| New cam rays = {cam_rays.shape}')\n\n maxbound_zdepth = torch.ones(self.img_hw[0]*self.img_hw[1], device=self.device) * 2 # always 2\n init_zdepth = torch.zeros(self.img_hw[0]*self.img_hw[1], device=self.device) # always 0\n\n return grid, cam_rays, init_zdepth, maxbound_zdepth\n\n\n def init_imgmap(self, img_hw):\n h, w = img_hw\n imgmap_init = torch.zeros(h, w)\n return imgmap_init\n\n def normalize_vectors(self, x):\n '''\n normalize the vector by the first dim\n '''\n norm = torch.norm(x, p=2, dim=0).expand_as(x)\n eps = 1e-12\n x = x.div(norm + eps)\n return x\n\n\n def generate_point_samples(self, cam_pos, cam_rays, Zdepth, has_zdepth_grad=False):\n '''\n Input:\n - cam_pos\ttype torch.Tensor (3, N)\n - cam_rays\ttype torch.Tensor (3)\n - Zdepth\ttype torch.Tensor (N)\n Return:\n - points\ttype torch.Tensor (3, N)\n '''\n if not has_zdepth_grad:\n Zdepth = Zdepth.detach()\n N = Zdepth.shape[0]\n if N == 0:\n raise ValueError('No valid depth.')\n cam_pos_pad = cam_pos # (3, N)\n \n Zdepth_pad = Zdepth[None,:].repeat(3,1) # (3, N)\n points = cam_rays * Zdepth_pad + cam_pos_pad # (3, N)\n \n if not points.requires_grad:\n points.requires_grad=True\n return points\n\n def get_distance_from_origin(self, cam_pos, cam_rays):\n '''\n get_distance_from_origin\n Input:\n - cam_pos\ttype torch.FloatTensor (3, H*W)\n - cam_rays\ttype torch.FloatTensor (3)\n '''\n print(f'[In get_distance_from_origin] cam_rays.shape = {cam_rays.shape}')\n N = cam_pos.shape[1]\n cam_pos_pad = cam_pos # (3, N)\n \n p, q = cam_pos_pad, cam_rays # (3, N), (3, N)\n ptq = (p * q).sum(0) # (N)\n dist = p - ptq[None,:].repeat(3,1) * q # (3, N)\n dist = torch.norm(dist, p=2, dim=0) # (N)\n return dist\n\n\n def copy_index(self, inputs, mask, src):\n '''\n out-of-place copy index.\n Input:\n - inputs:\ttorch.Tensor (H*W) / (H, W) / (H, W, k)\n - mask:\t\ttorch.Tensor (H*W)\n - src:\t\ttorch.Tensor (N) / (N, k)\n '''\n inputs_shape = inputs.shape\n if len(inputs_shape) <= 2:\n inputs, mask = inputs.reshape(-1), mask.reshape(-1)\n elif len(inputs_shape) == 3:\n inputs, mask = inputs.reshape(-1, inputs_shape[-1]), mask.reshape(-1)\n else:\n raise NotImplementedError\n index = torch.nonzero(mask).reshape(-1).long()\n outputs = inputs.index_copy(0, index, src)\n outputs = outputs.reshape(inputs_shape)\n return outputs\n\n def get_index_from_sdf_list(self, sdf_list, index_size, index_type='min', clamp_dist=0.1):\n '''\n get index with certain method.\n Input:\n - sdf_list:\t\ttype: torch.Tensor (self.march_step, N)\n Return:\n - sdf:\t\t\ttype: torch.Tensor (N, index_size)\n - index:\t\ttype: torch.Tensor (N, index_size). Note: the first dimension (index[0]) is always the min index.\n '''\n if index_type == 'min':\n sdf, index = torch.topk(-sdf_list.transpose(1,0), index_size, dim=1)\n sdf = -sdf\n elif index_type == 'min_abs':\n sdf_list_new = torch.abs(sdf_list)\n _, index = torch.topk(-sdf_list_new.transpose(1,0), index_size, dim=1)\n sdf = self.collect_data_from_index(sdf_list, index)\n elif index_type == 'max_neg':\n sdf_list_new = sdf_list.clone()\n sdf_list_pos = (sdf_list_new >= 0)\n sdf_list_new[sdf_list_pos] = sdf_list_new[sdf_list_pos].clone() * (-1) - 2\n sdf, index = torch.topk(sdf_list_new.transpose(1,0), index_size, dim=1) # (N, index_size)\n sdf_pos = (sdf <= -2)\n sdf[sdf_pos] = sdf[sdf_pos].clone() * (-1) - 2\n elif index_type == 'last_valid':\n march_step, N = sdf_list.shape[0], sdf_list.shape[1]\n valid = (torch.abs(sdf_list) < clamp_dist)\n idx_list = torch.arange(0, march_step)[:,None].repeat(1,N).to(sdf_list.device)\n idx_list = idx_list.float() * valid.float()\n _, index = torch.topk(idx_list.transpose(1,0), index_size, dim=1) # (N, index_size)\n sdf = self.collect_data_from_index(sdf_list, index)[0].transpose(1,0)\n elif index_type == 'last':\n march_step, N = sdf_list.shape[0], sdf_list.shape[1]\n sdf = sdf_list[-index_size:, :].transpose(1,0)\n index = torch.arange(march_step - index_size, march_step)[None,:].repeat(N, 1)\n index = index.to(sdf.device)\n else:\n raise NotImplementedError\n return sdf, index\n\n def collect_data_from_index(self, data, index):\n '''\n Input:\n - data:\t\ttype: torch.Tensor (self.march_step, N) / (self.march_step, N, k)\n - index:\ttype: torch.Tensor (N, index_size)\n Return:\n - data_sampled:\ttype: torch.Tensor (index_size, N) / (index_size, N, k)\n '''\n index_size = index.shape[1]\n count_index = torch.arange(index.shape[0]).repeat(index_size).to(index.device)\n point_index = index.transpose(1,0).reshape(-1) * data.shape[1] + count_index\n\n if len(data.shape) == 3:\n data_shape = data.shape\n data_sampled = data.reshape(-1, data_shape[-1])[point_index].reshape(index_size, -1, data_shape[-1]).clone() # (index_size, N, 3)\n elif len(data.shape) == 2:\n data_sampled = data.reshape(-1)[point_index].reshape(index_size, -1).clone() # (index_size, N)\n else:\n raise NotImplementedError\n return data_sampled\n\n def sample_points_uniform(self, points, cam_rays, num_samples=None):\n '''\n Input:\n points:\t\ttype: torch.Tensor (N, 3)\n cam_rays:\ttype: torch.Tensor (3, N)\n Return:\n points_sampled:\ttype: torch.Tensor (num_samples, N, 3)\n '''\n if num_samples == None:\n num_samples = self.buffer_size\n N = points.shape[0]\n points = points[None,:,:].repeat(num_samples, 1, 1) # (num_samples, N, 3)\n cam_rays = cam_rays.transpose(1, 0)[None,:,:].repeat(num_samples, 1, 1) # (num_samples, N, 3)\n delta_depth = torch.linspace(0, -self.max_sample_dist, num_samples).to(points.device) # (num_samples)\n delta_depth = delta_depth[:,None,None].repeat(1, N, 3) # (num_samples, N, 3)\n points_sampled = delta_depth * cam_rays + points # (num_smaples, N, 3)\n return points_sampled\n\n def get_min_sdf_sample(self, sdf_list, points_list, latent, index_type='min_abs', clamp_dist=0.1, profile=False, no_grad=False):\n profiler = Profiler(silent = not profile)\n _, index = self.get_index_from_sdf_list(sdf_list, 1, index_type=index_type)\n points = self.collect_data_from_index(points_list, index)[0] # (N, 3)\n min_sdf_sample = decode_sdf(self.decoder, latent, points, clamp_dist=None, no_grad=no_grad).squeeze(-1)\n profiler.report_process('[DEPTH] [SAMPLING] sample min sdf time\\t')\n if no_grad:\n min_sdf_sample = min_sdf_sample.detach()\n return min_sdf_sample\n\n def get_sample_on_marching_zdepth_along_ray(self, marching_zdepth_list, sdf_list, points_list, cam_rays, latent, index_type='min_abs', use_uniform_sample=False, clamp_dist=0.1, profile=False, no_grad=False):\n # initialization\n profiler = Profiler(silent = not profile)\n\n # collect points\n if use_uniform_sample:\n sdf_selected, index_selected = self.get_index_from_sdf_list(sdf_list, 1, index_type=index_type, clamp_dist=clamp_dist)\n points = self.collect_data_from_index(points_list, index_selected)[0] # (N, 3)\n points_sampled = self.sample_points_uniform(points, cam_rays)\n else:\n sdf_selected, index_selected = self.get_index_from_sdf_list(sdf_list, self.buffer_size, index_type=index_type, clamp_dist=clamp_dist)\n points_sampled = self.collect_data_from_index(points_list, index_selected)\n profiler.report_process('[DEPTH] [SAMPLING] collect points time\\t')\n\n # generate new marching zdepth\n marching_zdepth = self.collect_data_from_index(marching_zdepth_list, index_selected[:,[0]])[0] # (N)\n marching_zdepth = marching_zdepth + (1 - self.ray_marching_ratio) * torch.clamp(sdf_selected[0,:], -clamp_dist, clamp_dist) # (N)\n\n if no_grad:\n marching_zdepth_final = marching_zdepth\n else:\n marching_zdepth_new = marching_zdepth\n for i in range(self.buffer_size):\n sdf = decode_sdf(self.decoder, latent, points_sampled[i], clamp_dist=clamp_dist, no_grad=no_grad).squeeze(-1)\n marching_zdepth_new = marching_zdepth_new - sdf.detach() * self.ray_marching_ratio\n marching_zdepth_new = marching_zdepth_new + sdf * self.ray_marching_ratio\n profiler.report_process('[DEPTH] [SAMPLING] re-ray marching time')\n marching_zdepth_final = marching_zdepth_new\n return marching_zdepth_final\n\n\n def ray_marching_recursive(self, cam_pos, cam_rays, init_zdepth, valid_mask, latent, march_step=None, stop_threshold=None, clamp_dist=0.1, no_grad=False, use_first_query_check=True):\n print(f'[In ray_marching_recursive]')\n print(f'| | cam_rays = {cam_rays}')\n if stop_threshold is None:\n stop_threshold = self.threshold\n\n print(f'[In ray_marching_recursive] valid_mask.shape = {valid_mask.shape}')\n\n valid_cam_rays = cam_rays[:, valid_mask]\n cam_pos = cam_pos[:, valid_mask]\n \n init_zdepth = init_zdepth[valid_mask]\n \n print(f'[In ray_marching_recursive] init_zdepth.shape = {init_zdepth.shape}')\n print(f'[In ray_marching_recursive] init_zdepth = {init_zdepth}')\n \n if march_step is None:\n march_step = self.march_step\n\n \n #self.get_maxbound_zdepth(cam_pos, valid_cam_rays)\n _, _, _, maxbound_zdepth = self.get_grid_and_rays()\n print(f'[In ray_marching_recursive] maxbound_zdepth.shape = {maxbound_zdepth.shape}')\n\n marching_zdepth_list, sdf_list, points_list = [], [], []\n marching_zdepth = torch.zeros_like(init_zdepth)\n\n valid_mask_max_marching_zdepth = (marching_zdepth + init_zdepth < maxbound_zdepth)\n unfinished_mask = valid_mask_max_marching_zdepth # (N)\n print(f'[In ray_marching_recursive] marching_zdepth = {marching_zdepth}')\n print(f'[In ray_marching_recursive] init_zdepth = {init_zdepth}')\n print(f'[In ray_marching_recursive] maxbound_zdepth = {maxbound_zdepth}')\n print(f'[In ray_marching_recursive] unfinished_mask.shape = {unfinished_mask.shape}')\n print(f'[In ray_marching_recursive] unfinished_mask nonzero terms = {(unfinished_mask).sum()}')\n for i in range(march_step):\n # get unfinished\n cam_rays_now = valid_cam_rays[:, unfinished_mask] # (3, K)\n cam_pos_now = cam_pos[:, unfinished_mask]\n\n init_zdepth_now = init_zdepth[unfinished_mask] # (K)\n print(f'[In ray_marching_recursive] init_zdepth_now.shape = {init_zdepth_now.shape}')\n marching_zdepth_now = marching_zdepth[unfinished_mask] # (K)\n\n # get corresponding sdf value\n points_now = self.generate_point_samples(cam_pos_now, cam_rays_now, init_zdepth_now + marching_zdepth_now) # (3, K)\n if no_grad:\n points_now = points_now.detach()\n sdf_now = decode_sdf(self.decoder, latent, points_now.transpose(1,0), clamp_dist=None, no_grad=no_grad).squeeze(-1) # (K)\n points = torch.zeros_like(marching_zdepth)[:,None].repeat(1,3)\n points[unfinished_mask,:] = points_now.transpose(1,0)\n if no_grad:\n points = points.detach()\n points_list.append(points[None,:])\n\n # clamp sdf from below if the flag is invalid, which means that it has not meet any sdf < 0\n sdf = torch.zeros_like(marching_zdepth)\n sdf[unfinished_mask] = sdf_now.detach()\n sdf_marching = torch.clamp(sdf, -clamp_dist, clamp_dist)\n\n # aggressive ray marching\n marching_zdepth = marching_zdepth + sdf_marching * self.ray_marching_ratio\n marching_zdepth_list.append(marching_zdepth[None,:])\n\n # update sdf list\n sdf[~unfinished_mask] = 1.0\n sdf_list.append(sdf[None,:])\n\n # update unfinised mask\n valid_mask_max_marching_zdepth = (marching_zdepth + init_zdepth < maxbound_zdepth)\n unstop_mask = torch.abs(sdf) >= stop_threshold\n unfinished_mask = unfinished_mask & valid_mask_max_marching_zdepth & unstop_mask\n if torch.nonzero(unfinished_mask).shape[0] == 0:\n while(len(marching_zdepth_list) < self.buffer_size):\n marching_zdepth_list.append(marching_zdepth[None,:])\n sdf_list.append(sdf[None,:])\n points_list.append(points[None,:])\n break\n # concat ray marching info\n marching_zdepth_list = torch.cat(marching_zdepth_list, 0) # (self.march_step, N)\n sdf_list = torch.cat(sdf_list, 0)\n points_list = torch.cat(points_list, 0)\n\n # get valid mask\n valid_mask_max_marching_zdepth = (marching_zdepth_list[-1] + init_zdepth < maxbound_zdepth)\n min_sdf, _ = torch.abs(sdf_list).min(0)\n valid_mask_ray_marching = (min_sdf <= self.threshold)\n\n # get corner case: the first query is lower than threshold.\n valid_mask_render = valid_mask_max_marching_zdepth & valid_mask_ray_marching # (N)\n if use_first_query_check:\n valid_mask_first_query = sdf_list[0] > self.threshold\n valid_mask_render = valid_mask_render & valid_mask_first_query\n return sdf_list, marching_zdepth_list, points_list, valid_mask_render\n\n\n def ray_marching(self, cam_pos, init_zdepth, valid_mask, latent, march_step=None, clamp_dist=0.1, no_grad=False, ray_marching_type='recursive', split_type='raydepth'):\n '''\n ray marching function\n Input:\n - init_zdepth\t\t\ttype: torch.Tensor (H*W)\n - valid_mask\t\t\ttype: torch.Tensor (H*W) with N valid entries\n - split_type ['depth', 'raydepth'], which is the spliting strategy for pyramid recursive marching\n Return:\n - sdf_list\t\t\ttype: torch.Tensor (march_step, N)\n - marching_zdepth_list\t\ttype: torch.Tensor (march_step, N)\n - points_list\t\t\ttype: torch.Tensor (march_step, N, 3)\n - valid_mask_render\t\ttype: torch.Tensor (N)\n '''\n if not (split_type in ['depth', 'raydepth']):\n raise NotImplementedError\n elif ray_marching_type == 'recursive':\n _, cam_rays, _, _ = self.get_grid_and_rays()\n return self.ray_marching_recursive(cam_pos, cam_rays, init_zdepth, valid_mask, latent, march_step=None, clamp_dist=clamp_dist, no_grad=no_grad)\n else:\n raise ValueError('Error! Invalid type of ray marching: {}.'.format(ray_marching_type))\n\n def render_depth(self, latent, clamp_dist=0.1, sample_index_type='min_abs', profile=False, no_grad=False, no_grad_depth=False, no_grad_mask=False, no_grad_camera=False, ray_marching_type='recursive'):\n if no_grad:\n no_grad_depth, no_grad_mask, no_grad_camera = True, True, True\n \n # Getting camera pos and rays\n cam_pos, cam_rays, init_zdepth, _ = self.get_grid_and_rays()\n \n\n dist = self.get_distance_from_origin(cam_pos, cam_rays)\n print(f'| cam_pos = {cam_pos.shape}, {cam_pos}')\n print(f'| cam_rays = {cam_rays.shape}, ray viewing direction. For our orthogonal case, we only need a single direction!')\n dbgtmpvar_camraylen = (cam_rays**2).sum(0)\n print(f'| cam_rays lengths: min = {dbgtmpvar_camraylen.min()}, max = {dbgtmpvar_camraylen.max()}, so these are unit vectors.')\n print(f'| dist = {dist.shape}')\n\n\n profiler = Profiler(silent = not profile)\n # initialization on the unit sphere\n h, w = self.img_hw\n print(f'Getting initial zdepth and valid mask')\n \n valid_mask = torch.ones_like(init_zdepth, device=self.device).bool()\n #init_zdepth, valid_mask = self.get_intersections_with_unit_spheres(cam_pos, cam_rays)\n print(f'[In render_depth] init_zdepth = {init_zdepth.shape}')\n print(f'| valid_mask = {valid_mask.shape}')\n profiler.report_process('[DEPTH] initialization time')\n\n # ray marching\n print(f'Marching rays. Clearly the most important marching step happens here.')\n sdf_list, marching_zdepth_list, points_list, valid_mask_render = self.ray_marching(cam_pos, init_zdepth, valid_mask, latent, clamp_dist=clamp_dist, no_grad=no_grad_camera, ray_marching_type=ray_marching_type)\n print(f'| sdf_list = {sdf_list.shape}, the sdfs at all 50 marching steps')\n print(f'| marching_zdepth_list = {marching_zdepth_list.shape}, the depth at all 50 marching steps')\n print(f'| points_list = {points_list.shape}, the points at all 50 marching steps')\n print(f'| valid_mask_render = {valid_mask_render.shape}, only a single image')\n profiler.report_process('[DEPTH] ray marching time')\n\n # get differnetiable samples\n min_sdf_sample = self.get_min_sdf_sample(sdf_list, points_list, latent, index_type='min_abs', clamp_dist=clamp_dist, profile=profile, no_grad=no_grad_mask)\n marching_zdepth = self.get_sample_on_marching_zdepth_along_ray(marching_zdepth_list, sdf_list, points_list, cam_rays[:, valid_mask], latent, use_uniform_sample=False, index_type=sample_index_type, clamp_dist=clamp_dist, profile=profile, no_grad=no_grad_depth)\n profiler.report_process('[DEPTH] re-sampling time')\n\n # generate output\n min_sdf_sample_new = torch.zeros_like(valid_mask).float() # (H, W)\n min_sdf_sample_new.requires_grad = True\n min_sdf_sample_new = self.copy_index(min_sdf_sample_new, valid_mask, min_sdf_sample)\n min_sdf_sample_new = self.copy_index(min_sdf_sample_new, ~valid_mask, dist[~valid_mask] + self.threshold - self.radius) # help handle camera gradient\n\n ## get zdepth\n Zdepth = torch.ones_like(self.imgmap_init) * 1e11 # (H, W)\n Zdepth.requires_grad = True\n src_zdepth = init_zdepth[valid_mask] + marching_zdepth # (N)\n Zdepth = self.copy_index(Zdepth, valid_mask, src_zdepth)\n Zdepth = Zdepth.reshape(-1) # (H*W)\n\n ## update valid_mask\n valid_mask = valid_mask.clone()\n valid_mask[valid_mask] = valid_mask_render\n profiler.report_process('[DEPTH] finalize time\\t')\n if no_grad_depth:\n Zdepth = Zdepth.detach()\n return Zdepth, valid_mask, min_sdf_sample_new # (H*W), (H*W), (H*W)\n\n def render_normal(self, latent, Zdepth, valid_mask, clamp_dist=0.1, MAX_POINTS=100000, no_grad=False, normalize=True):\n \n cam_pos, cam_rays, init_zdepth, _ = self.get_grid_and_rays()\n\n ### Getting normals\n h, w = self.img_hw\n Znormal = torch.zeros_like(self.imgmap_init)[None,:,:].repeat(3, 1, 1) # (3, H, W)\n Znormal.requires_grad = True\n\n # initialization\n valid_cam_pos = cam_pos[:, valid_mask]\n valid_cam_rays = cam_rays[:, valid_mask]\n valid_zdepth = Zdepth[valid_mask]\n if valid_zdepth.shape[0] == 0:\n return Znormal.reshape(3, -1) # (3, H*W)\n\n # compute normal\n points = self.generate_point_samples(valid_cam_pos, valid_cam_rays, valid_zdepth, has_zdepth_grad=False)\n gradient = decode_sdf_gradient(self.decoder, latent, points.transpose(1,0), clamp_dist=clamp_dist, no_grad=no_grad, MAX_POINTS=MAX_POINTS) # (N, 3)\n gradient = gradient.transpose(1,0) # (3, N)\n if normalize:\n valid_normal = self.normalize_vectors(gradient) # (3, N)\n else:\n valid_normal = gradient\n \n # generate output\n Znormal = self.copy_index(Znormal.permute(1,2,0), valid_mask, valid_normal.transpose(1,0)) # (H, W, 3)\n Znormal = Znormal.reshape(-1, 3).transpose(1,0)\n\n if no_grad:\n Znormal = Znormal.detach()\n return Znormal # (3, H*W)\n\n \nif __name__ == '__main__':\n pass\n\n" ]
[ [ "torch.abs", "torch.linspace", "torch.norm", "torch.ones", "torch.zeros", "torch.cat", "torch.cuda.device_count", "torch.zeros_like", "torch.nonzero", "torch.arange", "torch.stack", "torch.clamp", "torch.meshgrid", "torch.ones_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Garimagupta85/Accident-Detection
[ "bfb6dd4ef102b4de92adf4f4c78b77ed9a25b127" ]
[ "Code/model.py" ]
[ "import glob\nimport numpy as np\nimport random\nfrom sklearn.model_selection import train_test_split \nimport os\nimport numpy\nimport glob\nimport cv2\nimport random\nfrom skimage import transform\nimport skimage\nimport sklearn\nfrom sklearn.model_selection import train_test_split \n\nimport os\nimport numpy as np\n\nfrom tensorflow.python import keras \nfrom tensorflow.python.keras.preprocessing.image import ImageDataGenerator,array_to_img,img_to_array,load_img\nbatch_size = 15\nnum_classes = 2\nepochs = 30\n\nrow_hidden = 128\ncol_hidden = 128\n\n\nframe , row, col =(99,144,256)\n\n'''\n\tLoading all the Positive and negative according to the desired \n\tfile path and the load_set preprocess the data in which each frame\n\tis extracted to a paricular size of (144,256)\n\n'''\n\ndef load_set(img_path):\n\timg = load_img(img_path)\n\ttmp = skimage.color.rgb2gray(np.array(img))\n\ttmp = transform.resize(tmp, (144, 256))\n\treturn tmp\n\n'''\n\tLoading all the Positive and negative according to the desired \n\tfile path and the load_set preprocess the data in which each frame\n\tis extracted to a paricular size of (144,256) and is horizontally filpped\n\n'''\n\ndef horizontal_flip(img_path):\n\timg = load_img(img_path)\n\ttmp = skimage.color.rgb2gray(np.array(img))\n\ttmp = skimage.transform.resize(tmp, (144, 256))\n\ttmp = np.array(tmp)\n\ttmp = np.flip(tmp, axis = 1)\n\treturn tmp\n\n\n'''\n\tLoading all the Positive and negative files assigned to varaiable\n\tneg and pos respectively\n\tAll files contains both the files paths\n\n'''\npos = glob.glob( '99frames/*.mp4')\nneg = glob.glob( 'negative/*.mp4')\nall_files = np.concatenate((pos, neg[0:len(pos)]))\n\n#print(len(neg),len(pos))\n#print(all_files) \n\n\n'''\n\tlabel matrix is used to make one hot encoding ie [0 1] for\n\tpositve data and [1 0] for negative data\n\n'''\n\n\ndef label_matrix(values):\n \n n_values = np.max(values) + 1 \n return np.eye(n_values)[values] \n\nlabels = np.concatenate(([1]*len(pos), [0]*len(neg[0:len(pos)]))) \nlabels = label_matrix(labels) \n#print(len(labels)) \n\n\n\n\n\ndef load_data1(path):\n\t\n\tx = []\n\tfor files in os.listdir(path):\n\n\t\tframes = []\n\t\timg_path = path+\"/\"+files\n\t\tif files !=(\"frame99.jpg\"):\n\t\t\timg = load_set(img_path)\n\t\t\tx.append(img)\n\treturn x\n\ndef load_data3(path):\n\tcount = 0\n\tx = []\n\tfor files in os.listdir(path):\n\n\t\tframes = []\n\t\timg_path = path+\"/\"+files\n\t\tif count < 99:\n\t\t\tcount = count + 1\n\t\t\timg = load_set(img_path)\n\t\t\tx.append(img)\n\treturn x\n\n\ndef load_data2(path):\t\n\tx = []\n\t\n\tfor files in os.listdir(path):\n\t\t\n\t\tframes = []\n\t\timg_path = path+\"/\"+files\n\t\tif files !=(\"frame99.jpg\") :\n\t\t\t\n\t\t\timg = horizontal_flip(img_path)\n\t\t\tx.append(img)\n\treturn x\n\n\ndef load_data4(path):\t\n\tx = []\n\tcount =0\n\tfor files in os.listdir(path):\n\t\t\n\t\tframes = []\n\t\timg_path = path+\"/\"+files\n\t\tif count < 99 :\n\t\t\tcount = count +1\n\t\t\timg = horizontal_flip(img_path)\n\t\t\tx.append(img)\n\treturn x\t\n\n'''\n\n'''\ndef make_dataset(rand):\n seq1 = np.zeros((len(rand), 99, 144, 256)) \n for i,fi in enumerate(rand): \n print (i, fi)\n \n if fi[9:11] == '00' :\n t = load_data1(fi)\n elif fi[9:13] == 'MVIH':\n \tt = load_data3(fi)\n elif fi[9:13] == 'MVI_':\t\n t = load_data4(fi) \n elif fi[9:11]=='11' :\n t = load_data2(fi) \n \n seq1[i] = t \n\n return seq1\n\n\n\nx_train, x_t1, y_train, y_t1 = train_test_split(all_files, labels, test_size=0.40, random_state=0) \nx_train = np.array(x_train); y_train = np.array(y_train)\n ### need to be np.arrays\nfor i in range(0,len(x_train)):\n\tprint(x_train[i],y_train[i])\n\nx_testA = np.array(x_t1[:int(len(x_t1)/3)]); y_testA = np.array(y_t1[:int(len(x_t1)/3)]) #### test set\nx_testA = make_dataset(x_testA)\n\n\n### valid set for model\nx_testB = np.array(x_t1[int(2*len(x_t1)/3):]); y_testB = np.array(y_t1[int(2*len(x_t1)/3):]) ### need to be np.arrays\nx_testB = make_dataset(x_testB)\n\n\t\n\n\nimport keras\nfrom keras.models import Model \nfrom keras.layers import Input,Dense,TimeDistributed\nfrom keras.layers import LSTM\n\nframe, row, col = (99, 144, 256)\nx =Input(shape=(frame, row, col))\nencoded_rows = TimeDistributed(LSTM(row_hidden))(x) \nencoded_columns =LSTM(col_hidden)(encoded_rows)\n\nprediction = Dense(num_classes, activation='softmax')(encoded_columns)\n\nmodel = Model(x, prediction)\n\nmodel.compile(loss='categorical_crossentropy', \n\t\t\t\toptimizer='NAdam', \n\t\t\t\tmetrics=['accuracy']) \n\nnp.random.seed(18247)\n\nimport matplotlib.pyplot as plt\nimport numpy\n\nfor i in range(0, 30): \n c = list(zip(x_train, y_train)) \n random.shuffle(c) \n x_shuff, y_shuff = zip(*c) \n x_shuff = np.array(x_shuff); y_shuff=np.array(y_shuff) \n \n x_batch = [x_shuff[i:i + batch_size] for i in range(0, len(x_shuff), batch_size)] \n y_batch = [y_shuff[i:i + batch_size] for i in range(0, len(x_shuff), batch_size)] \n\n for j,xb in enumerate(x_batch): \n xx = make_dataset(xb) \n yy = y_batch[j] \n \n history = model.fit(xx, yy, \n batch_size=len(xx), \n epochs=15, \n validation_data=(x_testB, y_testB), \n ) \n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n # summarize history for loss\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show() \n\n\nscores = model.evaluate(x_testA, y_testA, verbose=0) \nprint('Test loss:', scores[0]) \nprint('Test accuracy:', scores[1]) \t\t\t\n\nfrom keras.models import model_from_json\nfrom keras.models import load_model\n\n# serialize model to JSON\n# the keras model which is trained is defined as 'model' in this example\nmodel_json = model.to_json()\n\n\nwith open(\"model_num.json\", \"w\") as json_file:\n json_file.write(model_json)\n\n# serialize weights to HDF5\nmodel.save_weights(\"model_num.h5\")" ]
[ [ "matplotlib.pyplot.legend", "numpy.random.seed", "matplotlib.pyplot.title", "numpy.eye", "sklearn.model_selection.train_test_split", "matplotlib.pyplot.plot", "numpy.max", "tensorflow.python.keras.preprocessing.image.load_img", "matplotlib.pyplot.xlabel", "numpy.array", "numpy.flip", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.4", "2.3", "2.4", "1.5", "1.7", "2.5", "2.6" ] } ]
TianhongDai/div-hindsight
[ "68927ec45087ee0d57a123ddad16703a7af050a3", "68927ec45087ee0d57a123ddad16703a7af050a3" ]
[ "baselines/her/rollout.py", "baselines/her/experiment/config.py" ]
[ "from collections import deque\nimport numpy as np\nimport pickle\nfrom mujoco_py import MujocoException\nfrom baselines.her.util import convert_episode_to_batch_major, store_args\n\nclass RolloutWorker:\n\n @store_args\n def __init__(self, make_env, policy, dims, logger, T, rollout_batch_size=1,\n exploit=False, use_target_net=False, compute_Q=False, noise_eps=0,\n random_eps=0, history_len=100, render=False, **kwargs):\n \"\"\"Rollout worker generates experience by interacting with one or many environments.\n\n Args:\n make_env (function): a factory function that creates a new instance of the environment\n when called\n policy (object): the policy that is used to act\n dims (dict of ints): the dimensions for observations (o), goals (g), and actions (u)\n logger (object): the logger that is used by the rollout worker\n rollout_batch_size (int): the number of parallel rollouts that should be used\n exploit (boolean): whether or not to exploit, i.e. to act optimally according to the\n current policy without any exploration\n use_target_net (boolean): whether or not to use the target net for rollouts\n compute_Q (boolean): whether or not to compute the Q values alongside the actions\n noise_eps (float): scale of the additive Gaussian noise\n random_eps (float): probability of selecting a completely random action\n history_len (int): length of history for statistics smoothing\n render (boolean): whether or not to render the rollouts\n \"\"\"\n self.envs = [make_env() for _ in range(rollout_batch_size)]\n assert self.T > 0\n\n self.info_keys = [key.replace('info_', '') for key in dims.keys() if key.startswith('info_')]\n\n self.success_history = deque(maxlen=history_len)\n self.Q_history = deque(maxlen=history_len)\n\n self.n_episodes = 0\n self.g = np.empty((self.rollout_batch_size, self.dims['g']), np.float32) # goals\n self.initial_o = np.empty((self.rollout_batch_size, self.dims['o']), np.float32) # observations\n self.initial_ag = np.empty((self.rollout_batch_size, self.dims['g']), np.float32) # achieved goals\n self.reset_all_rollouts()\n self.clear_history()\n\n def reset_rollout(self, i):\n \"\"\"Resets the `i`-th rollout environment, re-samples a new goal, and updates the `initial_o`\n and `g` arrays accordingly.\n \"\"\"\n obs = self.envs[i].reset()\n self.initial_o[i] = obs['observation']\n self.initial_ag[i] = obs['achieved_goal']\n self.g[i] = obs['desired_goal']\n\n def reset_all_rollouts(self):\n \"\"\"Resets all `rollout_batch_size` rollout workers.\n \"\"\"\n for i in range(self.rollout_batch_size):\n self.reset_rollout(i)\n\n def generate_rollouts(self):\n \"\"\"Performs `rollout_batch_size` rollouts in parallel for time horizon `T` with the current\n policy acting on it accordingly.\n \"\"\"\n self.reset_all_rollouts()\n\n # compute observations\n o = np.empty((self.rollout_batch_size, self.dims['o']), np.float32) # observations\n ag = np.empty((self.rollout_batch_size, self.dims['g']), np.float32) # achieved goals\n o[:] = self.initial_o\n ag[:] = self.initial_ag\n\n # generate episodes\n obs, achieved_goals, acts, goals, successes = [], [], [], [], []\n info_values = [np.empty((self.T, self.rollout_batch_size, self.dims['info_' + key]), np.float32) for key in self.info_keys]\n Qs = []\n for t in range(self.T):\n policy_output = self.policy.get_actions(\n o, ag, self.g,\n compute_Q=self.compute_Q,\n noise_eps=self.noise_eps if not self.exploit else 0.,\n random_eps=self.random_eps if not self.exploit else 0.,\n use_target_net=self.use_target_net)\n\n if self.compute_Q:\n u, Q = policy_output\n Qs.append(Q)\n else:\n u = policy_output\n\n if u.ndim == 1:\n # The non-batched case should still have a reasonable shape.\n u = u.reshape(1, -1)\n\n o_new = np.empty((self.rollout_batch_size, self.dims['o']))\n ag_new = np.empty((self.rollout_batch_size, self.dims['g']))\n success = np.zeros(self.rollout_batch_size)\n # compute new states and observations\n for i in range(self.rollout_batch_size):\n try:\n # We fully ignore the reward here because it will have to be re-computed\n # for HER.\n curr_o_new, _, _, info = self.envs[i].step(u[i])\n if 'is_success' in info:\n success[i] = info['is_success']\n o_new[i] = curr_o_new['observation']\n ag_new[i] = curr_o_new['achieved_goal']\n for idx, key in enumerate(self.info_keys):\n info_values[idx][t, i] = info[key]\n if self.render:\n self.envs[i].render()\n except MujocoException as e:\n return self.generate_rollouts()\n\n if np.isnan(o_new).any():\n self.logger.warning('NaN caught during rollout generation. Trying again...')\n self.reset_all_rollouts()\n return self.generate_rollouts()\n\n obs.append(o.copy())\n achieved_goals.append(ag.copy())\n successes.append(success.copy())\n acts.append(u.copy())\n goals.append(self.g.copy())\n o[...] = o_new\n ag[...] = ag_new\n obs.append(o.copy())\n achieved_goals.append(ag.copy())\n self.initial_o[:] = o\n\n successful = np.array(successes)[-1, :].copy()\n\n episode = dict(o=obs,\n u=acts,\n g=goals,\n ag=achieved_goals,)\n for key, value in zip(self.info_keys, info_values):\n episode['info_{}'.format(key)] = value\n\n # stats\n assert successful.shape == (self.rollout_batch_size,)\n success_rate = np.mean(successful)\n self.success_history.append(success_rate)\n if self.compute_Q:\n self.Q_history.append(np.mean(Qs))\n self.n_episodes += self.rollout_batch_size\n\n return convert_episode_to_batch_major(episode)\n\n def clear_history(self):\n \"\"\"Clears all histories that are used for statistics\n \"\"\"\n self.success_history.clear()\n self.Q_history.clear()\n\n def current_success_rate(self):\n return np.mean(self.success_history)\n\n def current_mean_Q(self):\n return np.mean(self.Q_history)\n\n def save_policy(self, path):\n \"\"\"Pickles the current policy for later inspection.\n \"\"\"\n with open(path, 'wb') as f:\n pickle.dump(self.policy, f)\n\n def logs(self, prefix='worker'):\n \"\"\"Generates a dictionary that contains all collected statistics.\n \"\"\"\n logs = []\n logs += [('success_rate', np.mean(self.success_history))]\n if self.compute_Q:\n logs += [('mean_Q', np.mean(self.Q_history))]\n logs += [('episode', self.n_episodes)]\n\n if prefix is not '' and not prefix.endswith('/'):\n return [(prefix + '/' + key, val) for key, val in logs]\n else:\n return logs\n\n def seed(self, seed):\n \"\"\"Seeds each environment with a distinct seed derived from the passed in global seed.\n \"\"\"\n for idx, env in enumerate(self.envs):\n env.seed(seed + 1000 * idx)\n", "from copy import deepcopy\nimport numpy as np\nimport json\nimport os\nimport gym\nfrom baselines import logger\nfrom baselines.her.ddpg import DDPG\nfrom baselines.her.her import make_sample_her_transitions, \\\n make_sample_her_transitions_diversity, \\\n make_sample_her_transitions_diversity_with_kdpp\n# some params\nDEFAULT_ENV_PARAMS = {\n 'FetchReach-v0': {\n 'n_cycles': 10,\n },\n}\n\nDEFAULT_PARAMS = {\n # env\n 'max_u': 1., # max absolute value of actions on different coordinates\n # ddpg\n 'layers': 3, # number of layers in the critic/actor networks\n 'hidden': 256, # number of neurons in each hidden layers\n 'network_class': 'baselines.her.actor_critic:ActorCritic',\n 'Q_lr': 0.001, # critic learning rate\n 'pi_lr': 0.001, # actor learning rate\n 'buffer_size': int(1E6), # int(1E6) int(1E6) bug for experience replay \n 'polyak': 0.95, # polyak averaging coefficient\n 'action_l2': 1.0, # quadratic penalty on actions (before rescaling by max_u)\n 'clip_obs': 200.,\n 'scope': 'ddpg', # can be tweaked for testing\n 'relative_goals': False,\n # training\n 'n_cycles': 50, # per epoch\n 'rollout_batch_size': 2, # per mpi thread\n 'n_batches': 40, # training batches per cycle\n 'batch_size': 64, # per mpi thread, measured in transitions and reduced to even multiple of chunk_length.\n 'n_test_rollouts': 10, # number of test rollouts per epoch, each consists of rollout_batch_size rollouts\n 'test_with_polyak': False, # run test episodes with the target network\n # exploration\n 'random_eps': 0.3, # percentage of time a random action is taken\n 'noise_eps': 0.2, # std of gaussian noise added to not-completely-random actions as a percentage of max_u\n # HER\n 'replay_strategy': 'future', # supported modes: future, none\n 'replay_k': 4, # number of additional goals used for replay, only used if off_policy_data=future\n # normalization\n 'norm_eps': 0.01, # epsilon used for observation normalization\n 'norm_clip': 5, # normalized observations are cropped to this values\n\n # prioritized_replay (tderror) has been removed\n 'alpha': 0.6, # 0.6\n 'beta0': 0.4, # 0.4\n 'beta_iters': None, # None\n 'eps': 1e-6,\n}\n\nCACHED_ENVS = {}\ndef cached_make_env(make_env):\n \"\"\"\n Only creates a new environment from the provided function if one has not yet already been\n created. This is useful here because we need to infer certain properties of the env, e.g.\n its observation and action spaces, without any intend of actually using it.\n \"\"\"\n if make_env not in CACHED_ENVS:\n env = make_env()\n CACHED_ENVS[make_env] = env\n return CACHED_ENVS[make_env]\n\ndef prepare_params(kwargs):\n # DDPG params\n ddpg_params = dict()\n\n env_name = kwargs['env_name']\n def make_env():\n return gym.make(env_name)\n kwargs['make_env'] = make_env\n tmp_env = cached_make_env(kwargs['make_env'])\n assert hasattr(tmp_env, '_max_episode_steps')\n kwargs['T'] = tmp_env._max_episode_steps\n tmp_env.reset()\n kwargs['max_u'] = np.array(kwargs['max_u']) if type(kwargs['max_u']) == list else kwargs['max_u']\n kwargs['gamma'] = 1. - 1. / kwargs['T']\n if 'lr' in kwargs:\n kwargs['pi_lr'] = kwargs['lr']\n kwargs['Q_lr'] = kwargs['lr']\n del kwargs['lr']\n for name in ['buffer_size', 'hidden', 'layers',\n 'network_class',\n 'polyak', \n 'batch_size', 'Q_lr', 'pi_lr',\n 'norm_eps', 'norm_clip', 'max_u',\n 'action_l2', 'clip_obs', 'scope', 'relative_goals',\n 'alpha', 'beta0', 'beta_iters', 'eps']:\n ddpg_params[name] = kwargs[name]\n kwargs['_' + name] = kwargs[name]\n del kwargs[name]\n kwargs['ddpg_params'] = ddpg_params\n\n return kwargs\n\n\ndef log_params(params, logger=logger):\n for key in sorted(params.keys()):\n logger.info('{}: {}'.format(key, params[key]))\n\n\ndef configure_her(params):\n env = cached_make_env(params['make_env'])\n env.reset()\n def reward_fun(ag_2, g, info): # vectorized\n return env.compute_reward(achieved_goal=ag_2, desired_goal=g, info=info)\n\n # Prepare configuration for HER.\n her_params = {\n 'reward_fun': reward_fun,\n }\n for name in ['replay_strategy', 'replay_k']:\n her_params[name] = params[name]\n params['_' + name] = her_params[name]\n del params[name]\n if params['prioritization'] == 'diversity':\n \"\"\"\n decide if use the kdpp to sample\n \"\"\"\n if params['use_kdpp']:\n # use subset size\n her_params['subset_size'] = params['subset_size']\n params['_' + 'subset_size'] = her_params['subset_size']\n del params['subset_size']\n her_params['goal_type'] = params['goal_type']\n her_params['sigma'] = params['sigma']\n sample_her_transitions = make_sample_her_transitions_diversity_with_kdpp(**her_params)\n else:\n sample_her_transitions = make_sample_her_transitions_diversity(**her_params)\n else:\n sample_her_transitions = make_sample_her_transitions(**her_params)\n return sample_her_transitions\n\ndef simple_goal_subtract(a, b):\n assert a.shape == b.shape\n return a - b\n\ndef configure_ddpg(dims, params, reuse=False, use_mpi=True, clip_return=True):\n sample_her_transitions = configure_her(params)\n # Extract relevant parameters.\n gamma = params['gamma']\n rollout_batch_size = params['rollout_batch_size']\n ddpg_params = params['ddpg_params']\n prioritization = params['prioritization']\n env_name = params['env_name']\n max_timesteps = params['max_timesteps']\n input_dims = dims.copy()\n # DDPG agent\n env = cached_make_env(params['make_env'])\n env.reset()\n ddpg_params.update({'input_dims': input_dims, # agent takes an input observations\n 'T': params['T'],\n 'clip_pos_returns': True, # clip positive returns\n 'clip_return': (1. / (1. - gamma)) if clip_return else np.inf, # max abs of return\n 'rollout_batch_size': rollout_batch_size,\n 'subtract_goals': simple_goal_subtract,\n 'sample_transitions': sample_her_transitions,\n 'gamma': gamma,\n 'prioritization': prioritization,\n 'env_name': env_name,\n 'max_timesteps': max_timesteps,\n })\n ddpg_params['info'] = {\n 'env_name': params['env_name'],\n }\n # if use diversity\n if params['prioritization'] == 'diversity':\n ddpg_params['goal_type'] = params['goal_type']\n policy = DDPG(reuse=reuse, **ddpg_params, use_mpi=use_mpi)\n return policy\n\ndef configure_dims(params):\n env = cached_make_env(params['make_env'])\n env.reset()\n obs, _, _, info = env.step(env.action_space.sample())\n dims = {\n 'o': obs['observation'].shape[0],\n 'u': env.action_space.shape[0],\n 'g': obs['desired_goal'].shape[0],\n }\n for key, value in info.items():\n value = np.array(value)\n if value.ndim == 0:\n value = value.reshape(1)\n dims['info_{}'.format(key)] = value.shape[0]\n return dims" ]
[ [ "numpy.isnan", "numpy.mean", "numpy.array", "numpy.zeros", "numpy.empty" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
feidaoGavin/matplotlib
[ "84abb5ca1f561921e437f13491be2bfcec0b0847" ]
[ "mtaplotlib.py" ]
[ "import matplotlib.pyplot as plt\nfrom pylab import *\n\n\nx = linspace(0, 5, 10)\ny = x ** 2\n\nfig = plt.figure()\n\naxes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)\n\naxes.plot(x, y, 'r')\n\naxes.set_xlabel('x')\naxes.set_ylabel('y')\naxes.set_title('title')\n\nplt.savefig('fig.png',bbox_inches='tight')\n\nplt.show()\n\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.savefig", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
luozhouyang/smile_datasets
[ "c614314b2e2d83896b252670c6e3d8bd158f055b" ]
[ "rapidnlp_datasets/tf/token_classification_dataset.py" ]
[ "import logging\n\nimport tensorflow as tf\n\nfrom . import utils\nfrom .dataset import TFDataset\n\n\nclass TFDatasetForTokenClassification(TFDataset):\n \"\"\"Dataset for token classification in TensorFlow\"\"\"\n\n def __init__(self, examples=None, **kwargs) -> None:\n super().__init__(examples, **kwargs)\n self.input_ids = kwargs.pop(\"input_ids\", \"input_ids\")\n self.token_type_ids = kwargs.pop(\"token_type_ids\", \"token_type_ids\")\n self.attention_mask = kwargs.pop(\"attention_mask\", \"attention_mask\")\n self.labels = kwargs.pop(\"labels\", \"labels\")\n\n @classmethod\n def from_tfrecord_files(cls, input_files, **kwargs) -> tf.data.Dataset:\n dataset = utils.read_tfrecord_files(input_files, **kwargs)\n d = cls(examples=None, **kwargs)\n # parse example\n features = {\n d.input_ids: tf.io.VarLenFeature(tf.int64),\n d.token_type_ids: tf.io.VarLenFeature(tf.int64),\n d.attention_mask: tf.io.VarLenFeature(tf.int64),\n d.labels: tf.io.VarLenFeature(tf.int64),\n }\n dataset = dataset.map(\n lambda x: tf.io.parse_example(x, features),\n num_parallel_calls=utils.AUTOTUNE,\n ).prefetch(utils.AUTOTUNE)\n dataset = dataset.map(\n lambda x: (\n tf.cast(tf.sparse.to_dense(x[d.input_ids]), tf.int32),\n tf.cast(tf.sparse.to_dense(x[d.token_type_ids]), tf.int32),\n tf.cast(tf.sparse.to_dense(x[d.attention_mask]), tf.int32),\n tf.cast(tf.sparse.to_dense(x[d.labels]), tf.int32),\n ),\n num_parallel_calls=utils.AUTOTUNE,\n ).prefetch(utils.AUTOTUNE)\n # do transformation\n return d(dataset, **kwargs)\n\n def parse_examples_to_dataset(self):\n if not self.examples:\n logging.info(\"self.examples is empty or None, skipped.\")\n return None\n input_ids, token_type_ids, attention_mask, labels = [], [], [], []\n for e in self.examples:\n input_ids.append(e.input_ids)\n token_type_ids.append(e.token_type_ids)\n attention_mask.append(e.attention_mask)\n labels.append(e.label_ids)\n\n # parse examples to dataset\n def _to_dataset(x, dtype=tf.int32):\n x = tf.ragged.constant(x, dtype=dtype)\n d = tf.data.Dataset.from_tensor_slices(x)\n d = d.map(lambda x: x)\n return d\n\n dataset = tf.data.Dataset.zip(\n (\n _to_dataset(input_ids),\n _to_dataset(token_type_ids),\n _to_dataset(attention_mask),\n _to_dataset(labels),\n )\n )\n return dataset\n\n def _filter(self, dataset: tf.data.Dataset, do_filer=True, max_sequence_length=512, **kwargs) -> tf.data.Dataset:\n if not do_filer:\n return dataset\n dataset = dataset.filter(lambda a, b, c, y: tf.size(a) <= max_sequence_length)\n return dataset\n\n def _to_dict(self, dataset: tf.data.Dataset, to_dict=True, **kwargs) -> tf.data.Dataset:\n num_parallel_calls = kwargs.get(\"num_parallel_calls\", utils.AUTOTUNE)\n if not to_dict:\n dataset = dataset.map(\n lambda a, b, c, y: ((a, b, c), y),\n num_parallel_calls=num_parallel_calls,\n )\n return dataset\n dataset = dataset.map(\n lambda a, b, c, y: ({self.input_ids: a, self.token_type_ids: b, self.attention_mask: c}, {self.labels: y}),\n num_parallel_calls=num_parallel_calls,\n ).prefetch(kwargs.get(\"buffer_size\", utils.AUTOTUNE))\n return dataset\n\n def _fixed_padding(self, dataset: tf.data.Dataset, pad_id=0, max_sequence_length=512, **kwargs) -> tf.data.Dataset:\n maxlen = tf.constant(max_sequence_length, dtype=tf.int32)\n pad_id = tf.constant(pad_id, dtype=tf.int32)\n # fmt: off\n padded_shapes = kwargs.get(\"padded_shapes\", ([maxlen, ], [maxlen, ], [maxlen, ], [maxlen, ]))\n padding_values = kwargs.get(\"padding_values\", (pad_id, pad_id, pad_id, pad_id))\n # fmt: on\n dataset = utils.batching_and_padding(dataset, padded_shapes, padding_values, **kwargs)\n return dataset\n\n def _batch_padding(self, dataset: tf.data.Dataset, pad_id=0, **kwargs) -> tf.data.Dataset:\n pad_id = tf.constant(pad_id, dtype=tf.int32)\n # fmt: off\n padded_shapes = kwargs.get(\"padded_shapes\", ([None, ], [None, ], [None, ], [None, ]))\n padding_values = kwargs.get(\"padding_values\", (pad_id, pad_id, pad_id, pad_id))\n # fmt: on\n dataset = utils.batching_and_padding(dataset, padded_shapes, padding_values, **kwargs)\n return dataset\n\n def _bucket_padding(self, dataset: tf.data.Dataset, pad_id=0, **kwargs) -> tf.data.Dataset:\n pad_id = tf.constant(pad_id, dtype=tf.int32)\n # fmt: off\n padded_shapes = kwargs.get(\"padded_shapes\", ([None, ], [None, ], [None, ], [None, ]))\n padding_values = kwargs.get(\"padding_values\", (pad_id, pad_id, pad_id, pad_id))\n # fmt: on\n dataset = utils.bucketing_and_padding(\n dataset,\n bucket_fn=lambda a, b, c, y: tf.size(a),\n padded_shapes=padded_shapes,\n padding_values=padding_values,\n **kwargs,\n )\n return dataset\n" ]
[ [ "tensorflow.sparse.to_dense", "tensorflow.constant", "tensorflow.ragged.constant", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.io.VarLenFeature", "tensorflow.io.parse_example", "tensorflow.size" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
QUER01/flask-gentelella
[ "6344c0575abd1f6b1d715462206ebee2727c70de" ]
[ "source/tables/routes.py" ]
[ "from flask import Blueprint, render_template, request\nfrom flask_login import login_required\nfrom database import db\nfrom base.models import data_table_1\nfrom base.models import data_table_2\nimport datetime\nimport pandas as pd\n\nblueprint = Blueprint(\n 'tables_blueprint',\n __name__,\n url_prefix='/tables',\n template_folder='templates',\n static_folder='static'\n)\n\n\ndef retrieve_data(data_obect):\n raw_data = [i for i in data_obect.query.all()]\n legend = 'Monthly Data'\n labels = []\n values = []\n\n for u in data_obect.query.all():\n print(u.name, u.value1)\n values.append(u.value1)\n labels.append(u.name)\n\n df =pd.DataFrame()\n df[\"labels\"] = labels\n df[\"values\"] = values\n df[\"raw_data\"] = raw_data\n df[\"legend\"] = legend\n\n return (df)\n\n\[email protected]('/<template>')\n@login_required\ndef route_template(template):\n df = retrieve_data(data_table_1)\n return render_template(template + '.html'\n ,data_from_table_1 = df[\"raw_data\"]\n ,data_from_table_2 = df[\"raw_data\"]\n ,values=df[\"values\"], labels=df[\"labels\"], legend=df[\"legend\"]\n )\n\n\n\n\n#@blueprint.route('/<template>_handle_data', methods=['GET', 'POST'])\[email protected]('/<template>', methods=['GET', 'POST'])\n@login_required\ndef route_template_send_data(template):\n # Request data from form\n data_table_1_id = request.form['data_table_1_id']\n\n # Build new insert string that isnerts data into database\n newdata = data_table_1(data_table_1_id,'jhfj2','gys', 100)\n db.session.add(newdata)\n db.session.commit()\n\n # retrieve new data\n df = retrieve_data(data_table_1)\n\n return render_template(template + '.html'\n ,data_from_table_1 = df[\"raw_data\"]\n ,data_from_table_2 = df[\"raw_data\"]\n ,values=df[\"values\"], labels=df[\"labels\"], legend=df[\"legend\"]\n )\n\n\n\n\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
dair-iitd/1oML_workdir
[ "37117de4abf1774548786e9534c90977d67091d8" ]
[ "difflogic/nn/neural_logic/modules/neural_logic.py" ]
[ "#! /usr/bin/env python3\n#\n# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"MLP-based implementation for logic and logits inference.\"\"\"\n\nimport torch.nn as nn\n\nfrom jactorch.quickstart.models import MLPModel\n\n__all__ = ['LogicInference', 'LogitsInference','LogicSoftmaxInference']\n\n\nclass InferenceBase(nn.Module):\n \"\"\"MLP model with shared parameters among other axies except the channel axis.\"\"\"\n\n def __init__(self, input_dim, output_dim, hidden_dim):\n super().__init__()\n self.input_dim = input_dim\n self.output_dim = output_dim\n self.hidden_dim = hidden_dim\n self.layer = nn.Sequential(MLPModel(input_dim, output_dim, hidden_dim))\n\n def forward(self, inputs):\n input_size = inputs.size()[:-1]\n input_channel = inputs.size(-1)\n\n f = inputs.view(-1, input_channel)\n f = self.layer(f)\n f = f.view(*input_size, -1)\n return f\n\n def get_output_dim(self, input_dim):\n return self.output_dim\n\n\nclass LogicInference(InferenceBase):\n \"\"\"MLP layer with sigmoid activation.\"\"\"\n\n def __init__(self, input_dim, output_dim, hidden_dim):\n super().__init__(input_dim, output_dim, hidden_dim)\n self.layer.add_module(str(len(self.layer)), nn.Sigmoid())\n\n\nclass LogitsInference(InferenceBase):\n \"\"\"MLP layer without sigmoid activation.\"\"\"\n def __init__(self, input_dim, output_dim, hidden_dim):\n super().__init__(input_dim, output_dim, hidden_dim)\n #self.layer.add_module(str(len(self.layer)), nn.Sigmoid())\n\nclass LogicSoftmaxInference(InferenceBase):\n \"\"\"MLP layer with sigmoid activation.\"\"\"\n\n def __init__(self, input_dim, output_dim, hidden_dim):\n super().__init__(input_dim, output_dim, hidden_dim)\n self.layer.add_module(str(len(self.layer)), nn.Softmax(dim=-1))\n" ]
[ [ "torch.nn.Softmax", "torch.nn.Sigmoid" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
luke-who/TFF
[ "fe9f44a504bc51b603a3ab9a181148da0aa9612f" ]
[ "federated/distributed_discrete_gaussian/discrete_gaussian_utils_test.py" ]
[ "# Copyright 2021, Google LLC. 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# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Tests for discrete_gaussian_utils.\"\"\"\n\nimport collections\nimport fractions\nimport math\nimport random\n\nfrom absl.testing import parameterized\nimport numpy as np\nimport tensorflow as tf\nfrom distributed_discrete_gaussian import discrete_gaussian_utils\n\nGT_SAMPLER_SEED = 4242\n\n\nclass DiscreteGaussianUtilsTest(tf.test.TestCase, parameterized.TestCase):\n\n @parameterized.product(dtype=[tf.bool, tf.float32, tf.float64])\n def test_raise_on_bad_dtype(self, dtype):\n with self.assertRaises(ValueError):\n _ = discrete_gaussian_utils.sample_discrete_gaussian(1, (1,), dtype)\n\n def test_raise_on_negative_scale(self):\n with self.assertRaises(tf.errors.InvalidArgumentError):\n _ = discrete_gaussian_utils.sample_discrete_gaussian(-10, (1,))\n\n def test_raise_on_float_scale(self):\n with self.assertRaises(TypeError):\n _ = discrete_gaussian_utils.sample_discrete_gaussian(3.14, (1,))\n\n @parameterized.product(shape=[(), (1,), (100,), (2, 2), (3, 3, 3),\n (4, 1, 1, 1)])\n def test_shapes(self, shape):\n samples = discrete_gaussian_utils.sample_discrete_gaussian(100, shape)\n samples = self.evaluate(samples)\n self.assertAllEqual(samples.shape, shape)\n\n @parameterized.product(dtype=[tf.int32, tf.int64])\n def test_dtypes(self, dtype):\n samples = discrete_gaussian_utils.sample_discrete_gaussian(1, (10,), dtype)\n samples = self.evaluate(samples)\n # Convert output np dtypes to tf dtypes.\n self.assertEqual(tf.as_dtype(samples.dtype), dtype)\n\n def test_zero_noise(self):\n scale = 0\n shape = (100,)\n dtype = tf.int32\n samples = discrete_gaussian_utils.sample_discrete_gaussian(\n scale, shape, dtype=dtype)\n samples = self.evaluate(samples)\n self.assertAllEqual(samples, tf.zeros(shape, dtype=dtype))\n\n @parameterized.named_parameters([('small_scale_small_n', 10, 2000, 1, 2),\n ('small_scale_large_n', 10, 5000, 1, 1),\n ('large_scale_small_n', 50, 2000, 2, 5),\n ('large_scale_large_n', 50, 5000, 2, 3)])\n def test_match_exact_sampler(self, scale, num_samples, mean_std_atol,\n percentile_atol):\n true_samples = exact_sampler(scale, num_samples)\n drawn_samples = discrete_gaussian_utils.sample_discrete_gaussian(\n scale=scale, shape=(num_samples,))\n drawn_samples = self.evaluate(drawn_samples)\n\n # Check mean, std, and percentiles.\n self.assertAllClose(\n np.mean(true_samples), np.mean(drawn_samples), atol=mean_std_atol)\n self.assertAllClose(\n np.std(true_samples), np.std(drawn_samples), atol=mean_std_atol)\n self.assertAllClose(\n np.percentile(true_samples, [10, 30, 50, 70, 90]),\n np.percentile(drawn_samples, [10, 30, 50, 70, 90]),\n atol=percentile_atol)\n\n @parameterized.named_parameters([('n_1000', 1000, 5e-2),\n ('n_10000', 10000, 5e-3)])\n def test_kl_divergence(self, num_samples, kl_tolerance):\n \"\"\"Compute KL divergence betwen empirical & true distribution.\"\"\"\n scale = 10\n sq_sigma = scale * scale\n drawn_samples = discrete_gaussian_utils.sample_discrete_gaussian(\n scale=scale, shape=(num_samples,))\n drawn_samples = self.evaluate(drawn_samples)\n value_counts = collections.Counter(drawn_samples)\n\n kl = 0\n norm_const = dgauss_normalizing_constant(sq_sigma)\n\n for value, count in value_counts.items():\n kl += count * (\n math.log(count * norm_const / num_samples) + value * value /\n (2.0 * sq_sigma))\n\n kl /= num_samples\n self.assertLess(kl, kl_tolerance)\n\n\ndef exact_sampler(scale, num_samples, seed=GT_SAMPLER_SEED):\n \"\"\"Implementation of the exact discrete gaussian distribution sampler.\n\n Source: https://arxiv.org/pdf/2004.00010.pdf.\n\n Args:\n scale: The scale of the discrete Gaussian.\n num_samples: The number of samples to generate.\n seed: The seed for the random number generator to reproduce samples.\n\n Returns:\n A numpy array of discrete Gaussian samples.\n \"\"\"\n\n def randrange(a, rng):\n return rng.randrange(a)\n\n def bern_em1(rng):\n \"\"\"Sample from Bernoulli(exp(-1)).\"\"\"\n k = 2\n while True:\n if randrange(k, rng) == 0: # if Bernoulli(1/k)==1\n k = k + 1\n else:\n return k % 2\n\n def bern_emab1(a, b, rng):\n \"\"\"Sample from Bernoulli(exp(-a/b)), assuming 0 <= a <= b.\"\"\"\n assert isinstance(a, int)\n assert isinstance(b, int)\n assert 0 <= a <= b\n k = 1\n while True:\n if randrange(b, rng) < a and randrange(k, rng) == 0: # if Bern(a/b/k)==1\n k = k + 1\n else:\n return k % 2\n\n def bern_emab(a, b, rng):\n \"\"\"Sample from Bernoulli(exp(-a/b)), allowing a > b.\"\"\"\n while a > b:\n if bern_em1(rng) == 0:\n return 0\n a = a - b\n return bern_emab1(a, b, rng)\n\n def geometric(t, rng):\n \"\"\"Sample from geometric(1-exp(-1/t)).\"\"\"\n assert isinstance(t, int)\n assert t > 0\n while True:\n u = randrange(t, rng)\n if bern_emab1(u, t, rng) == 1:\n while bern_em1(rng) == 1:\n u = u + t\n return u\n\n def dlap(t, rng):\n \"\"\"Sample from discrete Laplace with scale t.\n\n Pr[x] = exp(-|x|/t) * (exp(1/t)-1)/(exp(1/t)+1). Supported on integers.\n\n Args:\n t: The scale.\n rng: The random number generator.\n\n Returns:\n A discrete Laplace sample.\n \"\"\"\n assert isinstance(t, int)\n assert t > 0\n while True:\n u = geometric(t, rng)\n b = randrange(2, rng)\n if b == 1:\n return u\n elif u > 0:\n return -u\n\n def floorsqrt(x):\n \"\"\"Compute floor(sqrt(x)) exactly.\"\"\"\n assert x >= 0\n a = 0 # maintain a^2<=x.\n b = 1 # maintain b^2>x.\n while b * b <= x:\n b = 2 * b\n # Do binary search.\n while a + 1 < b:\n c = (a + b) // 2\n if c * c <= x:\n a = c\n else:\n b = c\n return a\n\n def dgauss(ss, num, rng):\n \"\"\"Sample from discrete Gaussian.\n\n Args:\n ss: Variance proxy, squared scale, sigma^2.\n num: The number of samples to generate.\n rng: The random number generator.\n\n Returns:\n A list of discrete Gaussian samples.\n \"\"\"\n ss = fractions.Fraction(ss) # cast to rational for exact arithmetic\n assert ss > 0\n t = floorsqrt(ss) + 1\n results = []\n trials = 0\n while len(results) < num:\n trials = trials + 1\n y = dlap(t, rng)\n z = (abs(y) - ss / t)**2 / (2 * ss)\n if bern_emab(z.numerator, z.denominator, rng) == 1:\n results.append(y)\n return results, t, trials\n\n rng = random.Random(seed)\n return np.array(dgauss(scale * scale, num_samples, rng)[0])\n\n\ndef dgauss_normalizing_constant(sigma_sq):\n \"\"\"Compute the normalizing constant of the discrete Gaussian.\n\n Source: https://arxiv.org/pdf/2004.00010.pdf.\n\n Args:\n sigma_sq: Variance proxy, squared scale, sigma^2.\n\n Returns:\n The normalizing constant.\n \"\"\"\n original = None\n poisson = None\n if sigma_sq <= 1:\n original = 0\n x = 1000\n while x > 0:\n original = original + math.exp(-x * x / (2.0 * sigma_sq))\n x = x - 1\n original = 2 * original + 1\n\n if sigma_sq * 100 >= 1:\n poisson = 0\n y = 1000\n while y > 0:\n poisson = poisson + math.exp(-math.pi * math.pi * sigma_sq * 2 * y * y)\n y = y - 1\n poisson = math.sqrt(2 * math.pi * sigma_sq) * (1 + 2 * poisson)\n\n if poisson is None:\n return original\n if original is None:\n return poisson\n\n scale = max(1, math.sqrt(2 * math.pi * sigma_sq))\n precision = 1e-15\n assert -precision * scale <= original - poisson <= precision * scale\n return (original + poisson) / 2\n\n\nif __name__ == '__main__':\n tf.test.main()\n" ]
[ [ "tensorflow.as_dtype", "tensorflow.zeros", "tensorflow.test.main", "numpy.percentile", "numpy.std", "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pyne/magic-cones
[ "0920eefaad6669667059ee9c6b749c2034489893" ]
[ "gaia.py" ]
[ "\"\"\"Defending the earth mother.\"\"\"\nfrom __future__ import print_function\n\nimport numpy as np\n\nimport grimoire\nfrom utils import inventories\n\nP = np.exp(-np.log(2.0)/52.0)\n\"\"\"Cone survival probability per week\"\"\"\n\ndef drop(trans):\n \"\"\"Drops magic cones, maybe.\"\"\"\n spells = list(grimoire.SPELLBOOK.keys())\n nspells = len(spells)\n hist = trans['history']\n invs = inventories(trans)\n for player, inv in invs.items():\n p = np.random.rand()\n cones = inv['cones']\n if (cones <= 512 and p <= cones / 1024.0) or \\\n (cones > 512 and p <= cones / 2.0**(int(np.log2(cones)) + 2)):\n hist.append({'player': player, 'kind': 'drop', \n 'magic': {spells[np.random.randint(0, nspells)]: 1}})\n\ndef decay(trans):\n \"\"\"Decays cones weekly - you must stay active!\"\"\"\n hist = trans['history']\n invs = inventories(trans)\n for player, inv in invs.items():\n p = np.random.rand()\n cones = inv['cones']\n # trick to obtain average decay behaviour, even in small samples, \n # without having to roll for each cone individually.\n q, r = divmod(cones*P, 1)\n n = int(q) + int(p <= r)\n if n != cones:\n hist.append({'player': player, 'kind': 'decay', 'cones': n - cones})\n \n \n " ]
[ [ "numpy.log", "numpy.log2", "numpy.random.rand", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hth945/pytest
[ "83e2aada82a2c6a0fdd1721320e5bf8b8fd59abc" ]
[ "tf/yolov4tinyza/myYoloData.py" ]
[ "#%%\n# \nfrom tqdm import tqdm\nimport time\nimport os\nimport numpy as np\nimport cv2\nfrom PIL import Image\nfrom utils import get_random_data, get_random_data_with_Mosaic\nfrom matplotlib import pyplot as plt\n\ndef rand(a=0.0, b=1.0):\n return np.random.rand()*(b-a) + a\n\n#---------------------------------------------------#\n# 获得类和先验框\n#---------------------------------------------------#\ndef get_classes(classes_path):\n '''loads the classes'''\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\ndef get_anchors(anchors_path):\n '''loads the anchors from a file'''\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\n\n#---------------------------------------------------#\n# 训练数据生成器\n#---------------------------------------------------#\ndef data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes, mosaic=False):\n '''data generator for fit_generator'''\n n = len(annotation_lines)\n i = 0\n flag = True\n while True:\n image_data = []\n box_data = []\n for b in range(batch_size):\n if i==0:\n np.random.shuffle(annotation_lines)\n if mosaic:\n if flag and (i+4) < n:\n image, box = get_random_data_with_Mosaic(annotation_lines[i:i+4], input_shape)\n i = (i+1) % n\n else:\n image, box = get_random_data(annotation_lines[i], input_shape)\n i = (i+1) % n\n flag = bool(1-flag)\n else:\n image, box = get_random_data(annotation_lines[i], input_shape)\n i = (i+1) % n\n image_data.append(image)\n box_data.append(box)\n \n \n image_data = np.array(image_data)\n box_data = np.array(box_data)\n \n y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)\n yield image_data, y_true[0], y_true[1]\n\n\n#---------------------------------------------------#\n# 读入xml文件,并输出y_true\n#---------------------------------------------------#\ndef preprocess_true_boxes(true_boxes, input_shape, anchors, num_classes):\n assert (true_boxes[..., 4]<num_classes).all(), 'class id must be less than num_classes'\n # 一共有三个特征层数\n num_layers = len(anchors)//3\n # 先验框\n # 678为 142,110, 192,243, 459,401\n # 345为 36,75, 76,55, 72,146\n # 012为 12,16, 19,36, 40,28\n anchor_mask = [[6,7,8], [3,4,5], [0,1,2]] if num_layers==3 else [[3,4,5], [1,2,3]]\n\n true_boxes = np.array(true_boxes, dtype='float32')\n input_shape = np.array(input_shape, dtype='int32') # 416,416\n # 读出xy轴,读出长宽\n # 中心点(m,n,2)\n boxes_xy = (true_boxes[..., 0:2] + true_boxes[..., 2:4]) // 2\n boxes_wh = true_boxes[..., 2:4] - true_boxes[..., 0:2]\n # 计算比例\n true_boxes[..., 0:2] = boxes_xy/input_shape[:]\n true_boxes[..., 2:4] = boxes_wh/input_shape[:]\n\n # m张图\n m = true_boxes.shape[0]\n # 得到网格的shape为13,13;26,26;52,52\n grid_shapes = [input_shape//{0:32, 1:16, 2:8}[l] for l in range(num_layers)]\n # y_true的格式为(m,13,13,3,85)(m,26,26,3,85)(m,52,52,3,85)\n y_true = [np.zeros((m,grid_shapes[l][0],grid_shapes[l][1],len(anchor_mask[l]),5+num_classes),\n dtype='float32') for l in range(num_layers)]\n # [1,9,2]\n anchors = np.expand_dims(anchors, 0)\n anchor_maxes = anchors / 2.\n anchor_mins = -anchor_maxes\n # 长宽要大于0才有效\n valid_mask = boxes_wh[..., 0]>0\n\n print(true_boxes)\n\n for b in range(m):\n # 对每一张图进行处理\n wh = boxes_wh[b, valid_mask[b]]\n if len(wh)==0: continue\n # [n,1,2]\n wh = np.expand_dims(wh, -2)\n box_maxes = wh / 2.\n box_mins = -box_maxes\n\n # 计算真实框和哪个先验框最契合\n intersect_mins = np.maximum(box_mins, anchor_mins)\n intersect_maxes = np.minimum(box_maxes, anchor_maxes)\n intersect_wh = np.maximum(intersect_maxes - intersect_mins, 0.)\n intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1]\n box_area = wh[..., 0] * wh[..., 1]\n anchor_area = anchors[..., 0] * anchors[..., 1]\n iou = intersect_area / (box_area + anchor_area - intersect_area)\n # 维度是(n) 感谢 消尽不死鸟 的提醒\n best_anchor = np.argmax(iou, axis=-1)\n\n for t, n in enumerate(best_anchor):\n for l in range(num_layers):\n if n in anchor_mask[l]:\n # floor用于向下取整\n i = np.floor(true_boxes[b,t,0]*grid_shapes[l][1]).astype('int32')\n j = np.floor(true_boxes[b,t,1]*grid_shapes[l][0]).astype('int32')\n # 找到真实框在特征层l中第b副图像对应的位置\n k = anchor_mask[l].index(n)\n c = true_boxes[b,t, 4].astype('int32')\n # print(t,n,l)\n # print(true_boxes[b,t, :])\n\n y_true[l][b, j, i, k, 0:4] = true_boxes[b,t, 0:4]\n y_true[l][b, j, i, k, 4] = 1\n y_true[l][b, j, i, k, 5+c] = 1\n # else:\n # print(t,n,l,'NG')\n\n\n return y_true\n\nif __name__ == '__main__':\n annotation_path = r'D:\\sysDef\\Documents\\GitHub\\pytest\\dataAndModel\\data\\mnist\\objtrainlab.txt'\n anchors_path = 'yolo_anchors.txt'\n with open(annotation_path) as f:\n lines = f.readlines()\n import myYoloData\n anchors = myYoloData.get_anchors(anchors_path)\n\n line = lines[0].split()\n image = Image.open(line[0])\n iw, ih = image.size\n h, w = (419,419)\n box = np.array([[np.array(list(map(int, box.split(',')))) for box in line[1:]]])\n y_true = preprocess_true_boxes(box, (416,416), anchors, 10)\n y_true0 = y_true[0]\n y_true1 = y_true[1]\n\n image_data = np.array(image,np.float32)/255 # cv2.cvtColor(, cv2.COLOR_RGB2HSV)\n # print(y_true)\n print(image_data.shape)\n print(y_true0.shape)\n print(y_true1.shape)\n \n\n \n print((np.reshape(y_true0,[-1,3,15])[:,:,4] > 0.5).sum())\n print((np.reshape(y_true1,[-1,3,15])[:,:,4] > 0.5).sum())\n\n import cv2\n from cv2 import cv2\n image = image_data.copy()\n\n\n lab = np.reshape(y_true0,[-1,3,15])\n bboxs = lab[lab[:,:,4] > 0.5][:,:4]\n for i in range(bboxs.shape[0]):\n bbox = bboxs[i]\n image = cv2.rectangle(image, (int(float(bbox[0]*416 - bbox[2]*416/2)),\n int(float(bbox[1]*416 - bbox[3]*416/2))),\n (int(float(bbox[0]*416 + bbox[2]*416/2)),\n int(float(bbox[1]*416 + bbox[3]*416/2))), (1.0, 0, 0), 2)\n lab = np.reshape(y_true1,[-1,3,15])\n bboxs = lab[lab[:,:,4] > 0.5][:,:4]\n for i in range(bboxs.shape[0]):\n bbox = bboxs[i]\n image = cv2.rectangle(image, (int(float(bbox[0]*416 - bbox[2]*416/2)),\n int(float(bbox[1]*416 - bbox[3]*416/2))),\n (int(float(bbox[0]*416 + bbox[2]*416/2)),\n int(float(bbox[1]*416 + bbox[3]*416/2))), (1.0, 0, 0), 2)\n plt.imshow(image)\n\n\n#%%\n\n\n#%%\nif __name__ == '__main1__':\n annotation_path = r'D:\\sysDef\\Documents\\GitHub\\pytest\\dataAndModel\\data\\mnist\\objtrainlab.txt'\n anchors_path = 'yolo_anchors.txt'\n with open(annotation_path) as f:\n lines = f.readlines()\n anchors = get_anchors(anchors_path)\n gen = data_generator(annotation_lines=lines, batch_size=1,\n input_shape=(416,416),\n anchors=anchors, num_classes=10)\n for image_data, y_true0, y_true1 in gen:\n print(image_data.shape)\n print(y_true0.shape)\n print(y_true1.shape)\n \n\n \n print((np.reshape(y_true0,[-1,3,15])[:,:,4] > 0.5).sum())\n print((np.reshape(y_true1,[-1,3,15])[:,:,4] > 0.5).sum())\n\n import cv2\n from cv2 import cv2\n image = image_data[0].copy()\n\n\n lab = np.reshape(y_true0,[-1,3,15])\n bboxs = lab[lab[:,:,4] > 0.5][:,:4]\n for i in range(bboxs.shape[0]):\n bbox = bboxs[i]\n image = cv2.rectangle(image, (int(float(bbox[0]*416 - bbox[2]*416/2)),\n int(float(bbox[1]*416 - bbox[3]*416/2))),\n (int(float(bbox[0]*416 + bbox[2]*416/2)),\n int(float(bbox[1]*416 + bbox[3]*416/2))), (1.0, 0, 0), 2)\n lab = np.reshape(y_true1,[-1,3,15])\n bboxs = lab[lab[:,:,4] > 0.5][:,:4]\n for i in range(bboxs.shape[0]):\n bbox = bboxs[i]\n image = cv2.rectangle(image, (int(float(bbox[0]*416 - bbox[2]*416/2)),\n int(float(bbox[1]*416 - bbox[3]*416/2))),\n (int(float(bbox[0]*416 + bbox[2]*416/2)),\n int(float(bbox[1]*416 + bbox[3]*416/2))), (1.0, 0, 0), 2)\n plt.imshow(image)\n\n break\n" ]
[ [ "matplotlib.pyplot.imshow", "numpy.expand_dims", "numpy.maximum", "numpy.minimum", "numpy.reshape", "numpy.random.shuffle", "numpy.argmax", "numpy.random.rand", "numpy.floor", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vasugamdha/stylegan2
[ "df1aace0c48a4f4754cc0c9627571a12be28b0d6" ]
[ "blend_models.py" ]
[ "import tensorflow as tf\nimport sys, getopt, os\n\nimport numpy as np\nimport dnnlib\nimport dnnlib.tflib as tflib\nfrom dnnlib.tflib import tfutil\nfrom dnnlib.tflib.autosummary import autosummary\nimport math\nimport numpy as np\n\nfrom training import dataset\nfrom training import misc\nimport pickle\n\nfrom pathlib import Path\nimport typer\nfrom typing import Optional\n\ndef extract_conv_names(model):\n # layers are G_synthesis/{res}x{res}/...\n # make a list of (name, resolution, level, position)\n # Currently assuming square(?)\n\n model_names = list(model.trainables.keys())\n conv_names = []\n\n resolutions = [4*2**x for x in range(9)]\n\n level_names = [[\"Conv0_up\", \"Const\"],\n [\"Conv1\", \"ToRGB\"]]\n \n position = 0\n # option not to split levels\n for res in resolutions:\n root_name = f\"G_synthesis/{res}x{res}/\"\n for level, level_suffixes in enumerate(level_names):\n for suffix in level_suffixes:\n search_name = root_name + suffix\n matched_names = [x for x in model_names if x.startswith(search_name)]\n to_add = [(name, f\"{res}x{res}\", level, position) for name in matched_names]\n conv_names.extend(to_add)\n position += 1\n\n return conv_names\n\n\ndef blend_models(model_1, model_2, resolution, level, blend_width=None, verbose=False):\n\n # y is the blending amount which y = 0 means all model 1, y = 1 means all model_2\n\n # TODO add small x offset for smoother blend animations\n resolution = f\"{resolution}x{resolution}\"\n \n model_1_names = extract_conv_names(model_1)\n model_2_names = extract_conv_names(model_2)\n\n assert all((x == y for x, y in zip(model_1_names, model_2_names)))\n\n model_out = model_1.clone()\n\n short_names = [(x[1:3]) for x in model_1_names]\n full_names = [(x[0]) for x in model_1_names]\n mid_point_idx = short_names.index((resolution, level))\n mid_point_pos = model_1_names[mid_point_idx][3]\n \n ys = []\n for name, resolution, level, position in model_1_names:\n # low to high (res)\n x = position - mid_point_pos\n if blend_width:\n exponent = -x/blend_width\n y = 1 / (1 + math.exp(exponent))\n else:\n y = 1 if x > 1 else 0\n\n ys.append(y)\n if verbose:\n print(f\"Blending {name} by {y}\")\n\n tfutil.set_vars(\n tfutil.run(\n {model_out.vars[name]: (model_2.vars[name] * y + model_1.vars[name] * (1-y))\n for name, y \n in zip(full_names, ys)}\n )\n )\n\n return model_out\n\ndef main(low_res_pkl: Path, # Pickle file from which to take low res layers\n high_res_pkl: Path, # Pickle file from which to take high res layers\n resolution: int, # Resolution level at which to switch between models\n level: int = 0, # Switch at Conv block 0 or 1?\n blend_width: Optional[float] = None, # None = hard switch, float = smooth switch (logistic) with given width\n output_grid: Optional[Path] = \"blended.jpg\", # Path of image file to save example grid (None = don't save)\n seed: int = 0, # seed for random grid\n output_pkl: Optional[Path] = None, # Output path of pickle (None = don't save)\n verbose: bool = False, # Print out the exact blending fraction\n ):\n\n grid_size = (3, 3)\n\n tflib.init_tf()\n\n with tf.Session() as sess, tf.device('/gpu:0'):\n low_res_G, low_res_D, low_res_Gs = misc.load_pkl(low_res_pkl)\n high_res_G, high_res_D, high_res_Gs = misc.load_pkl(high_res_pkl)\n\n out = blend_models(low_res_Gs, high_res_Gs, resolution, level, blend_width=blend_width, verbose=verbose)\n\n if output_grid:\n rnd = np.random.RandomState(seed)\n grid_latents = rnd.randn(np.prod(grid_size), *out.input_shape[1:])\n grid_fakes = out.run(grid_latents, None, is_validation=True, minibatch_size=1)\n misc.save_image_grid(grid_fakes, output_grid, drange= [-1,1], grid_size=grid_size)\n\n # TODO modify all the networks\n if output_pkl:\n misc.save_pkl((low_res_G, low_res_D, out), output_pkl)\n print('%s saved'%output_pkl)\n \nif __name__ == '__main__':\n typer.run(main)\n \n" ]
[ [ "numpy.prod", "tensorflow.device", "numpy.random.RandomState", "tensorflow.Session" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
Angel-Vazquez/CS497-7-Intro-to-Deep-Learning
[ "86f6169718c52e314e00dfa937ae27678fe2e977" ]
[ "hw1/softmaxExercise.py" ]
[ "## Softmax Exercise \n\n# Instructions\n# ------------\n# \n# This file contains code that helps you get started on the\n# softmax exercise. You will need to write the softmax cost function and\n# the softmax prediction function in softmax.py. You will also need to write\n# code in computeNumericalGradient.py.\n# For this exercise, you will not need to change any code in this file,\n# or any other files other than the ones mentioned above.\n\nimport argparse\nimport sys\n\nimport numpy as np\nfrom numpy.random import randn, randint\nfrom numpy.linalg import norm\nimport matplotlib.pyplot as plt\n\nfrom softmax import softmaxCost, softmaxPredict\nfrom computeNumericalGradient import computeNumericalGradient\n\nimport utils\n\nparser = argparse.ArgumentParser('Softmax Exercise.')\nparser.add_argument('-i', '--input_data',\n type=str,\n default='spiral',\n help='Dataset: select between \"spiral\" and \"flower\".')\nparser.add_argument('-d', '--debug',\n action='store_true',\n help='Used for gradient checking.')\n\nFLAGS, unparsed = parser.parse_known_args()\n\n##======================================================================\n## STEP 1: Loading data\n#\n# In this section, we load the training examples and their labels.\n\nif FLAGS.input_data == 'spiral':\n instances, labels, numClasses = utils.load_spiral_dataset()\nelif FLAGS.input_data == 'flower':\n instances, labels, numClasses = utils.load_flower_dataset()\nelse:\n print('Wrong dataset specified. Select between \"spiral\" and \"flower\".')\n sys.exit(1)\n\ninputSize = instances.shape[0]\nnumExamples = instances.shape[1]\n\n# For debugging purposes, you may wish to reduce the size of the input data\n# in order to speed up gradient checking. \n# Here, we create synthetic dataset using random data for testing\n\nif FLAGS.debug:\n inputSize = 8\n instances, labels = randn(8, 100), randint(0, numClasses, 100, dtype = np.uint8)\n\n# Randomly initialize parameters\nW = 0.01 * randn(numClasses, inputSize)\nb = np.zeros((numClasses, 1))\n\n##======================================================================\n## STEP 2: Gradient checking\n#\n# As with any learning algorithm, you should always check that your\n# gradients are correct before learning the parameters.\n#\n\nif FLAGS.debug:\n decay = 0.001\n cost, dW, db = softmaxCost(W, b, numClasses, inputSize, decay, instances, labels)\n W_numGrad = computeNumericalGradient(lambda x: softmaxCost(x, b, numClasses, inputSize,\n decay, instances, labels), W)\n\n # Use this to visually compare the gradients side by side.\n print(np.stack((W_numGrad.ravel(), dW.ravel())).T)\n\n # Compare numerically computed gradients with those computed analytically.\n diff = norm(W_numGrad - dW) / norm(W_numGrad + dW)\n print(diff)\n sys.exit(0)\n # The difference should be small. \n # In our implementation, these values are usually less than 1e-7.\n\n \n##======================================================================\n## STEP 3: Learning parameters\n#\n# Once you have verified that your gradients are correct, you can start \n# training your softmax regression code using gradient descent.\n\n# Set hyper-parameters.\nlearning_rate = 1.0\ndecay = 0.001\nnum_epochs = 200\n\n# Gradient descent loop.\nfor epoch in range(num_epochs):\n # Implement softmaxCost in softmax.py, to compute cost and gradients.\n cost, dW, db = softmaxCost(W, b, numClasses, inputSize, decay, instances, labels)\n if epoch % 10 == 0:\n print(\"Epoch %d: cost %f\" % (epoch, cost))\n\n # Update parameters.\n W += -learning_rate * dW\n b += -learning_rate * db\n\n##======================================================================\n## STEP 4: Testing on training data\n#\n# You should now test your model against the training examples.\n# To do this, you will first need to write softmaxPredict\n# (in softmax.py), which should return predictions\n# given a softmax model and the input data.\n\npred = softmaxPredict(W, b, instances)\n\nacc = np.mean(labels == pred)\nprint('Accuracy: %0.3f%%.' % (acc * 100))\n\n# Accuracy is the proportion of correctly classified images\n# After 200 epochs, the results for our implementation were:\n#\n# Spiral Accuracy: 53.3%\n# Flower Accuracy: 47.0%\n\n##======================================================================\n## STEP 5: Plot the decision boundary.\n#\nutils.plot_decision_boundary(lambda x: softmaxPredict(W, b, x), instances, labels)\nplt.title(\"Softmax Regression\")\nplt.savefig(FLAGS.input_data + '-boundary.jpg')\nplt.show()\n" ]
[ [ "matplotlib.pyplot.title", "numpy.linalg.norm", "matplotlib.pyplot.savefig", "numpy.mean", "numpy.random.randn", "matplotlib.pyplot.show", "numpy.zeros", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ghj-hey/Huawei-cloud-garbage_classify_git
[ "52eb22e4666be1c141b126ff95490de8eb6b8904" ]
[ "timm_ns_swa.py" ]
[ "import argparse\nimport time\nimport yaml\nimport os\nimport logging\nfrom collections import OrderedDict\nfrom contextlib import suppress\nfrom datetime import datetime\n\nimport torch\nimport torch.nn as nn\nimport torchvision.utils\nfrom torch.nn.parallel import DistributedDataParallel as NativeDDP\n\nfrom timm.data import Dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset\nfrom timm.models import create_model, resume_checkpoint, load_checkpoint, convert_splitbn_model\nfrom timm.utils import *\nfrom timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy, JsdCrossEntropy\nfrom timm.optim import create_optimizer\nfrom timm.scheduler import create_scheduler\nfrom timm.utils import ApexScaler, NativeScaler\n\nfrom apex import amp\n\nimport torchcontrib\nfrom torch.optim import lr_scheduler\n#\nimport os\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\nimport time\nfrom sklearn.metrics import accuracy_score\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\nfrom config import Config\n\nfrom utils import rubbishDataset,cutmix_data\nfrom mymodel import BaseModel\nfrom my_loss import LabelSmoothingLoss\n\n\ndef schedule(epoch):\n swa=True\n swa_start=20\n swa_lr=1e-4\n lr_init=1e-3\n t = (epoch) / (swa_start)\n lr_ratio = swa_lr / lr_init if swa else 0.01\n if t <= 0.5:\n factor = 1.0\n elif t <= 0.9:\n factor = 1.0 - (1.0 - lr_ratio) * (t - 0.5) / 0.4\n else:\n factor = lr_ratio\n return lr_init * factor\n\n#\ndef train_model(model,criterion, optimizer):\n\n train_dataset = rubbishDataset(opt.train_val_data, opt.train_list, phase='train', input_size=opt.input_size)\n trainloader = DataLoader(train_dataset,\n batch_size=opt.train_batch_size,\n shuffle=True,\n num_workers=opt.num_workers)\n\n # scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, patience=4, verbose=False)\n # scheduler = lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1)\n\n total_iters=len(trainloader)\n model_name=opt.backbone\n train_loss = []\n since = time.time()\n best_score = 0.0\n best_epoch = 0\n # accumulation_steps=4\n #\n for epoch in range(1,opt.max_epoch+1):\n\n lr = schedule(epoch)\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n print(lr)\n\n model.train(True)\n begin_time=time.time()\n running_corrects_linear = 0\n count=0\n for i, data in enumerate(trainloader):\n count+=1\n inputs, labels = data\n labels = labels.type(torch.LongTensor)\n inputs, labels = inputs.cuda(), labels.cuda()\n\n inputs, targets_a, targets_b, lam = cutmix_data(inputs, labels, 0.5, use_cuda=True)\n # print(epoch)\n\n #\n out_linear= model(inputs)\n _, linear_preds = torch.max(out_linear.data, 1)\n\n loss = criterion(out_linear, targets_a) * lam + criterion(out_linear, targets_b) * (1. - lam)\n # loss = criterion(out_linear, labels)\n #\n optimizer.zero_grad()\n # loss = loss/accumulation_steps\n with amp.scale_loss(loss,optimizer) as scaled_loss:\n scaled_loss.backward()\n # loss.backward()\n\n # if((i+1)%accumulation_steps)==0:\n optimizer.step()\n # optimizer.zero_grad()\n\n\n\n # if epoch>21:\n # print(optimizer.param_groups[-1]['lr'])\n if i % opt.print_interval == 0 or out_linear.size()[0] < opt.train_batch_size:\n spend_time = time.time() - begin_time\n print(\n ' Epoch:{}({}/{}) loss:{:.3f} lr:{:.7f} epoch_Time:{}min:'.format(\n epoch, count, total_iters,\n loss.item(), optimizer.param_groups[-1]['lr'],\n spend_time / count * total_iters // 60 - spend_time // 60))\n train_loss.append(loss.item())\n running_corrects_linear += torch.sum(linear_preds == labels.data)\n #\n\n\n\n\n if (epoch + 1) > 3:\n # print('swa')\n optimizer.swap_swa_sgd()\n optimizer.bn_update(trainloader, model, device='cuda')\n weight_score,val_loss = val_model(model, criterion)\n else:\n weight_score,val_loss = val_model(model, criterion)\n\n # scheduler.step(val_loss)\n\n epoch_acc_linear = running_corrects_linear.double() / total_iters / opt.train_batch_size\n print('Epoch:[{}/{}] train_acc={:.3f} '.format(epoch, opt.max_epoch,\n epoch_acc_linear))\n\n\n with open(os.path.join(model_save_dir, 'log.txt'), 'a+')as f:\n f.write('epoch:{}, loss:{:.4f}, acc:{:.4f}\\n'.format(epoch, val_loss, weight_score))\n\n\n #\n model_out_path = model_save_dir + \"/\" + '{}_'.format(model_name) + str(epoch) +'_'+str(weight_score)[:6]+ '.pth'\n\n #save the best model\n if weight_score > best_score:\n best_score = weight_score\n best_epoch=epoch\n best_model_out_path = model_save_dir + \"/\" + '{}_'.format(model_name) + 'best'+'_'+str(weight_score)[:6]+ '.pth'\n torch.save(model.state_dict(), best_model_out_path)\n print(\"best epoch: {} best acc: {}\".format(best_epoch,weight_score))\n #save based on epoch interval\n if epoch % opt.save_interval == 0 and epoch>opt.min_save_epoch:\n torch.save(model.state_dict(), model_out_path)\n\n if (epoch + 1) > 3:\n optimizer.swap_swa_sgd()\n\n #\n print('Best acc: {:.3f} Best epoch:{}'.format(best_score,best_epoch))\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n\[email protected]_grad()\ndef val_model(model, criterion):\n val_dataset = rubbishDataset(opt.train_val_data, opt.val_list, phase='val', input_size=opt.input_size)\n val_loader = DataLoader(val_dataset,\n batch_size=opt.val_batch_size,\n shuffle=False,\n num_workers=opt.num_workers)\n dset_sizes=len(val_dataset)\n model.eval()\n running_loss = 0.0\n running_corrects = 0\n cont = 0\n outPre = []\n outLabel = []\n pres_list=[]\n labels_list=[]\n for data in val_loader:\n inputs, labels = data\n labels = labels.type(torch.LongTensor)\n inputs, labels = inputs.cuda(), labels.cuda()\n outputs = model(inputs)\n _, preds = torch.max(outputs.data, 1)\n loss = criterion(outputs, labels)\n if cont == 0:\n outPre = outputs.data.cpu()\n outLabel = labels.data.cpu()\n else:\n outPre = torch.cat((outPre, outputs.data.cpu()), 0)\n outLabel = torch.cat((outLabel, labels.data.cpu()), 0)\n pres_list+=preds.cpu().numpy().tolist()\n labels_list+=labels.data.cpu().numpy().tolist()\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n cont += 1\n #\n val_acc = accuracy_score(labels_list, pres_list)\n val_loss=running_loss / dset_sizes\n print('val_size: {} valLoss: {:.4f} valAcc: {:.4f}'.format(dset_sizes, running_loss / dset_sizes,\n val_acc))\n return val_acc,val_loss\n\nif __name__ == \"__main__\":\n #\n opt = Config()\n torch.cuda.empty_cache()\n device = torch.device(opt.device)\n criterion=LabelSmoothingLoss(classes=43,smoothing=0.1)\n # criterion = torch.nn.CrossEntropyLoss().cuda()\n model_name=opt.backbone\n model_save_dir =os.path.join(opt.checkpoints_dir , model_name)\n if not os.path.exists(model_save_dir): os.makedirs(model_save_dir)\n model = create_model(\n model_name,\n pretrained=True,\n num_classes=43,\n drop_rate=None,\n drop_connect_rate=None, # DEPRECATED, use drop_path\n drop_path_rate=None,\n drop_block_rate=None,\n global_pool=None,\n bn_tf=False,\n bn_momentum=None,\n bn_eps=None,\n checkpoint_path=None)\n model.to(device)\n # model = nn.DataParallel(model)\n # model_path='./ckpt/tf_efficientnet_b5_ns_best/tf_efficientnet_b5_ns_456_best_val97.24_test96.5.pth'\n #\n # net_weight = torch.load(model_path,map_location=torch.device('cpu'))\n # model.load_state_dict(net_weight)\n # for param in model.parameters():\n # param.requires_grad = False\n #\n # for param in model.classifier.parameters():\n # param.requires_grad = True\n\n\n base_lr=opt.lr\n lr_ratio=10\n # ignored_params = list(map(id, model.classifier.parameters()))\n\n # print('the num of new layers:', len(ignored_params), flush=True)\n # base_params = filter(lambda p: id(p) not in ignored_params, model.parameters())\n # optimizer = optim.SGD([{'params': base_params},\n # {'params': model.classifier.parameters(), 'lr': lr_ratio*base_lr}\n # ], lr = base_lr, momentum=0.9)\n base_optimizer = optim.SGD((model.parameters()), lr=opt.lr, momentum=opt.MOMENTUM, weight_decay=0.0004)\n\n optimizer = torchcontrib.optim.SWA(base_optimizer,0,3,1e-4)\n\n model,optimizer=amp.initialize(model,optimizer,opt_level='O1')\n train_model(model, criterion, optimizer)\n\n\n\n" ]
[ [ "torch.max", "torch.utils.data.DataLoader", "torch.cuda.empty_cache", "torch.sum", "torch.no_grad", "torch.device", "sklearn.metrics.accuracy_score" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
howardchenhd/Paraphrase_Copy
[ "a1afbdd88ee62b53ecd714e58c1f504f3eed9a48" ]
[ "src/utils/beam_search.py" ]
[ "import torch\nimport numpy as np\n\nfrom .common_utils import GlobalNames, Vocab\n\n__all__ = [\n 'tile_batch',\n 'mask_scores',\n 'tensor_gather_helper',\n 'reranking_beams'\n]\n\n_FLOAT32_INF = np.float32(np.finfo('float32').max / 10)\n\n\nclass Beam(object):\n \"\"\"\n Class for managing the internals of the beam search process.\n\n Takes care of beams, back pointers, and scores.\n\n Args:\n size (int): beam size\n pad, bos, eos (int): indices of padding, beginning, and ending.\n n_best (int): nbest size to use\n cuda (bool): use gpu\n global_scorer (:obj:`GlobalScorer`)\n \"\"\"\n def __init__(self, size, pad, bos, eos,\n n_best=1, cuda=False,\n global_scorer=None,\n min_length=0,\n stepwise_penalty=False):\n\n self.size = size\n self.tt = torch.cuda if cuda else torch\n\n # The score for each translation on the beam.\n self.scores = self.tt.FloatTensor(size).zero_()\n self.all_scores = []\n\n # The backpointers at each time-step.\n self.prev_ks = []\n\n # The outputs at each time-step.\n self.next_ys = [self.tt.LongTensor(size)\n .fill_(pad)]\n self.next_ys[0][0] = bos\n\n # Has EOS topped the beam yet.\n self._eos = eos\n self.eos_top = False\n\n # The attentions (matrix) for each time.\n self.attn = []\n\n # Time and k pair for finished.\n self.finished = []\n self.n_best = n_best\n\n # Information for global scoring.\n self.global_scorer = global_scorer\n self.global_state = {}\n\n # Minimum prediction length\n self.min_length = min_length\n\n # Apply Penalty at every step\n self.stepwise_penalty = stepwise_penalty\n\n def get_current_state(self):\n \"Get the outputs for the current timestep.\"\n return self.next_ys[-1]\n\n def get_current_origin(self):\n \"Get the backpointers for the current timestep.\"\n return self.prev_ks[-1]\n\n def advance(self, word_probs, attn_out):\n \"\"\"\n Given prob over words for every last beam `wordLk` and attention\n `attn_out`: Compute and update the beam search.\n\n Parameters:\n\n * `word_probs`- probs of advancing from the last step (K x words)\n * `attn_out`- attention at the last step\n\n Returns: True if beam search is complete.\n \"\"\"\n num_words = word_probs.size(1)\n if self.stepwise_penalty:\n self.global_scorer.update_score(self, attn_out)\n # force the output to be longer than self.min_length\n cur_len = len(self.next_ys)\n if cur_len < self.min_length:\n for k in range(len(word_probs)):\n word_probs[k][self._eos] = -1e20\n # Sum the previous scores.\n if len(self.prev_ks) > 0:\n beam_scores = word_probs + \\\n self.scores.unsqueeze(1).expand_as(word_probs)\n # Don't let EOS have children.\n for i in range(self.next_ys[-1].size(0)):\n if self.next_ys[-1][i] == self._eos:\n beam_scores[i] = -1e20\n else:\n beam_scores = word_probs[0]\n flat_beam_scores = beam_scores.view(-1)\n best_scores, best_scores_id = flat_beam_scores.topk(self.size, 0,\n True, True)\n\n self.all_scores.append(self.scores)\n self.scores = best_scores\n\n # best_scores_id is flattened beam x word array, so calculate which\n # word and beam each score came from\n prev_k = best_scores_id / num_words\n self.prev_ks.append(prev_k)\n self.next_ys.append((best_scores_id - prev_k * num_words))\n self.attn.append(attn_out.index_select(0, prev_k))\n self.global_scorer.update_global_state(self)\n\n for i in range(self.next_ys[-1].size(0)):\n if self.next_ys[-1][i] == self._eos:\n global_scores = self.global_scorer.score(self, self.scores)\n s = global_scores[i]\n self.finished.append((s, len(self.next_ys) - 1, i))\n\n # End condition is when top-of-beam is EOS and no global score.\n if self.next_ys[-1][0] == self._eos:\n self.all_scores.append(self.scores)\n self.eos_top = True\n\n def done(self):\n return self.eos_top and len(self.finished) >= self.n_best\n\n def sort_finished(self, minimum=None):\n if minimum is not None:\n i = 0\n # Add from beam until we have minimum outputs.\n while len(self.finished) < minimum:\n global_scores = self.global_scorer.score(self, self.scores)\n s = global_scores[i]\n self.finished.append((s, len(self.next_ys) - 1, i))\n i += 1\n\n self.finished.sort(key=lambda a: -a[0])\n scores = [sc for sc, _, _ in self.finished]\n ks = [(t, k) for _, t, k in self.finished]\n return scores, ks\n\n def get_hyp(self, timestep, k):\n \"\"\"\n Walk back to construct the full hypothesis.\n \"\"\"\n hyp, attn = [], []\n for j in range(len(self.prev_ks[:timestep]) - 1, -1, -1):\n hyp.append(self.next_ys[j+1][k])\n attn.append(self.attn[j][k])\n k = self.prev_ks[j][k]\n return hyp[::-1], torch.stack(attn[::-1])\n\n\ndef tile_batch(x, multiplier, batch_dim=0):\n x_size = x.size()\n out_size = x_size[:batch_dim] + (x_size[batch_dim] * multiplier,) + x_size[batch_dim+1:]\n\n x_tiled = torch.unsqueeze(x, dim=batch_dim + 1)\n x_tiled = x_tiled.repeat(*[1 if d != batch_dim + 1 else multiplier for d in range(len(x_size) + 1)])\n x_tiled = x_tiled.view(*out_size)\n\n return x_tiled\n\n\ndef mask_scores(scores, beam_mask):\n vocab_size = scores.size(-1)\n\n finished_row = beam_mask.new(vocab_size, ).zero_() + float(_FLOAT32_INF)\n\n # If beam finished, only PAD could be generated afterwards.\n finished_row[Vocab.EOS] = 0.0\n\n scores = scores * beam_mask.unsqueeze(2) + torch.matmul((1.0 - beam_mask).unsqueeze(2), finished_row.unsqueeze(0))\n\n return scores\n\n\ndef tensor_gather_helper(gather_indices,\n gather_from,\n batch_size,\n beam_size,\n gather_shape):\n\n range_ = (torch.arange(0, batch_size) * beam_size).long()\n\n if GlobalNames.USE_GPU:\n range_ = range_.cuda()\n\n gather_indices_ = (gather_indices + torch.unsqueeze(range_, 1)).view(-1) # batch1 (0:beam-1);batch2 (beam: 2beam-1)\n\n output = torch.index_select(gather_from.view(*gather_shape), 0, gather_indices_)\n\n out_size = gather_from.size()[:1 + len(gather_shape)]\n\n return output.view(*out_size)\n\ndef reranking_beams(word_ids, scores):\n\n word_ids = word_ids.cpu().numpy()\n scores = scores.cpu().numpy()\n\n # Reranking beams\n reranked_beams = np.argsort(scores, axis=1)\n reranked_word_ids = np.ones_like(word_ids) * Vocab.PAD\n\n for b in range(scores.shape[0]):\n for ii in reranked_beams[b]:\n reranked_word_ids[b, ii] = word_ids[b, ii]\n\n reranked_word_ids = reranked_word_ids.tolist()\n\n return reranked_word_ids" ]
[ [ "numpy.ones_like", "torch.unsqueeze", "numpy.finfo", "torch.arange", "torch.stack", "numpy.argsort" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shermelin/pymodaq_plugins_template
[ "e6e4f5c40cb3f1ad99493fcfac31b4f9f51917b6" ]
[ "src/pymodaq_plugins_template/daq_viewer_plugins/plugins_0D/daq_0Dviewer_Template.py" ]
[ "import numpy as np\nfrom easydict import EasyDict as edict\nfrom pymodaq.daq_utils.daq_utils import ThreadCommand, getLineInfo, DataFromPlugins\nfrom pymodaq.daq_viewer.utility_classes import DAQ_Viewer_base, comon_parameters\n\n\nclass DAQ_0DViewer_Template(DAQ_Viewer_base):\n \"\"\"\n \"\"\"\n params = comon_parameters+[\n ## TODO for your custom plugin\n # elements to be added here as dicts in order to control your custom stage\n ############\n ]\n\n def __init__(self, parent=None, params_state=None):\n super().__init__(parent, params_state)\n\n def commit_settings(self, param):\n \"\"\"\n \"\"\"\n ## TODO for your custom plugin\n if param.name() == \"a_parameter_you've_added_in_self.params\":\n self.controller.your_method_to_apply_this_param_change()\n# elif ...\n ##\n\n def ini_detector(self, controller=None):\n \"\"\"Detector communication initialization\n\n Parameters\n ----------\n controller: (object) custom object of a PyMoDAQ plugin (Slave case). None if only one detector by controller (Master case)\n\n Returns\n -------\n self.status (edict): with initialization status: three fields:\n * info (str)\n * controller (object) initialized controller\n *initialized: (bool): False if initialization failed otherwise True\n \"\"\"\n\n try:\n self.status.update(edict(initialized=False,info=\"\",x_axis=None,y_axis=None,controller=None))\n if self.settings.child(('controller_status')).value() == \"Slave\":\n if controller is None:\n raise Exception('no controller has been defined externally while this detector is a slave one')\n else:\n self.controller = controller\n else:\n ## TODO for your custom plugin\n self.controller = python_wrapper_of_your_instrument() # any object that will control the stages\n #####################################\n\n ## TODO for your custom plugin\n #initialize viewers pannel with the future type of data\n self.data_grabed_signal_temp.emit([DataFromPlugins(name='Mock1',data=[np.array([0]), np.array([0])], dim='Data0D',\n labels=['Mock1', 'label2'])])\n ##############################\n\n self.status.info = \"Whatever info you want to log\"\n self.status.initialized = True\n self.status.controller = self.controller\n return self.status\n\n except Exception as e:\n self.emit_status(ThreadCommand('Update_Status',[getLineInfo()+ str(e),'log']))\n self.status.info=getLineInfo()+ str(e)\n self.status.initialized=False\n return self.status\n\n def close(self):\n \"\"\"\n Terminate the communication protocol\n \"\"\"\n ## TODO for your custom plugin\n self.controller.your_method_to_terminate_the_communication()\n ##\n\n def grab_data(self, Naverage=1, **kwargs):\n \"\"\"\n\n Parameters\n ----------\n Naverage: (int) Number of hardware averaging\n kwargs: (dict) of others optionals arguments\n \"\"\"\n ## TODO for your custom plugin\n\n ##synchrone version (blocking function)\n data_tot = self.controller.your_method_to_start_a_grab_snap()\n self.data_grabed_signal.emit([DataFromPlugins(name='Mock1', data=data_tot,\n dim='Data0D', labels=['dat0', 'data1'])])\n #########################################################\n\n ##asynchrone version (non-blocking function with callback)\n self.controller.your_method_to_start_a_grab_snap(self.callback)\n #########################################################\n\n\n def callback(self):\n \"\"\"optional asynchrone method called when the detector has finished its acquisition of data\"\"\"\n data_tot = self.controller.your_method_to_get_data_from_buffer()\n self.data_grabed_signal.emit([DataFromPlugins(name='Mock1', data=data_tot,\n dim='Data0D', labels=['dat0', 'data1'])])\n\n def stop(self):\n\n ## TODO for your custom plugin\n self.controller.your_method_to_stop_acquisition()\n self.emit_status(ThreadCommand('Update_Status', ['Some info you want to log']))\n ##############################\n\n return ''\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
abhilash-sw/sunkit-instruments
[ "e5655da3f422e5306930a8139bbf9c839d1ac8ca" ]
[ "sunkit_instruments/lyra/lyra.py" ]
[ "\"\"\"\nThis module provides processing routines for data captured with the LYRA (Lyman\nAlpha Radiometer) instrument on Proba-2.\n\"\"\"\nimport csv\nimport copy\nimport sqlite3\nimport datetime\nfrom warnings import warn\nfrom urllib.parse import urljoin\n\nimport numpy as np\nimport pandas\n\nfrom astropy.time import Time\nfrom sunpy.data import cache\nfrom sunpy.time import parse_time\nfrom sunpy.time.time import _variables_for_parse_time_docstring\nfrom sunpy.timeseries import TimeSeries\nfrom sunpy.util.decorators import add_common_docstring\n\nLYTAF_REMOTE_PATH = \"http://proba2.oma.be/lyra/data/lytaf/\"\n\n\n__all__ = [\n \"remove_lytaf_events_from_timeseries\",\n \"get_lytaf_events\",\n \"get_lytaf_event_types\",\n \"split_series_using_lytaf\",\n \"_prep_columns\",\n \"_lytaf_event2string\",\n \"_remove_lytaf_events\",\n]\n\n\ndef remove_lytaf_events_from_timeseries(\n ts, artifacts=None, return_artifacts=False, force_use_local_lytaf=False\n):\n \"\"\"\n Removes periods of LYRA artifacts defined in LYTAF from a TimeSeries.\n\n Parameters\n ----------\n ts : `sunpy.timeseries.TimeSeries`\n artifacts : `list`\n Sets the artifact types to be removed. For a list of artifact types\n see reference [1]. For example, if a user wants to remove only large\n angle rotations, listed at reference [1] as LAR, set artifacts=[\"LAR\"].\n The default is that no artifacts will be removed.\n return_artifacts : `bool`\n Set to True to return a `numpy.recarray` containing the start time, end\n time and type of all artifacts removed.\n Default=False\n force_use_local_lytaf : `bool`\n Ensures current local version of lytaf files are not replaced by\n up-to-date online versions even if current local lytaf files do not\n cover entire input time range etc.\n Default=False\n\n Returns\n -------\n ts_new : `sunpy.timeseries.TimeSeries`\n copy of input TimeSeries with periods corresponding to artifacts\n removed.\n artifact_status : `dict`\n List of 4 variables containing information on what artifacts were\n found, removed, etc. from the time series.\n | **artifact_status[\"lytaf\"]** : `numpy.recarray`\n | The full LYRA annotation file for the time series time range\n | output by get_lytaf_events().\n | **artifact_status[\"removed\"]** : `numpy.recarray`\n | Artifacts which were found and removed from from time series.\n | **artifact_status[\"not_removed\"]** : `numpy.recarray`\n | Artifacts which were found but not removed as they were not\n | included when user defined artifacts kwarg.\n | **artifact_status[\"not_found\"]** : `list` of strings\n | Artifacts listed to be removed by user when defining\n | artifacts kwarg which were not found in time series time range.\n\n Notes\n -----\n This function is intended to take TimeSeries objects as input, but the\n deprecated LightCurve is still supported here.\n\n References\n ----------\n [1] http://proba2.oma.be/data/TARDIS\n\n Examples\n --------\n Remove LARs (Large Angle Rotations) from TimeSeries for 4-Dec-2014:\n >>> import sunpy.timeseries as ts\n >>> import sunpy.data.sample # doctest: +REMOTE_DATA\n >>> from sunkit_instruments.lyra import remove_lytaf_events_from_timeseries\n >>> lyrats = ts.TimeSeries(sunpy.data.sample.LYRA_LEVEL3_TIMESERIES, source='LYRA') # doctest: +REMOTE_DATA\n >>> ts_nolars = remove_lytaf_events_from_timeseries(lyrats, artifacts=[\"LAR\"]) # doctest: +REMOTE_DATA\n\n To also retrieve information on the artifacts during that day:\n >>> ts_nolars, artifact_status = remove_lytaf_events_from_timeseries(\n ... lyrats, artifacts=[\"LAR\"], return_artifacts=True) # doctest: +REMOTE_DATA\n \"\"\"\n # Remove artifacts from time series\n ts_ds = ts.to_dataframe()\n data_columns = ts_ds.columns\n time, channels, artifact_status = _remove_lytaf_events(\n ts_ds.index,\n channels=[np.asanyarray(ts_ds[col]) for col in data_columns],\n artifacts=artifacts,\n return_artifacts=True,\n force_use_local_lytaf=force_use_local_lytaf,\n )\n # Create new copy of timeseries and replace data with\n # artifact-free time series.\n data = pandas.DataFrame(\n index=time, data={col: channels[i] for i, col in enumerate(data_columns)}\n )\n ts_new = TimeSeries(data, ts.meta)\n if return_artifacts:\n return ts_new, artifact_status\n else:\n return ts_new\n\n\ndef _remove_lytaf_events(\n time,\n channels=None,\n artifacts=None,\n return_artifacts=False,\n filecolumns=None,\n force_use_local_lytaf=False,\n):\n \"\"\"\n Removes periods of LYRA artifacts from a time series.\n\n This functions removes periods corresponding to certain artifacts recorded\n in the LYRA annotation file from an array of times given by the time input.\n If a list of arrays of other properties is supplied through the channels\n kwarg, then the relevant values from these arrays are also removed. This\n is done by assuming that each element in each array supplied corresponds to\n the time in the same index in time array. The artifacts to be removed are\n given via the artifacts kwarg. The default is \"all\", meaning that all\n artifacts will be removed. However, a subset of artifacts can be removed\n by supplying a list of strings of the desired artifact types.\n\n Parameters\n ----------\n time : `numpy.ndarray` of `astropy.time.Time`\n Gives the times of the timeseries.\n channels : `list` of `numpy.array` convertible to float64.\n Contains arrays of the irradiances taken at the times in the time\n variable. Each element in the list must have the same number of\n elements as time.\n artifacts : `list` of strings\n Contain the artifact types to be removed. For list of artifact types\n see reference [1]. For example, if user wants to remove only large\n angle rotations, listed at reference [1] as LAR, let artifacts=[\"LAR\"].\n Default=[], i.e. no artifacts will be removed.\n return_artifacts : `bool`\n Set to True to return a numpy recarray containing the start time, end\n time and type of all artifacts removed.\n Default=False\n filecolumns : `list` of strings\n Gives names of columns of any output files produced. Although\n initially set to None above, the default is in fact\n [\"time\", \"channel0\", \"channel1\",...\"channelN\"]\n where N is the number of irradiance arrays in the channels input\n (assuming 0-indexed counting).\n force_use_local_lytaf : `bool`\n Ensures current local version of lytaf files are not replaced by\n up-to-date online versions even if current local lytaf files do not\n cover entire input time range etc.\n Default=False\n\n Returns\n -------\n clean_time : `numpy.ndarray` of `astropy.time.Time`\n time array with artifact periods removed.\n clean_channels : `list` ndarrays/array-likes convertible to float64\n list of irradiance arrays with artifact periods removed.\n artifact_status : `dict`\n List of 4 variables containing information on what artifacts were\n found, removed, etc. from the time series.\n artifact_status[\"lytaf\"] = artifacts found : `numpy.recarray`\n The full LYRA annotation file for the time series time range\n output by get_lytaf_events().\n artifact_status[\"removed\"] = artifacts removed : `numpy.recarray`\n Artifacts which were found and removed from from time series.\n artifact_status[\"not_removed\"] = artifacts found but not removed :\n `numpy.recarray`\n Artifacts which were found but not removed as they were not\n included when user defined artifacts kwarg.\n artifact_status[\"not_found\"] = artifacts not found : `list` of strings\n Artifacts listed to be removed by user when defining artifacts\n kwarg which were not found in time series time range.\n\n References\n ----------\n [1] http://proba2.oma.be/data/TARDIS\n\n Example\n -------\n Sample data for example\n >>> from sunpy.time import parse_time\n >>> from sunkit_instruments.lyra import _remove_lytaf_events\n\n >>> time = parse_time(np.arange('2005-02-01T00:00:00', '2005-02-01T02:00:00',\n ... dtype='datetime64[m]'))\n >>> channel_1 = np.zeros(len(time))+0.4\n >>> channel_2 = np.zeros(len(time))+0.1\n\n Remove LARs (Large Angle Rotations) from time series.\n\n >>> time_clean, channels_clean = _remove_lytaf_events(\n ... time, channels=[channel_1, channel_2], artifacts=['LAR']) # doctest: +SKIP\n \"\"\"\n # Check inputs\n if channels and type(channels) is not list:\n raise TypeError(\n \"channels must be None or a list of numpy arrays \" \"of dtype 'float64'.\"\n )\n if not artifacts:\n raise ValueError(\"User has supplied no artifacts to remove.\")\n if type(artifacts) is str:\n artifacts = [artifacts]\n if not all(isinstance(artifact_type, str) for artifact_type in artifacts):\n raise TypeError(\"All elements in artifacts must in strings.\")\n all_lytaf_event_types = get_lytaf_event_types(print_event_types=False)\n for artifact in artifacts:\n if artifact not in all_lytaf_event_types:\n print(all_lytaf_event_types)\n raise ValueError(f\"{artifact} is not a valid artifact type. See above.\")\n # Define outputs\n clean_time = parse_time(time)\n clean_channels = copy.deepcopy(channels)\n artifacts_not_found = []\n # Get LYTAF file for given time range\n lytaf = get_lytaf_events(\n time[0], time[-1], force_use_local_lytaf=force_use_local_lytaf\n )\n\n # Find events in lytaf which are to be removed from time series.\n artifact_indices = np.empty(0, dtype=\"int64\")\n for artifact_type in artifacts:\n indices = np.where(lytaf[\"event_type\"] == artifact_type)[0]\n # If none of a given type of artifact is found, record this\n # type in artifact_not_found list.\n if len(indices) == 0:\n artifacts_not_found.append(artifact_type)\n else:\n # Else, record the indices of the artifacts of this type\n artifact_indices = np.concatenate((artifact_indices, indices))\n artifact_indices.sort()\n\n # Remove relevant artifacts from timeseries. If none of the\n # artifacts the user wanted removed were found, raise a warning and\n # continue with code.\n if not len(artifact_indices):\n warn(\"None of user supplied artifacts were found.\")\n artifacts_not_found = artifacts\n else:\n # Remove periods corresponding to artifacts from flux and time\n # arrays.\n bad_indices = np.empty(0, dtype=\"int64\")\n all_indices = np.arange(len(time))\n for index in artifact_indices:\n bad_period = np.logical_and(\n time >= lytaf[\"begin_time\"][index].datetime,\n time <= lytaf[\"end_time\"][index].datetime,\n )\n bad_indices = np.append(bad_indices, all_indices[bad_period])\n clean_time = np.delete(clean_time, bad_indices)\n if channels:\n for i, f in enumerate(clean_channels):\n clean_channels[i] = np.delete(f, bad_indices)\n # If return_artifacts kwarg is True, return a list containing\n # information on what artifacts found, removed, etc. See docstring.\n if return_artifacts:\n artifact_status = {\n \"lytaf\": lytaf,\n \"removed\": lytaf[artifact_indices],\n \"not_removed\": np.delete(lytaf, artifact_indices),\n \"not_found\": artifacts_not_found,\n }\n\n # Return values.\n if return_artifacts:\n if not channels:\n return clean_time, artifact_status\n else:\n return clean_time, clean_channels, artifact_status\n else:\n if not channels:\n return clean_time\n else:\n return clean_time, clean_channels\n\n\ndef get_lytaf_events(\n start_time,\n end_time,\n combine_files=(\"lyra\", \"manual\", \"ppt\", \"science\"),\n csvfile=None,\n force_use_local_lytaf=False,\n):\n \"\"\"\n Extracts combined lytaf file for given time range.\n\n Given a time range defined by start_time and end_time, this function\n extracts the segments of each LYRA annotation file and combines them.\n\n Parameters\n ----------\n start_time : `astropy.time.Time` or `str`\n Start time of period for which annotation file is required.\n end_time : `astropy.time.Time` or `str`\n End time of period for which annotation file is required.\n combine_files : `tuple` of strings\n States which LYRA annotation files are to be combined.\n Default is all four, i.e. lyra, manual, ppt, science.\n See Notes section for an explanation of each.\n force_use_local_lytaf : `bool`\n Ensures current local version of lytaf files are not replaced by\n up-to-date online versions even if current local lytaf files do not\n cover entire input time range etc.\n Default=False\n\n Returns\n -------\n lytaf : `numpy.recarray`\n Containing the various parameters stored in the LYTAF files.\n\n Notes\n -----\n There are four LYRA annotation files which mark different types of events\n or artifacts in the data. They are named annotation_suffix.db where\n suffix is a variable equalling either lyra, manual, ppt, or science.\n\n annotation_lyra.db : contains entries regarding possible effects to\n the data due to normal operation of LYRA instrument.\n\n annotation_manual.db : contains entries regarding possible effects\n to the data due to unusual or manually logged events.\n\n annotation_ppt.db : contains entries regarding possible effects to\n the data due to pointing or positioning of PROBA2.\n\n annotation_science.db : contains events in the data scientifically\n interesting, e.g. GOES flares.\n\n References\n ----------\n Further documentation: http://proba2.oma.be/data/TARDIS\n\n Examples\n --------\n Get all events in the LYTAF files for January 2014\n >>> from sunkit_instruments.lyra import get_lytaf_events\n >>> lytaf = get_lytaf_events('2014-01-01', '2014-02-01') # doctest: +SKIP\n \"\"\"\n # Check inputs\n # Parse start_time and end_time\n start_time = parse_time(start_time)\n end_time = parse_time(end_time)\n # Check combine_files contains correct inputs\n if not all(\n suffix in [\"lyra\", \"manual\", \"ppt\", \"science\"] for suffix in combine_files\n ):\n raise ValueError(\n \"Elements in combine_files must be strings equalling \"\n \"'lyra', 'manual', 'ppt', or 'science'.\"\n )\n # Remove any duplicates from combine_files input\n combine_files = list(set(combine_files))\n combine_files.sort()\n # Convert input times to UNIX timestamp format since this is the\n # time format in the annotation files\n start_time_uts = (start_time - Time(\"1970-1-1\")).sec\n end_time_uts = (end_time - Time(\"1970-1-1\")).sec\n\n # Define numpy record array which will hold the information from\n # the annotation file.\n lytaf = np.empty(\n (0,),\n dtype=[\n (\"insertion_time\", object),\n (\"begin_time\", object),\n (\"reference_time\", object),\n (\"end_time\", object),\n (\"event_type\", object),\n (\"event_definition\", object),\n ],\n )\n # Access annotation files\n for suffix in combine_files:\n # Check database files are present\n dbname = f\"annotation_{suffix}.db\"\n lytaf_path = cache.download(urljoin(LYTAF_REMOTE_PATH, dbname))\n # Open SQLITE3 annotation files\n connection = sqlite3.connect(str(lytaf_path))\n # Create cursor to manipulate data in annotation file\n cursor = connection.cursor()\n # Check if lytaf file spans the start and end times defined by\n # user. If not, download newest version.\n # First get start time of first event and end time of last\n # event in lytaf.\n cursor.execute(\n \"select begin_time from event order by begin_time asc \" \"limit 1;\"\n )\n db_first_begin_time = cursor.fetchone()[0]\n db_first_begin_time = datetime.datetime.fromtimestamp(db_first_begin_time)\n cursor.execute(\"select end_time from event order by end_time desc \" \"limit 1;\")\n db_last_end_time = cursor.fetchone()[0]\n db_last_end_time = datetime.datetime.fromtimestamp(db_last_end_time)\n # If lytaf does not include entire input time range...\n if not force_use_local_lytaf:\n if end_time > db_last_end_time or start_time < db_first_begin_time:\n # ...close lytaf file...\n cursor.close()\n connection.close()\n # ...Download latest lytaf file...\n lytaf_path = cache.download(\n urljoin(LYTAF_REMOTE_PATH, dbname), redownload=True\n )\n # ...and open new version of lytaf database.\n connection = sqlite3.connect(str(lytaf_path))\n cursor = connection.cursor()\n # Select and extract the data from event table within file within\n # given time range\n cursor.execute(\n \"select insertion_time, begin_time, reference_time, \"\n \"end_time, eventType_id from event where end_time >= \"\n \"{} and begin_time <= \"\n \"{}\".format(start_time_uts, end_time_uts)\n )\n event_rows = cursor.fetchall()\n # Select and extract the event types from eventType table\n cursor.row_factory = sqlite3.Row\n cursor.execute(\"select * from eventType\")\n eventType_rows = cursor.fetchall()\n eventType_id = []\n eventType_type = []\n eventType_definition = []\n for eventType_row in eventType_rows:\n eventType_id.append(eventType_row[\"id\"])\n eventType_type.append(eventType_row[\"type\"])\n eventType_definition.append(eventType_row[\"definition\"])\n # Enter desired information into the lytaf numpy record array\n for event_row in event_rows:\n id_index = eventType_id.index(event_row[4])\n lytaf = np.append(\n lytaf,\n np.array(\n (\n Time(\n datetime.datetime.utcfromtimestamp(event_row[0]),\n format=\"datetime\",\n ),\n Time(\n datetime.datetime.utcfromtimestamp(event_row[1]),\n format=\"datetime\",\n ),\n Time(\n datetime.datetime.utcfromtimestamp(event_row[2]),\n format=\"datetime\",\n ),\n Time(\n datetime.datetime.utcfromtimestamp(event_row[3]),\n format=\"datetime\",\n ),\n eventType_type[id_index],\n eventType_definition[id_index],\n ),\n dtype=lytaf.dtype,\n ),\n )\n # Close file\n cursor.close()\n connection.close()\n # Sort lytaf in ascending order of begin time\n np.recarray.sort(lytaf, order=\"begin_time\")\n\n # If csvfile kwarg is set, write out lytaf to csv file\n if csvfile:\n # Open and write data to csv file.\n with open(csvfile, \"w\") as openfile:\n csvwriter = csv.writer(openfile, delimiter=\";\")\n # Write header.\n csvwriter.writerow(lytaf.dtype.names)\n # Write data.\n for row in lytaf:\n new_row = []\n new_row.append(row[0].strftime(\"%Y-%m-%dT%H:%M:%S\"))\n new_row.append(row[1].strftime(\"%Y-%m-%dT%H:%M:%S\"))\n new_row.append(row[2].strftime(\"%Y-%m-%dT%H:%M:%S\"))\n new_row.append(row[3].strftime(\"%Y-%m-%dT%H:%M:%S\"))\n new_row.append(row[4])\n new_row.append(row[5])\n csvwriter.writerow(new_row)\n\n return lytaf\n\n\ndef get_lytaf_event_types(print_event_types=True):\n \"\"\"\n Prints the different event types in the each of the LYTAF databases.\n\n Parameters\n ----------\n print_event_types : `bool`\n If True, prints the artifacts in each lytaf database to screen.\n\n Returns\n -------\n all_event_types : `list`\n List of all events types in all lytaf databases.\n \"\"\"\n suffixes = [\"lyra\", \"manual\", \"ppt\", \"science\"]\n all_event_types = []\n # For each database file extract the event types and print them.\n if print_event_types:\n print(\"\\nLYTAF Event Types\\n-----------------\\n\")\n for suffix in suffixes:\n dbname = f\"annotation_{suffix}.db\"\n # Check database file exists, else download it.\n lytaf_path = cache.download(urljoin(LYTAF_REMOTE_PATH, dbname))\n # Open SQLITE3 LYTAF files\n connection = sqlite3.connect(str(lytaf_path))\n # Create cursor to manipulate data in annotation file\n cursor = connection.cursor()\n cursor.execute(\"select type from eventType;\")\n event_types = cursor.fetchall()\n all_event_types.append(event_types)\n if print_event_types:\n print(f\"----------------\\n{suffix} database\\n----------------\")\n for event_type in event_types:\n print(str(event_type[0]))\n print(\" \")\n # Unpack event types in all_event_types into single list\n all_event_types = [\n event_type[0] for event_types in all_event_types for event_type in event_types\n ]\n return all_event_types\n\n\ndef split_series_using_lytaf(timearray, data, lytaf):\n \"\"\"\n Splits LYRA timeseries around locations where \"LARs\" (and other data\n events) are observed.\n\n Parameters\n ----------\n timearray : `numpy.ndarray`\n An array of times understood by `sunpy.time.parse_time`.\n data : `numpy.ndarray`\n An array corresponding to the given time array.\n lytaf : `numpy.recarray`\n Events obtained from querying the LYTAF database using\n `sunkit_instruments.lyra.get_lytaf_events`.\n\n Returns\n -------\n `list` of `dict`\n Each dictionary contains a sub-series corresponding to an interval of\n \"good data\".\n \"\"\"\n n = len(timearray)\n mask = np.ones(n)\n el = len(lytaf)\n\n # make the input time array a list of Time objects\n time_array = [parse_time(tim) for tim in timearray]\n\n # scan through each entry retrieved from the LYTAF database\n for j in range(0, el):\n # want to mark all times with events as bad in the mask, i.e. = 0\n start_dt = lytaf[\"begin_time\"][j]\n end_dt = lytaf[\"end_time\"][j]\n\n # find the start and end indices for each event\n start_ind = np.searchsorted(time_array, start_dt)\n end_ind = np.searchsorted(time_array, end_dt)\n\n # append the mask to mark event as 'bad'\n mask[start_ind:end_ind] = 0\n\n diffmask = np.diff(mask)\n tmp_discontinuity = np.where(diffmask != 0.0)\n # disc contains the indices of mask where there are discontinuities\n disc = tmp_discontinuity[0]\n\n if len(disc) == 0:\n print(\n \"No events found within time series interval. \" \"Returning original series.\"\n )\n return [{\"subtimes\": time_array, \"subdata\": data}]\n\n # -1 in diffmask means went from good data to bad\n # +1 means went from bad data to good\n\n # want to get the data between a +1 and the next -1\n\n # if the first discontinuity is a -1 then the start of the series was good.\n if diffmask[disc[0]] == -1.0:\n # make sure we can always start from disc[0] below\n disc = np.insert(disc, 0, 0)\n\n split_series = []\n\n limit = len(disc)\n # now extract the good data regions and ignore the bad ones\n for h in range(0, limit, 2):\n\n if h == limit - 1:\n # can't index h+1 here. Go to end of series\n subtimes = time_array[disc[h]: -1]\n subdata = data[disc[h]: -1]\n subseries = {\"subtimes\": subtimes, \"subdata\": subdata}\n split_series.append(subseries)\n else:\n subtimes = time_array[disc[h]: disc[h + 1]]\n subdata = data[disc[h]: disc[h + 1]]\n subseries = {\"subtimes\": subtimes, \"subdata\": subdata}\n split_series.append(subseries)\n\n return split_series\n\n\ndef _lytaf_event2string(integers):\n if isinstance(integers, int):\n integers = [integers]\n out = []\n\n for i in integers:\n if i == 1:\n out.append(\"LAR\")\n if i == 2:\n out.append(\"N/A\")\n if i == 3:\n out.append(\"UV occult.\")\n if i == 4:\n out.append(\"Vis. occult.\")\n if i == 5:\n out.append(\"Offpoint\")\n if i == 6:\n out.append(\"SAA\")\n if i == 7:\n out.append(\"Auroral zone\")\n if i == 8:\n out.append(\"Moon in LYRA\")\n if i == 9:\n out.append(\"Moon in SWAP\")\n if i == 10:\n out.append(\"Venus in LYRA\")\n if i == 11:\n out.append(\"Venus in SWAP\")\n\n return out\n\n\n# TODO: Change this function to only need the amount of channels to be passed in.\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef _prep_columns(time, channels=None, filecolumns=None):\n \"\"\"\n Checks and prepares data to be written out to a file.\n\n Parameters\n ----------\n time: {parse_time_types}\n A list or array of times.\n channels: `list`, optional\n A list of the channels found within the data.\n filecolumns: `list`, optional\n A list of strings that are the column names for the file.\n Defaults to `None`, which means that a filenames list is generated\n equal to ``[\"time\", \"channel0\", \"channel1\",..., \"channelN\"]``\n where ``N`` is the number of arrays in the ``channels`` list (if provided).\n\n Returns\n -------\n `numpy.ndarray`, `list`\n The time strings in an array and a list of string headers for each column of data.\n \"\"\"\n time = parse_time(time)\n time.precision = 9\n string_time = np.array(time.isot)\n\n if filecolumns:\n if all(isinstance(column, str) for column in filecolumns) is False:\n raise TypeError(\"All elements in filecolumns must by strings.\")\n # ...and that there are the same number of elements as there\n # are arrays in channels, plus 1 for a time array. Otherwise\n # raise a ValueError.\n if channels:\n ncol = 1 + len(channels)\n else:\n ncol = 1\n if len(filecolumns) != ncol:\n raise ValueError(\n \"Number of elements in filecolumns must be \"\n \"equal to the number of input data arrays, \"\n \"i.e. time + elements in channels.\"\n )\n # If filenames not given, create a list of columns names of the\n # form: [\"time\", \"channel0\", \"channel1\",...,\"channelN\"] where N\n # is the number of arrays in channels (assuming 0-indexed counting).\n else:\n if channels:\n filecolumns = [f\"channel{fluxnum}\" for fluxnum in range(len(channels))]\n filecolumns.insert(0, \"time\")\n else:\n filecolumns = [\"time\"]\n\n return string_time, filecolumns\n" ]
[ [ "numpy.logical_and", "numpy.ones", "numpy.concatenate", "numpy.delete", "numpy.append", "numpy.diff", "numpy.insert", "numpy.searchsorted", "numpy.asanyarray", "numpy.array", "numpy.where", "numpy.recarray.sort", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wolframalpha/scorecardpy
[ "3642bebd208da52623a99356d310289dbd36dd35" ]
[ "scorecardpy/var_filter.py" ]
[ "# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport warnings\nimport time\nfrom .condition_fun import *\nfrom .info_value import *\n\n\ndef var_filter(dt, y, x=None, iv_limit=0.02, missing_limit=0.95, \n identical_limit=0.95, var_rm=None, var_kp=None, \n return_rm_reason=False, positive='bad|1'):\n '''\n Variable Filter\n ------\n This function filter variables base on specified conditions, such as \n information value, missing rate, identical value rate.\n \n Params\n ------\n dt: A data frame with both x (predictor/feature) and y \n (response/label) variables.\n y: Name of y variable.\n x: Name of x variables. Default is NULL. If x is NULL, then all \n variables except y are counted as x variables.\n iv_limit: The information value of kept variables should>=iv_limit. \n The default is 0.02.\n missing_limit: The missing rate of kept variables should<=missing_limit. \n The default is 0.95.\n identical_limit: The identical value rate (excluding NAs) of kept \n variables should <= identical_limit. The default is 0.95.\n var_rm: Name of force removed variables, default is NULL.\n var_kp: Name of force kept variables, default is NULL.\n return_rm_reason: Logical, default is FALSE.\n positive: Value of positive class, default is \"bad|1\".\n \n Returns\n ------\n DataFrame\n A data.table with y and selected x variables\n Dict(if return_rm_reason == TRUE)\n A DataFrame with y and selected x variables and \n a DataFrame with the reason of removed x variable.\n \n Examples\n ------\n import scorecardpy as sc\n \n # load data\n dat = sc.germancredit()\n \n # variable filter\n dt_sel = sc.var_filter(dat, y = \"creditability\")\n '''\n # start time\n start_time = time.time()\n print('[INFO] filtering variables ...')\n \n dt = dt.copy(deep=True)\n if isinstance(y, str):\n y = [y]\n if isinstance(x, str) and x is not None:\n x = [x]\n if x is not None: \n dt = dt[y+x]\n # remove date/time col\n dt = rmcol_datetime_unique1(dt)\n # replace \"\" by NA\n dt = rep_blank_na(dt)\n # check y\n dt = check_y(dt, y, positive)\n # x variable names\n x = x_variable(dt,y,x)\n \n # force removed variables\n if var_rm is not None: \n if isinstance(var_rm, str):\n var_rm = [var_rm]\n x = list(set(x).difference(set(var_rm)))\n # check force kept variables\n if var_kp is not None:\n if isinstance(var_kp, str):\n var_kp = [var_kp]\n var_kp2 = list(set(var_kp) & set(x))\n len_diff_var_kp = len(var_kp) - len(var_kp2)\n if len_diff_var_kp > 0:\n warnings.warn(\"Incorrect inputs; there are {} var_kp variables are not exist in input data, which are removed from var_kp. \\n {}\".format(len_diff_var_kp, list(set(var_kp)-set(var_kp2))) )\n var_kp = var_kp2 if len(var_kp2)>0 else None\n \n # -iv\n iv_list = iv(dt, y, x, order=False)\n # -na percentage\n nan_rate = lambda a: a[a.isnull()].size/a.size\n na_perc = dt[x].apply(nan_rate).reset_index(name='missing_rate').rename(columns={'index':'variable'})\n # -identical percentage\n idt_rate = lambda a: a.value_counts().max() / a.size\n identical_perc = dt[x].apply(idt_rate).reset_index(name='identical_rate').rename(columns={'index':'variable'})\n \n # dataframe iv na idt\n dt_var_selector = iv_list.merge(na_perc,on='variable').merge(identical_perc,on='variable')\n # remove na_perc>95 | ele_perc>0.95 | iv<0.02\n # variable datatable selected\n dt_var_sel = dt_var_selector.query('(info_value >= {}) & (missing_rate <= {}) & (identical_rate <= {})'.format(iv_limit,missing_limit,identical_limit))\n \n # add kept variable\n x_selected = dt_var_sel.variable.tolist()\n if var_kp is not None: \n x_selected = np.unique(x_selected+var_kp).tolist()\n # data kept\n dt_kp = dt[x_selected+y]\n \n # runingtime\n runingtime = time.time() - start_time\n if (runingtime >= 10):\n # print(time.strftime(\"%H:%M:%S\", time.gmtime(runingtime)))\n print('Variable filtering on {} rows and {} columns in {} \\n{} variables are removed'.format(dt.shape[0], dt.shape[1], time.strftime(\"%H:%M:%S\", time.gmtime(runingtime)), dt.shape[1]-len(x_selected+y)))\n # return remove reason\n if return_rm_reason:\n dt_var_rm = dt_var_selector.query('(info_value < {}) | (missing_rate > {}) | (identical_rate > {})'.format(iv_limit,missing_limit,identical_limit)) \\\n .assign(\n info_value = lambda x: ['info_value<{}'.format(iv_limit) if i else np.nan for i in (x.info_value < iv_limit)], \n missing_rate = lambda x: ['missing_rate>{}'.format(missing_limit) if i else np.nan for i in (x.missing_rate > missing_limit)],\n identical_rate = lambda x: ['identical_rate>{}'.format(identical_limit) if i else np.nan for i in (x.identical_rate > identical_limit)]\n )\n dt_rm_reason = pd.melt(dt_var_rm, id_vars=['variable'], var_name='iv_mr_ir').dropna()\\\n .groupby('variable').apply(lambda x: ', '.join(x.value)).reset_index(name='rm_reason')\n \n if var_rm is not None: \n dt_rm_reason = pd.concat([\n dt_rm_reason, \n pd.DataFrame({'variable':var_rm,'rm_reason':\"force remove\"}, columns=['variable', 'rm_reason'])\n ])\n if var_kp is not None:\n dt_rm_reason = dt_rm_reason.query('variable not in {}'.format(var_kp))\n \n dt_rm_reason = pd.merge(dt_rm_reason, dt_var_selector, how='outer', on = 'variable')\n return {'dt': dt_kp, 'rm':dt_rm_reason}\n else:\n return dt_kp\n\n\n" ]
[ [ "pandas.merge", "pandas.melt", "pandas.DataFrame", "numpy.unique" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
jerryzh168/ClassyVision-1
[ "e8704ecaa59a15dbb2f4b0724e85d6e5cb2f704e", "e8704ecaa59a15dbb2f4b0724e85d6e5cb2f704e" ]
[ "classy_vision/hooks/exponential_moving_average_model_hook.py", "classy_vision/models/mlp.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 itertools\nimport logging\nfrom typing import Any, Dict, Iterable, Tuple\n\nimport torch\nimport torch.nn as nn\nfrom classy_vision.generic.util import get_torch_version\nfrom classy_vision.hooks import register_hook\nfrom classy_vision.hooks.classy_hook import ClassyHook\n\n\n@register_hook(\"ema_model_weights\")\nclass ExponentialMovingAverageModelHook(ClassyHook):\n \"\"\"\n Hook which keeps a track of the exponential moving average (EMA) of the model's\n parameters and applies the EMA params to the model during the test phases.\n\n Saving the state in cpu will save gpu memory, but will make training slower since\n the model parameters will need to be moved to cpu before the averaging.\n\n Note:\n This hooks stores two additional copies of the model's parameters, which will\n increase memory usage significantly.\n \"\"\"\n\n on_end = ClassyHook._noop\n\n def __init__(\n self, decay: float, consider_bn_buffers: bool = True, device: str = \"gpu\"\n ) -> None:\n \"\"\"The constructor method of ExponentialMovingAverageModelHook.\n\n Args:\n decay: EMA decay factor, should be in [0, 1]. A decay of 0 corresponds to\n always using the latest value (no EMA) and a decay of 1 corresponds to\n not updating weights after initialization.\n consider_bn_buffers: Whether to apply EMA to batch norm buffers\n device: Device to store the model state.\n \"\"\"\n super().__init__()\n assert 0 <= decay <= 1, \"Decay should be between 0 and 1\"\n assert device in [\"cpu\", \"gpu\"], \"Device should be one of cpu or gpu\"\n self.decay: int = decay\n self.consider_bn_buffers = consider_bn_buffers\n self.device = \"cuda\" if device == \"gpu\" else \"cpu\"\n self.state.model_state = {}\n self.state.ema_model_state = {}\n self.ema_model_state_list = []\n self.param_list = []\n logging.info(\n f\"{self.__class__.__name__} initialized with a decay of \"\n f\"{decay} on device {device}\"\n )\n\n def get_model_state_iterator(self, model: nn.Module) -> Iterable[Tuple[str, Any]]:\n \"\"\"Get an iterator over the model state to apply EMA to.\"\"\"\n iterable = model.named_parameters()\n if self.consider_bn_buffers:\n # also add batch norm buffers to the list of state params to iterate over\n buffers_iterable = (\n (f\"{module_name}_buffer_{name}\", buffer)\n for module_name, module in model.named_modules()\n for name, buffer in module.named_buffers()\n if isinstance(module, nn.modules.batchnorm._BatchNorm)\n )\n iterable = itertools.chain(iterable, buffers_iterable)\n return iterable\n\n def _save_current_model_state(self, model: nn.Module, model_state: Dict[str, Any]):\n \"\"\"Copy the model's state to the provided dict.\"\"\"\n for name, param in self.get_model_state_iterator(model):\n model_state[name] = param.detach().clone().to(device=self.device)\n\n def on_start(self, task) -> None:\n if self.state.model_state:\n # loaded state from checkpoint, do not re-initialize, only move the state\n # to the right device\n for name in self.state.model_state:\n self.state.model_state[name] = self.state.model_state[name].to(\n device=self.device\n )\n self.state.ema_model_state[name] = self.state.ema_model_state[name].to(\n device=self.device\n )\n else:\n self._save_current_model_state(task.base_model, self.state.model_state)\n self._save_current_model_state(task.base_model, self.state.ema_model_state)\n\n if self.use_optimization(task):\n non_fp_states = []\n for name in self.state.ema_model_state:\n if self.state.ema_model_state[name].dtype not in [\n torch.float32,\n torch.float16,\n ]:\n non_fp_states.append(name)\n if non_fp_states:\n logging.warning(\n f\"In {self.__class__.__name__}, {non_fp_states} are excluded in EMA hook\"\n f\"because the dtype is not fp32 or fp16.\"\n )\n\n def on_phase_start(self, task) -> None:\n # restore the right state depending on the phase type\n use_ema = (\n (not task.train and task.ema) if hasattr(task, \"ema\") else not task.train\n )\n self.set_model_state(task, use_ema=use_ema)\n if self.use_optimization(task):\n self.param_list = []\n self.ema_model_state_list = []\n for name, param in self.get_model_state_iterator(task.base_model):\n if param.dtype in [torch.float32, torch.float16]:\n self.param_list.append(param)\n self.ema_model_state_list.append(self.state.ema_model_state[name])\n else:\n logging.warning(\n \"ExponentialMovingAverageModelHook has better performance since PyTorch version 1.7 \"\n \"and the ema state is on the same device as the model params\"\n )\n\n def on_phase_end(self, task) -> None:\n if task.train:\n # save the current model state since this will be overwritten by the ema\n # state in the test phase\n self._save_current_model_state(task.base_model, self.state.model_state)\n\n def on_step(self, task) -> None:\n if not task.train:\n return\n\n with torch.no_grad():\n if self.use_optimization(task):\n torch._foreach_mul_(self.ema_model_state_list, self.decay)\n torch._foreach_add_(\n self.ema_model_state_list, self.param_list, alpha=(1 - self.decay)\n )\n else:\n for name, param in self.get_model_state_iterator(task.base_model):\n self.state.ema_model_state[\n name\n ] = self.decay * self.state.ema_model_state[name] + (\n 1 - self.decay\n ) * param.to(\n device=self.device\n )\n\n def set_model_state(self, task, use_ema: bool) -> None:\n \"\"\"\n Depending on use_ema, set the appropriate state for the model.\n \"\"\"\n model_state = self.state.ema_model_state if use_ema else self.state.model_state\n with torch.no_grad():\n for name, param in self.get_model_state_iterator(task.base_model):\n param.copy_(model_state[name])\n\n def use_optimization(self, task):\n # we can only use the optimization if we are on PyTorch >= 1.7 and the EMA state\n # is on the same device as the model\n return get_torch_version() >= [1, 7] and task.use_gpu == (self.device == \"cuda\")\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"MLP model.\"\"\"\n\nfrom typing import Any, Dict\n\nimport torch.nn as nn\n\nfrom . import register_model\nfrom .classy_model import ClassyModel\n\n\n@register_model(\"mlp\")\nclass MLP(ClassyModel):\n \"\"\"MLP model using ReLU. Useful for testing on CPUs.\"\"\"\n\n def __init__(\n self,\n input_dim,\n output_dim,\n hidden_dims,\n dropout,\n first_dropout,\n use_batchnorm,\n first_batchnorm,\n ):\n super().__init__()\n\n layers = []\n # If first_batchnorm is set, must be using batchnorm\n assert not first_batchnorm or use_batchnorm\n\n self._num_inputs = input_dim\n self._num_classes = output_dim\n self._model_depth = len(hidden_dims) + 1\n\n if dropout > 0 and first_dropout:\n layers.append(nn.Dropout(p=dropout))\n\n if use_batchnorm and first_batchnorm:\n layers.append(nn.BatchNorm1d(input_dim))\n\n for dim in hidden_dims:\n layers.append(nn.Linear(input_dim, dim))\n if use_batchnorm:\n layers.append(nn.BatchNorm1d(dim))\n if dropout > 0:\n layers.append(nn.Dropout(p=dropout))\n layers.append(nn.ReLU(inplace=True))\n input_dim = dim\n\n layers.append(nn.Linear(input_dim, output_dim))\n self.mlp = nn.Sequential(*layers)\n\n @classmethod\n def from_config(cls, config: Dict[str, Any]) -> \"MLP\":\n \"\"\"Instantiates a MLP from a configuration.\n\n Args:\n config: A configuration for a MLP.\n See :func:`__init__` for parameters expected in the config.\n\n Returns:\n A MLP instance.\n \"\"\"\n assert (key in config for key in [\"input_dim\", \"output_dim\", \"hidden_dims\"])\n\n output_dim = config[\"output_dim\"]\n return cls(\n input_dim=config[\"input_dim\"],\n output_dim=output_dim,\n hidden_dims=config[\"hidden_dims\"],\n dropout=config.get(\"dropout\", 0),\n first_dropout=config.get(\"first_dropout\", False),\n use_batchnorm=config.get(\"use_batchnorm\", False),\n first_batchnorm=config.get(\"first_batchnorm\", False),\n )\n\n def forward(self, x):\n batchsize_per_replica = x.shape[0]\n out = x.view(batchsize_per_replica, -1)\n out = self.mlp(out)\n return out\n" ]
[ [ "torch._foreach_add_", "torch._foreach_mul_", "torch.no_grad" ], [ "torch.nn.Sequential", "torch.nn.Dropout", "torch.nn.BatchNorm1d", "torch.nn.Linear", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hl2500/deepchem
[ "9d0fc5554b286117ae08b21b3f15877b06a1009e" ]
[ "deepchem/data/tests/test_datasets.py" ]
[ "\"\"\"\nTests for dataset creation\n\"\"\"\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\n__author__ = \"Bharath Ramsundar\"\n__copyright__ = \"Copyright 2016, Stanford University\"\n__license__ = \"MIT\"\n\nimport random\nimport math\nimport unittest\nimport tempfile\nimport os\nimport shutil\nimport numpy as np\nimport deepchem as dc\nimport tensorflow as tf\nfrom tensorflow.python.framework import test_util\n\n\nclass TestDatasets(test_util.TensorFlowTestCase):\n \"\"\"\n Test basic top-level API for dataset objects.\n \"\"\"\n\n def test_sparsify_and_densify(self):\n \"\"\"Test that sparsify and densify work as inverses.\"\"\"\n # Test on identity matrix\n num_samples = 10\n num_features = num_samples\n X = np.eye(num_samples)\n X_sparse = dc.data.sparsify_features(X)\n X_reconstructed = dc.data.densify_features(X_sparse, num_features)\n np.testing.assert_array_equal(X, X_reconstructed)\n\n # Generate random sparse features dataset\n np.random.seed(123)\n p = .05\n X = np.random.binomial(1, p, size=(num_samples, num_features))\n X_sparse = dc.data.sparsify_features(X)\n X_reconstructed = dc.data.densify_features(X_sparse, num_features)\n np.testing.assert_array_equal(X, X_reconstructed)\n\n # Test edge case with array of all zeros\n X = np.zeros((num_samples, num_features))\n X_sparse = dc.data.sparsify_features(X)\n X_reconstructed = dc.data.densify_features(X_sparse, num_features)\n np.testing.assert_array_equal(X, X_reconstructed)\n\n def test_pad_features(self):\n \"\"\"Test that pad_features pads features correctly.\"\"\"\n batch_size = 100\n num_features = 10\n num_tasks = 5\n\n # Test cases where n_samples < 2*n_samples < batch_size\n n_samples = 29\n X_b = np.zeros((n_samples, num_features))\n\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n # Test cases where n_samples < batch_size\n n_samples = 79\n X_b = np.zeros((n_samples, num_features))\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n # Test case where n_samples == batch_size\n n_samples = 100\n X_b = np.zeros((n_samples, num_features))\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n # Test case for object featurization.\n n_samples = 2\n X_b = np.array([{\"a\": 1}, {\"b\": 2}])\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n # Test case for more complicated object featurization\n n_samples = 2\n X_b = np.array([(1, {\"a\": 1}), (2, {\"b\": 2})])\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n # Test case with multidimensional data\n n_samples = 50\n num_atoms = 15\n d = 3\n X_b = np.zeros((n_samples, num_atoms, d))\n X_out = dc.data.pad_features(batch_size, X_b)\n assert len(X_out) == batch_size\n\n def test_pad_batches(self):\n \"\"\"Test that pad_batch pads batches correctly.\"\"\"\n batch_size = 100\n num_features = 10\n num_tasks = 5\n\n # Test cases where n_samples < 2*n_samples < batch_size\n n_samples = 29\n X_b = np.zeros((n_samples, num_features))\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n # Test cases where n_samples < batch_size\n n_samples = 79\n X_b = np.zeros((n_samples, num_features))\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n # Test case where n_samples == batch_size\n n_samples = 100\n X_b = np.zeros((n_samples, num_features))\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n # Test case for object featurization.\n n_samples = 2\n X_b = np.array([{\"a\": 1}, {\"b\": 2}])\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n # Test case for more complicated object featurization\n n_samples = 2\n X_b = np.array([(1, {\"a\": 1}), (2, {\"b\": 2})])\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n # Test case with multidimensional data\n n_samples = 50\n num_atoms = 15\n d = 3\n X_b = np.zeros((n_samples, num_atoms, d))\n y_b = np.zeros((n_samples, num_tasks))\n w_b = np.zeros((n_samples, num_tasks))\n ids_b = np.zeros((n_samples,))\n\n X_out, y_out, w_out, ids_out = dc.data.pad_batch(batch_size, X_b, y_b, w_b,\n ids_b)\n assert len(X_out) == len(y_out) == len(w_out) == len(ids_out) == batch_size\n\n def test_get_task_names(self):\n \"\"\"Test that get_task_names returns correct task_names\"\"\"\n solubility_dataset = dc.data.tests.load_solubility_data()\n assert solubility_dataset.get_task_names() == [\"log-solubility\"]\n\n multitask_dataset = dc.data.tests.load_multitask_data()\n assert sorted(multitask_dataset.get_task_names()) == sorted([\n \"task0\", \"task1\", \"task2\", \"task3\", \"task4\", \"task5\", \"task6\", \"task7\",\n \"task8\", \"task9\", \"task10\", \"task11\", \"task12\", \"task13\", \"task14\",\n \"task15\", \"task16\"\n ])\n\n def test_get_data_shape(self):\n \"\"\"Test that get_data_shape returns currect data shape\"\"\"\n solubility_dataset = dc.data.tests.load_solubility_data()\n assert solubility_dataset.get_data_shape() == (1024,)\n\n multitask_dataset = dc.data.tests.load_multitask_data()\n assert multitask_dataset.get_data_shape() == (1024,)\n\n def test_len(self):\n \"\"\"Test that len(dataset) works.\"\"\"\n solubility_dataset = dc.data.tests.load_solubility_data()\n assert len(solubility_dataset) == 10\n\n def test_reshard(self):\n \"\"\"Test that resharding the dataset works.\"\"\"\n solubility_dataset = dc.data.tests.load_solubility_data()\n X, y, w, ids = (solubility_dataset.X, solubility_dataset.y,\n solubility_dataset.w, solubility_dataset.ids)\n assert solubility_dataset.get_number_shards() == 1\n solubility_dataset.reshard(shard_size=1)\n assert solubility_dataset.get_shard_size() == 1\n X_r, y_r, w_r, ids_r = (solubility_dataset.X, solubility_dataset.y,\n solubility_dataset.w, solubility_dataset.ids)\n assert solubility_dataset.get_number_shards() == 10\n solubility_dataset.reshard(shard_size=10)\n assert solubility_dataset.get_shard_size() == 10\n X_rr, y_rr, w_rr, ids_rr = (solubility_dataset.X, solubility_dataset.y,\n solubility_dataset.w, solubility_dataset.ids)\n\n # Test first resharding worked\n np.testing.assert_array_equal(X, X_r)\n np.testing.assert_array_equal(y, y_r)\n np.testing.assert_array_equal(w, w_r)\n np.testing.assert_array_equal(ids, ids_r)\n\n # Test second resharding worked\n np.testing.assert_array_equal(X, X_rr)\n np.testing.assert_array_equal(y, y_rr)\n np.testing.assert_array_equal(w, w_rr)\n np.testing.assert_array_equal(ids, ids_rr)\n\n def test_select(self):\n \"\"\"Test that dataset select works.\"\"\"\n num_datapoints = 10\n num_features = 10\n num_tasks = 1\n X = np.random.rand(num_datapoints, num_features)\n y = np.random.randint(2, size=(num_datapoints, num_tasks))\n w = np.ones((num_datapoints, num_tasks))\n ids = np.array([\"id\"] * num_datapoints)\n dataset = dc.data.DiskDataset.from_numpy(X, y, w, ids)\n\n indices = [0, 4, 5, 8]\n select_dataset = dataset.select(indices)\n X_sel, y_sel, w_sel, ids_sel = (select_dataset.X, select_dataset.y,\n select_dataset.w, select_dataset.ids)\n np.testing.assert_array_equal(X[indices], X_sel)\n np.testing.assert_array_equal(y[indices], y_sel)\n np.testing.assert_array_equal(w[indices], w_sel)\n np.testing.assert_array_equal(ids[indices], ids_sel)\n\n def test_complete_shuffle(self):\n shard_sizes = [1, 2, 3, 4, 5]\n batch_size = 10\n\n all_Xs, all_ys, all_ws, all_ids = [], [], [], []\n\n def shard_generator():\n for sz in shard_sizes:\n X_b = np.random.rand(sz, 1)\n y_b = np.random.rand(sz, 1)\n w_b = np.random.rand(sz, 1)\n ids_b = np.random.rand(sz)\n\n all_Xs.append(X_b)\n all_ys.append(y_b)\n all_ws.append(w_b)\n all_ids.append(ids_b)\n\n yield X_b, y_b, w_b, ids_b\n\n dataset = dc.data.DiskDataset.create_dataset(shard_generator())\n\n res = dataset.complete_shuffle()\n\n # approx 1/15! chance of equality\n np.testing.assert_equal(np.any(np.not_equal(dataset.X, res.X)), True)\n np.testing.assert_equal(np.any(np.not_equal(dataset.y, res.w)), True)\n np.testing.assert_equal(np.any(np.not_equal(dataset.w, res.y)), True)\n np.testing.assert_equal(np.any(np.not_equal(dataset.ids, res.ids)), True)\n\n np.testing.assert_array_equal(\n np.sort(dataset.X, axis=0), np.sort(res.X, axis=0))\n np.testing.assert_array_equal(\n np.sort(dataset.y, axis=0), np.sort(res.y, axis=0))\n np.testing.assert_array_equal(\n np.sort(dataset.w, axis=0), np.sort(res.w, axis=0))\n np.testing.assert_array_equal(np.sort(dataset.ids), np.sort(res.ids))\n\n def test_get_shape(self):\n \"\"\"Test that get_shape works.\"\"\"\n num_datapoints = 100\n num_features = 10\n num_tasks = 10\n # Generate data\n X = np.random.rand(num_datapoints, num_features)\n y = np.random.randint(2, size=(num_datapoints, num_tasks))\n w = np.random.randint(2, size=(num_datapoints, num_tasks))\n ids = np.array([\"id\"] * num_datapoints)\n\n dataset = dc.data.NumpyDataset(X, y, w, ids)\n\n X_shape, y_shape, w_shape, ids_shape = dataset.get_shape()\n assert X_shape == X.shape\n assert y_shape == y.shape\n assert w_shape == w.shape\n assert ids_shape == ids.shape\n\n def test_iterbatches(self):\n \"\"\"Test that iterating over batches of data works.\"\"\"\n solubility_dataset = dc.data.tests.load_solubility_data()\n batch_size = 2\n data_shape = solubility_dataset.get_data_shape()\n tasks = solubility_dataset.get_task_names()\n for (X_b, y_b, w_b, ids_b) in solubility_dataset.iterbatches(batch_size):\n assert X_b.shape == (batch_size,) + data_shape\n assert y_b.shape == (batch_size,) + (len(tasks),)\n assert w_b.shape == (batch_size,) + (len(tasks),)\n assert ids_b.shape == (batch_size,)\n\n def test_itersamples_numpy(self):\n \"\"\"Test that iterating over samples in a NumpyDataset works.\"\"\"\n num_datapoints = 100\n num_features = 10\n num_tasks = 10\n # Generate data\n X = np.random.rand(num_datapoints, num_features)\n y = np.random.randint(2, size=(num_datapoints, num_tasks))\n w = np.random.randint(2, size=(num_datapoints, num_tasks))\n ids = np.array([\"id\"] * num_datapoints)\n dataset = dc.data.NumpyDataset(X, y, w, ids)\n for i, (sx, sy, sw, sid) in enumerate(dataset.itersamples()):\n np.testing.assert_array_equal(sx, X[i])\n np.testing.assert_array_equal(sy, y[i])\n np.testing.assert_array_equal(sw, w[i])\n np.testing.assert_array_equal(sid, ids[i])\n\n def test_itersamples_disk(self):\n \"\"\"Test that iterating over samples in a DiskDataset works.\"\"\"\n solubility_dataset = dc.data.tests.load_solubility_data()\n X = solubility_dataset.X\n y = solubility_dataset.y\n w = solubility_dataset.w\n ids = solubility_dataset.ids\n for i, (sx, sy, sw, sid) in enumerate(solubility_dataset.itersamples()):\n np.testing.assert_array_equal(sx, X[i])\n np.testing.assert_array_equal(sy, y[i])\n np.testing.assert_array_equal(sw, w[i])\n np.testing.assert_array_equal(sid, ids[i])\n\n def test_transform_numpy(self):\n \"\"\"Test that the transform() method works for NumpyDatasets.\"\"\"\n num_datapoints = 100\n num_features = 10\n num_tasks = 10\n\n # Generate data\n X = np.random.rand(num_datapoints, num_features)\n y = np.random.randint(2, size=(num_datapoints, num_tasks))\n w = np.random.randint(2, size=(num_datapoints, num_tasks))\n ids = np.array([\"id\"] * num_datapoints)\n dataset = dc.data.NumpyDataset(X, y, w, ids)\n\n # Transform it\n\n def fn(x, y, w):\n return (2 * x, 1.5 * y, w)\n\n transformed = dataset.transform(fn)\n np.testing.assert_array_equal(X, dataset.X)\n np.testing.assert_array_equal(y, dataset.y)\n np.testing.assert_array_equal(w, dataset.w)\n np.testing.assert_array_equal(ids, dataset.ids)\n np.testing.assert_array_equal(2 * X, transformed.X)\n np.testing.assert_array_equal(1.5 * y, transformed.y)\n np.testing.assert_array_equal(w, transformed.w)\n np.testing.assert_array_equal(ids, transformed.ids)\n\n def test_transform_disk(self):\n \"\"\"Test that the transform() method works for DiskDatasets.\"\"\"\n dataset = dc.data.tests.load_solubility_data()\n X = dataset.X\n y = dataset.y\n w = dataset.w\n ids = dataset.ids\n\n # Transform it\n def fn(x, y, w):\n return (2 * x, 1.5 * y, w)\n\n transformed = dataset.transform(fn)\n np.testing.assert_array_equal(X, dataset.X)\n np.testing.assert_array_equal(y, dataset.y)\n np.testing.assert_array_equal(w, dataset.w)\n np.testing.assert_array_equal(ids, dataset.ids)\n np.testing.assert_array_equal(2 * X, transformed.X)\n np.testing.assert_array_equal(1.5 * y, transformed.y)\n np.testing.assert_array_equal(w, transformed.w)\n np.testing.assert_array_equal(ids, transformed.ids)\n\n def test_to_numpy(self):\n \"\"\"Test that transformation to numpy arrays is sensible.\"\"\"\n solubility_dataset = dc.data.tests.load_solubility_data()\n data_shape = solubility_dataset.get_data_shape()\n tasks = solubility_dataset.get_task_names()\n X, y, w, ids = (solubility_dataset.X, solubility_dataset.y,\n solubility_dataset.w, solubility_dataset.ids)\n N_samples = len(solubility_dataset)\n N_tasks = len(tasks)\n\n assert X.shape == (N_samples,) + data_shape\n assert y.shape == (N_samples, N_tasks)\n assert w.shape == (N_samples, N_tasks)\n assert ids.shape == (N_samples,)\n\n def test_consistent_ordering(self):\n \"\"\"Test that ordering of labels is consistent over time.\"\"\"\n solubility_dataset = dc.data.tests.load_solubility_data()\n\n ids1 = solubility_dataset.ids\n ids2 = solubility_dataset.ids\n\n assert np.array_equal(ids1, ids2)\n\n def test_get_statistics(self):\n \"\"\"Test statistics computation of this dataset.\"\"\"\n solubility_dataset = dc.data.tests.load_solubility_data()\n X, y, _, _ = (solubility_dataset.X, solubility_dataset.y,\n solubility_dataset.w, solubility_dataset.ids)\n X_means, y_means = np.mean(X, axis=0), np.mean(y, axis=0)\n X_stds, y_stds = np.std(X, axis=0), np.std(y, axis=0)\n comp_X_means, comp_X_stds, comp_y_means, comp_y_stds = \\\n solubility_dataset.get_statistics()\n np.testing.assert_allclose(comp_X_means, X_means)\n np.testing.assert_allclose(comp_y_means, y_means)\n np.testing.assert_allclose(comp_X_stds, X_stds)\n np.testing.assert_allclose(comp_y_stds, y_stds)\n\n def test_disk_iterate_batch_size(self):\n solubility_dataset = dc.data.tests.load_solubility_data()\n X, y, _, _ = (solubility_dataset.X, solubility_dataset.y,\n solubility_dataset.w, solubility_dataset.ids)\n batch_sizes = []\n for X, y, _, _ in solubility_dataset.iterbatches(\n 3, pad_batches=False, deterministic=True):\n batch_sizes.append(len(X))\n self.assertEqual([3, 3, 3, 1], batch_sizes)\n\n def test_disk_pad_batches(self):\n shard_sizes = [21, 11, 41, 21, 51]\n batch_size = 10\n\n all_Xs, all_ys, all_ws, all_ids = [], [], [], []\n\n def shard_generator():\n for sz in shard_sizes:\n X_b = np.random.rand(sz, 1)\n y_b = np.random.rand(sz, 1)\n w_b = np.random.rand(sz, 1)\n ids_b = np.random.rand(sz)\n\n all_Xs.append(X_b)\n all_ys.append(y_b)\n all_ws.append(w_b)\n all_ids.append(ids_b)\n\n yield X_b, y_b, w_b, ids_b\n\n dataset = dc.data.DiskDataset.create_dataset(shard_generator())\n\n all_Xs = np.concatenate(all_Xs, axis=0)\n all_ys = np.concatenate(all_ys, axis=0)\n all_ws = np.concatenate(all_ws, axis=0)\n all_ids = np.concatenate(all_ids, axis=0)\n\n test_Xs, test_ys, test_ws, test_ids = [], [], [], []\n for bidx, (a, b, c, d) in enumerate(\n dataset.iterbatches(\n batch_size=batch_size, pad_batches=True, deterministic=True)):\n\n test_Xs.append(a)\n test_ys.append(b)\n test_ws.append(c)\n test_ids.append(d)\n\n test_Xs = np.concatenate(test_Xs, axis=0)\n test_ys = np.concatenate(test_ys, axis=0)\n test_ws = np.concatenate(test_ws, axis=0)\n test_ids = np.concatenate(test_ids, axis=0)\n\n total_size = sum(shard_sizes)\n\n assert bidx == math.ceil(total_size / batch_size) - 1\n\n expected_batches = math.ceil(total_size / batch_size) * batch_size\n\n assert len(test_Xs) == expected_batches\n assert len(test_ys) == expected_batches\n assert len(test_ws) == expected_batches\n assert len(test_ids) == expected_batches\n\n np.testing.assert_array_equal(all_Xs, test_Xs[:total_size, :])\n np.testing.assert_array_equal(all_ys, test_ys[:total_size, :])\n np.testing.assert_array_equal(all_ws, test_ws[:total_size, :])\n np.testing.assert_array_equal(all_ids, test_ids[:total_size])\n\n def test_disk_iterate_y_w_None(self):\n shard_sizes = [21, 11, 41, 21, 51]\n batch_size = 10\n\n all_Xs, all_ys, all_ws, all_ids = [], [], [], []\n\n def shard_generator():\n for sz in shard_sizes:\n X_b = np.random.rand(sz, 1)\n ids_b = np.random.rand(sz)\n\n all_Xs.append(X_b)\n all_ids.append(ids_b)\n\n yield X_b, None, None, ids_b\n\n dataset = dc.data.DiskDataset.create_dataset(shard_generator())\n\n all_Xs = np.concatenate(all_Xs, axis=0)\n all_ids = np.concatenate(all_ids, axis=0)\n\n test_Xs, test_ids = [], []\n for bidx, (a, _, _, d) in enumerate(\n dataset.iterbatches(\n batch_size=batch_size, pad_batches=True, deterministic=True)):\n\n test_Xs.append(a)\n test_ids.append(d)\n\n test_Xs = np.concatenate(test_Xs, axis=0)\n test_ids = np.concatenate(test_ids, axis=0)\n\n total_size = sum(shard_sizes)\n\n assert bidx == math.ceil(total_size / batch_size) - 1\n\n expected_batches = math.ceil(total_size / batch_size) * batch_size\n\n assert len(test_Xs) == expected_batches\n assert len(test_ids) == expected_batches\n\n np.testing.assert_array_equal(all_Xs, test_Xs[:total_size, :])\n np.testing.assert_array_equal(all_ids, test_ids[:total_size])\n\n def test_disk_iterate_batch(self):\n\n all_batch_sizes = [None, 32, 17, 11]\n all_shard_sizes = [[7, 3, 12, 4, 5], [1, 1, 1, 1, 1], [31, 31, 31, 31, 31],\n [21, 11, 41, 21, 51]]\n\n for idx in range(25):\n shard_length = random.randint(1, 32)\n shard_sizes = []\n for _ in range(shard_length):\n shard_sizes.append(random.randint(1, 128))\n all_shard_sizes.append(shard_sizes)\n if idx == 0:\n # special case to test\n all_batch_sizes.append(None)\n else:\n all_batch_sizes.append(random.randint(1, 256))\n\n for shard_sizes, batch_size in zip(all_shard_sizes, all_batch_sizes):\n\n all_Xs, all_ys, all_ws, all_ids = [], [], [], []\n\n def shard_generator():\n for sz in shard_sizes:\n X_b = np.random.rand(sz, 1)\n y_b = np.random.rand(sz, 1)\n w_b = np.random.rand(sz, 1)\n ids_b = np.random.rand(sz)\n\n all_Xs.append(X_b)\n all_ys.append(y_b)\n all_ws.append(w_b)\n all_ids.append(ids_b)\n\n yield X_b, y_b, w_b, ids_b\n\n dataset = dc.data.DiskDataset.create_dataset(shard_generator())\n\n all_Xs = np.concatenate(all_Xs, axis=0)\n all_ys = np.concatenate(all_ys, axis=0)\n all_ws = np.concatenate(all_ws, axis=0)\n all_ids = np.concatenate(all_ids, axis=0)\n\n total_size = sum(shard_sizes)\n\n assert dataset.X.shape[0] == total_size\n\n # deterministic\n test_Xs, test_ys, test_ws, test_ids = [], [], [], []\n for bidx, (a, b, c, d) in enumerate(\n dataset.iterbatches(\n batch_size=batch_size, pad_batches=False, deterministic=True)):\n\n test_Xs.append(a)\n test_ys.append(b)\n test_ws.append(c)\n test_ids.append(d)\n\n if batch_size is None:\n for idx, (tx, ty, tw, tids) in enumerate(\n zip(test_Xs, test_ys, test_ws, test_ids)):\n assert len(tx) == shard_sizes[idx]\n assert len(ty) == shard_sizes[idx]\n assert len(tw) == shard_sizes[idx]\n assert len(tids) == shard_sizes[idx]\n\n test_Xs = np.concatenate(test_Xs, axis=0)\n test_ys = np.concatenate(test_ys, axis=0)\n test_ws = np.concatenate(test_ws, axis=0)\n test_ids = np.concatenate(test_ids, axis=0)\n\n if batch_size is None:\n assert bidx == len(shard_sizes) - 1\n else:\n assert bidx == math.ceil(total_size / batch_size) - 1\n\n np.testing.assert_array_equal(all_Xs, test_Xs)\n np.testing.assert_array_equal(all_ys, test_ys)\n np.testing.assert_array_equal(all_ws, test_ws)\n np.testing.assert_array_equal(all_ids, test_ids)\n\n # non-deterministic\n test_Xs, test_ys, test_ws, test_ids = [], [], [], []\n\n for bidx, (a, b, c, d) in enumerate(\n dataset.iterbatches(\n batch_size=batch_size, pad_batches=False, deterministic=False)):\n\n test_Xs.append(a)\n test_ys.append(b)\n test_ws.append(c)\n test_ids.append(d)\n\n # we don't know the order in which the shards are iterated in.\n test_Xs = np.concatenate(test_Xs, axis=0)\n test_ys = np.concatenate(test_ys, axis=0)\n test_ws = np.concatenate(test_ws, axis=0)\n test_ids = np.concatenate(test_ids, axis=0)\n\n if batch_size is None:\n assert bidx == len(shard_sizes) - 1\n else:\n assert bidx == math.ceil(total_size / batch_size) - 1\n\n np.testing.assert_array_equal(\n np.sort(all_Xs, axis=0), np.sort(test_Xs, axis=0))\n np.testing.assert_array_equal(\n np.sort(all_ys, axis=0), np.sort(test_ys, axis=0))\n np.testing.assert_array_equal(\n np.sort(all_ws, axis=0), np.sort(test_ws, axis=0))\n np.testing.assert_array_equal(\n np.sort(all_ids, axis=0), np.sort(test_ids, axis=0))\n\n def test_numpy_iterate_batch_size(self):\n solubility_dataset = dc.data.tests.load_solubility_data()\n X, y, _, _ = (solubility_dataset.X, solubility_dataset.y,\n solubility_dataset.w, solubility_dataset.ids)\n solubility_dataset = dc.data.NumpyDataset.from_DiskDataset(\n solubility_dataset)\n batch_sizes = []\n for X, y, _, _ in solubility_dataset.iterbatches(\n 3, pad_batches=False, deterministic=True):\n batch_sizes.append(len(X))\n self.assertEqual([3, 3, 3, 1], batch_sizes)\n\n def test_merge(self):\n \"\"\"Test that dataset merge works.\"\"\"\n num_datapoints = 10\n num_features = 10\n num_tasks = 1\n num_datasets = 4\n datasets = []\n for i in range(num_datasets):\n Xi = np.random.rand(num_datapoints, num_features)\n yi = np.random.randint(2, size=(num_datapoints, num_tasks))\n wi = np.ones((num_datapoints, num_tasks))\n idsi = np.array([\"id\"] * num_datapoints)\n dataseti = dc.data.DiskDataset.from_numpy(Xi, yi, wi, idsi)\n datasets.append(dataseti)\n\n new_data = dc.data.datasets.DiskDataset.merge(datasets)\n\n # Check that we have all the data in\n assert new_data.X.shape == (num_datapoints * num_datasets, num_features)\n assert new_data.y.shape == (num_datapoints * num_datasets, num_tasks)\n assert len(new_data.tasks) == len(datasets[0].tasks)\n\n def test_make_iterator(self):\n \"\"\"Test creating a Tensorflow Iterator from a Dataset.\"\"\"\n X = np.random.random((100, 5))\n y = np.random.random((100, 1))\n dataset = dc.data.NumpyDataset(X, y)\n iterator = dataset.make_iterator(\n batch_size=10, epochs=2, deterministic=True)\n next_element = iterator.get_next()\n with self.session() as sess:\n for i in range(20):\n batch_X, batch_y, batch_w = sess.run(next_element)\n offset = (i % 10) * 10\n np.testing.assert_array_equal(X[offset:offset + 10, :], batch_X)\n np.testing.assert_array_equal(y[offset:offset + 10, :], batch_y)\n np.testing.assert_array_equal(np.ones((10, 1)), batch_w)\n finished = False\n try:\n sess.run(next_element)\n except tf.errors.OutOfRangeError:\n finished = True\n assert finished\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "numpy.random.random", "numpy.random.seed", "numpy.array_equal", "numpy.eye", "numpy.sort", "numpy.ones", "numpy.testing.assert_array_equal", "numpy.concatenate", "numpy.std", "numpy.mean", "numpy.random.rand", "numpy.testing.assert_allclose", "numpy.random.binomial", "numpy.not_equal", "numpy.array", "numpy.zeros", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ChaofanTao/litegt
[ "65c8d9ee9a2b9dcc1de9f39df7e9a8af5b69c1d8" ]
[ "train/train_TSP_edge_classification.py" ]
[ "\"\"\"\n Utility functions for training one epoch \n and evaluating one epoch\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport math\nimport dgl\nfrom tqdm import tqdm\nfrom train.metrics import binary_f1_score\n \ndef train_epoch(model, optimizer, device, data_loader, epoch):\n model.train()\n epoch_loss = 0\n epoch_train_f1 = 0\n nb_data = 0\n gpu_mem = 0\n pbar = tqdm(enumerate(data_loader))\n for iter, (batch_graphs, batch_labels) in pbar:\n pbar.set_description(\"batch id\", iter)\n batch_graphs = batch_graphs.to(device)\n batch_x = batch_graphs.ndata['feat'].to(device) # num x feat\n batch_e = batch_graphs.edata['feat'].to(device)\n batch_labels = batch_labels.to(device)\n optimizer.zero_grad()\n try:\n batch_lap_pos_enc = batch_graphs.ndata['lap_pos_enc'].to(device)\n sign_flip = torch.rand(batch_lap_pos_enc.size(1)).to(device)\n sign_flip[sign_flip>=0.5] = 1.0; sign_flip[sign_flip<0.5] = -1.0\n batch_lap_pos_enc = batch_lap_pos_enc * sign_flip.unsqueeze(0)\n except:\n batch_lap_pos_enc = None\n \n batch_scores = model.forward(batch_graphs, batch_x, batch_e, batch_lap_pos_enc)\n \n loss = model.loss(batch_scores, batch_labels)\n loss.backward()\n optimizer.step()\n epoch_loss += loss.detach().item()\n f1 = binary_f1_score(batch_scores, batch_labels)\n epoch_train_f1 += f1\n nb_data += batch_labels.size(0)\n pbar.set_postfix({'loss':loss.item(),'f1':f1})\n epoch_loss /= (iter + 1)\n epoch_train_f1 /= (iter + 1)\n \n return epoch_loss, epoch_train_f1, optimizer\n \ndef evaluate_network(model, device, data_loader, epoch):\n model.eval()\n epoch_test_loss = 0\n epoch_test_f1 = 0\n nb_data = 0\n with torch.no_grad():\n for iter, (batch_graphs, batch_labels) in enumerate(data_loader):\n \n batch_graphs = batch_graphs.to(device)\n batch_x = batch_graphs.ndata['feat'].to(device)\n batch_e = batch_graphs.edata['feat'].to(device)\n batch_labels = batch_labels.to(device)\n try:\n batch_lap_pos_enc = batch_graphs.ndata['lap_pos_enc'].to(device)\n except:\n batch_lap_pos_enc = None\n batch_scores = model.forward(batch_graphs, batch_x, batch_e, batch_lap_pos_enc)\n loss = model.loss(batch_scores, batch_labels)\n epoch_test_loss += loss.detach().item()\n epoch_test_f1 += binary_f1_score(batch_scores, batch_labels)\n nb_data += batch_labels.size(0)\n\n epoch_test_loss /= (iter + 1)\n epoch_test_f1 /= (iter + 1)\n \n return epoch_test_loss, epoch_test_f1\n\n" ]
[ [ "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
serrhini/CSIKit
[ "1cc9ecb2c0444622b258e9de48841366cbbc667b" ]
[ "CSIKit/util/byteops.py" ]
[ "from typing import Tuple\n\nimport numpy as np\n\ndef signbit_convert(data: int, maxbit: int) -> int:\n if (data & (1 << (maxbit - 1))):\n data -= (1 << maxbit)\n\n return data\n\ndef get_next_bits(buf: bytes, current_data: int, idx: int, bits_left: int) -> Tuple[int, int, int]:\n h_data = buf[idx]\n h_data += (buf[idx+1] << 8)\n\n current_data += h_data << bits_left\n\n idx += 2\n bits_left += 16\n\n return current_data, idx, bits_left\n\ndef unpack_float_acphy(nbits: int, autoscale: int, shft: int, fmt: int, nman: int, nexp: int, nfft: int, H: np.array) -> np.array:\n k_tof_unpack_sgn_mask = (1<<31)\n\n He = [0] * nfft\n\n iq_mask = (1 << (nman - 1)) - 1\n e_mask = (1 << nexp) - 1\n e_p = (1 << (nexp - 1))\n sgnr_mask = (1 << (nexp + 2*nman - 1))\n sgni_mask = (sgnr_mask >> nman)\n e_zero = -nman\n\n out = np.zeros((nfft*2, 1), dtype=np.int64)\n n_out = (nfft << 1)\n e_shift = 1\n maxbit = -e_p\n\n for i in range(len(H)):\n vi = ((H[i] >> (nexp + nman)) & iq_mask)\n vq = ((H[i] >> nexp) & iq_mask)\n e = (H[i] & e_mask)\n \n if e >= e_p:\n e -= (e_p << 1)\n \n He[i] = e\n\n x = vi | vq\n \n if autoscale and x:\n m = 0xffff0000\n b = 0xffff\n s = 16\n\n while s > 0:\n if x & m:\n e += s\n x >>= s\n \n s >>= 1\n m = (m >> s) & b\n b >>= s\n \n if e > maxbit:\n maxbit = e\n \n if H[i] & sgnr_mask:\n vi |= k_tof_unpack_sgn_mask\n \n if H[i] & sgni_mask:\n vq |= k_tof_unpack_sgn_mask\n\n out[i<<1] = vi\n out[(i<<1)+1] = vq\n\n shft = nbits - maxbit\n for i in range(n_out):\n e = He[(i >> e_shift)] + shft\n vi = out[i]\n\n sgn = 1\n\n if vi & k_tof_unpack_sgn_mask:\n sgn = -1\n\n vi &= ~k_tof_unpack_sgn_mask\n \n if e < e_zero:\n vi = 0\n elif e < 0:\n e = -e\n vi = (vi >> e)\n else:\n vi = (vi << e)\n\n out[i] = sgn * vi\n\n return out" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dgketchum/csci547
[ "bbba91c1cd09f672342b11280f79e551968a0037" ]
[ "hw2/titanic.py" ]
[ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import confusion_matrix, accuracy_score\n\n\ndef softmax(X, W, N):\n a = np.dot(X, W)\n return np.exp(a) / np.repeat(np.sum(np.exp(a), axis=1, keepdims=True), N, axis=1)\n\n\ndef _J(X, W, T, N):\n return -np.sum(np.sum(T * np.log(softmax(X, W, N)), axis=1), axis=0)\n\n\ndef _gradient(X, W, T, m, N):\n return -np.column_stack([np.sum([(T - softmax(X, W, N))[i, k] * X[i] for i in range(m)],\n axis=0) for k in range(N)])\n\n\nfirst = True\nfor csv in ['titanic_train.csv', 'titanic_test.csv']:\n\n df = pd.read_csv(csv, engine='python')\n df.drop(columns=['PassengerId', 'Ticket', 'Cabin', 'Name',\n 'SibSp', 'Parch'], inplace=True)\n df.dropna(axis=0, how='any', inplace=True)\n\n one_hot_embark = pd.get_dummies(df['Embarked'])\n one_hot_sex = pd.get_dummies(df['Sex'])\n one_hot_pclass = pd.get_dummies(df['Pclass'])\n one_hot_pclass.columns = ['c1', 'c2', 'c3']\n\n df.drop(columns=['Sex', 'Embarked', 'Pclass', 'Age', 'Fare'], inplace=True)\n df = df.join([one_hot_pclass, one_hot_sex, one_hot_embark], how='outer')\n\n if first:\n y = df['Survived'].values\n train = df.drop(columns=['Survived'])\n x = train.values\n min_max_scaler = MinMaxScaler()\n D = min_max_scaler.fit_transform(x)\n first = False\n else:\n y_test = df['Survived'].values\n test = df.drop(columns=['Survived'])\n x = test.values\n min_max_scaler = MinMaxScaler()\n D_test = min_max_scaler.fit_transform(x)\n\nN = train.shape[1]\n\nX = np.column_stack((np.ones_like(y), D))\nm = X.shape[0]\nn = X.shape[1]\n\nT = np.zeros((m, N))\nfor t, yi in zip(T, y):\n t[yi] = 1\n\nN_iterations = 10**4\n\neta = 0.001\nW = 0.1 * np.random.randn(n, N)\n\ncost = np.zeros((N_iterations, 2))\ncost.fill(np.nan)\n\nfor i in range(N_iterations):\n W -= eta * _gradient(X, W, T, m, N)\n cost[i] = [i, _J(X, W, T, N)]\n if i % 1000 == 0:\n print(i)\n if i > 2:\n delta_cost = abs((cost[i, 1] - cost[i - 1, 1]) / cost[i, 1])\n print(delta_cost)\n if delta_cost < 0.01:\n print('Met change criterion after {} '\n 'iterations\\n cost change: {}'.format(i, delta_cost))\n break\n\ncost = cost[~np.isnan(cost).any(axis=1)]\n\ny_pred = np.argmax(softmax(X, W, N), axis=1)\nprint('Objective Function Value: ', _J(X, W, T, N),\n 'Total misclassified: ', sum(y != y_pred))\nprint(confusion_matrix(y_pred, y))\nprint('Training accuracy: {}'.format(accuracy_score(y, y_pred)))\n\nX = np.column_stack((np.ones_like(y_test), D_test))\n\ny_test_pred = np.argmax(softmax(X, W, N), axis=1)\n\nprint(confusion_matrix(y_test_pred, y_test))\nprint('Test accuracy: {}'.format(accuracy_score(y_test, y_test_pred)))\n\nplt.plot(cost[:, 0], cost[:, 1], 'r')\nplt.xlabel('Iteration')\nplt.ylabel('Cost Function Value')\nplt.show()\n\n# ========================= EOF ================================================================\n" ]
[ [ "numpy.dot", "pandas.read_csv", "numpy.ones_like", "numpy.isnan", "pandas.get_dummies", "sklearn.metrics.accuracy_score", "sklearn.metrics.confusion_matrix", "matplotlib.pyplot.plot", "numpy.random.randn", "numpy.exp", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.zeros", "sklearn.preprocessing.MinMaxScaler", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
Fredrik00/wavedata
[ "3e9b9b57c3254d84b2384153658206f07310264e" ]
[ "wavedata/tools/core/voxel_grid_2d.py" ]
[ "import numpy as np\n\nfrom wavedata.tools.core import geometry_utils\n\n\nclass VoxelGrid2D(object):\n \"\"\"\n Voxel grids represent occupancy info. The voxelize_2d method projects a point cloud\n onto a plane, while saving height and point density information for each voxel.\n \"\"\"\n\n # Class Constants\n VOXEL_EMPTY = -1\n VOXEL_FILLED = 0\n\n def __init__(self):\n\n # Quantization size of the voxel grid\n self.voxel_size = 0.0\n\n # Voxels at the most negative/positive xyz\n self.min_voxel_coord = np.array([])\n self.max_voxel_coord = np.array([])\n\n # Size of the voxel grid along each axis\n self.num_divisions = np.array([0, 0, 0])\n\n # Points in sorted order, to match the order of the voxels\n self.points = []\n\n # Indices of filled voxels\n self.voxel_indices = []\n\n # Max point height in projected voxel\n self.heights = []\n\n # Min point height in projected voxel\n self.min_heights = []\n\n # Number of points corresponding to projected voxel\n self.num_pts_in_voxel = []\n\n # Full occupancy grid, VOXEL_EMPTY or VOXEL_FILLED\n self.leaf_layout_2d = []\n\n # List of distances of filled voxels from origin, defaulted to a static value of 1\n self.distances = 1\n\n # Color of each point for visualization\n self.colors = []\n\n\n def voxelize_2d(self, pts, voxel_size, extents=None,\n ground_plane=None, create_leaf_layout=True, maps=[]):\n \"\"\"Voxelizes the point cloud into a 2D voxel grid by\n projecting it down into a flat plane, and stores the maximum\n point height, and number of points corresponding to the voxel\n\n :param pts: Point cloud as N x [x, y, z]\n :param voxel_size: Quantization size for the grid\n :param extents: Optional, specifies the full extents of the point cloud.\n Used for creating same sized voxel grids.\n :param ground_plane: Plane coefficients (a, b, c, d), xz plane used if\n not specified\n :param create_leaf_layout: Set this to False to create an empty\n leaf_layout, which will save computation\n time.\n \"\"\"\n\n if len(pts) == 0:\n pts = np.array([[0,0,0]]) # Add single point in origin to prevent crashing\n\n # Check if points are 3D, otherwise early exit\n if pts.shape[1] != 3:\n raise ValueError(\"Points have the wrong shape: {}\".format(\n pts.shape))\n\n self.voxel_size = voxel_size\n\n # Discretize voxel coordinates to given quantization size\n discrete_pts = np.floor(pts / voxel_size).astype(np.int32)\n\n # Use Lex Sort, sort by x, then z, then y (\n x_col = discrete_pts[:, 0]\n y_col = discrete_pts[:, 1]\n z_col = discrete_pts[:, 2]\n sorted_order = np.lexsort((y_col, z_col, x_col))\n\n # Save original points in sorted order\n self.points = pts[sorted_order]\n\n # Save discrete points in sorted order\n discrete_pts = discrete_pts[sorted_order]\n\n # Project all points to a 2D plane\n discrete_pts_2d = discrete_pts.copy()\n discrete_pts_2d[:, 1] = 0\n\n # Format the array to c-contiguous array for unique function\n contiguous_array = np.ascontiguousarray(discrete_pts_2d).view(\n np.dtype((np.void, discrete_pts_2d.dtype.itemsize *\n discrete_pts_2d.shape[1])))\n\n # The new coordinates are the discretized array with its unique indexes\n _, unique_indices = np.unique(contiguous_array, return_index=True)\n\n # Sort unique indices to preserve order\n unique_indices.sort()\n\n if \"max\" in maps or \"cluster\" in maps:\n height_in_voxel = self.get_voxel_height(ground_plane, unique_indices)\n # Store the heights\n self.heights = height_in_voxel\n\n if \"min\" in maps or \"cluster\" in maps:\n # Returns the indices of the lowest coordinate by reading the reversed view\n _, unique_min_indices = np.unique(contiguous_array[::-1], return_index=True)\n\n # Reverse indices so they refer to the same point\n unique_min_indices = (len(contiguous_array) - 1) - unique_min_indices\n\n # Sort unique indices to preserve order\n unique_min_indices.sort()\n\n min_height_in_voxel = self.get_voxel_height(ground_plane, unique_min_indices)\n\n # Store the heights\n # NOTE min height can be larger than max height if difference is\n # less than the voxel size\n self.min_heights = min_height_in_voxel\n\n voxel_coords = discrete_pts_2d[unique_indices]\n\n # Number of points per voxel, last voxel calculated separately\n num_points_in_voxel = np.diff(unique_indices)\n num_points_in_voxel = np.append(num_points_in_voxel,\n discrete_pts_2d.shape[0] -\n unique_indices[-1])\n\n # Store number of points per voxel\n self.num_pts_in_voxel = num_points_in_voxel\n\n if \"dnd\" in maps:\n # Calculate distances decomposed from x and z coordinates for all filled voxels\n distances = np.sqrt(np.sum(np.square(voxel_coords*voxel_size), axis=1))\n self.distances = distances\n\n if \"variance\" in maps:\n # Probably incredibly slow...\n variance = np.zeros_like(num_points_in_voxel)\n j = 0\n for i in range(len(variance)):\n variance[i] = np.var(self.points[j:j+num_points_in_voxel[i], 1])\n j += num_points_in_voxel[i]\n\n # Store the height variance per voxel\n self.variance = variance\n\n if \"cluster\" in maps:\n global_clusters = []\n height_diffs = np.abs(self.heights - self.min_heights)\n avg_dists = height_diffs/num_points_in_voxel\n dists = np.abs(np.diff(self.points[:, 1]))\n for i in range(len(unique_indices)):\n first = unique_indices[i]\n local_clusters = [[first]] # List of clusters with index of contained points\n longest_cluster = [first]\n longest = 1\n num_points = num_points_in_voxel[i]\n height_diff = height_diffs[i]\n average_distance = avg_dists[i]\n if average_distance < voxel_size:\n average_distance = voxel_size\n\n for j in range(first, first + num_points - 1):\n distance = dists[j]\n if distance <= average_distance:\n local_clusters[-1].append(j+1) # Add to current cluster\n if len(local_clusters[-1]) > longest:\n longest_cluster = local_clusters[-1]\n longest = len(longest_cluster)\n \n else:\n local_clusters.append([j+1]) # Add new cluster\n\n #if num_points > 1 and height_diff > voxel_size/10: #and longest > 1: # Removes some noise, but potentially also objects\n global_clusters.append(longest_cluster)\n\n cluster_indices = np.array([cluster[0] for cluster in global_clusters]) # Mark cluster location by index of first point\n cluster_min_indices = np.array([cluster[-1] for cluster in global_clusters]) # Mark cluster end location by index of first point\n cluster_coords = discrete_pts_2d[cluster_indices]\n \n self.num_pts_in_cluster = np.array([len(cluster) for cluster in global_clusters])\n self.cluster_heights = self.get_voxel_height(ground_plane, cluster_indices) # Take top point of clusters as max heights\n self.cluster_min_heights = self.get_voxel_height(ground_plane, cluster_min_indices) # Take bottom point of clusters as min heights\n\n # In order to only draw selected clusters\n #self.colors = np.array([[0, 0, 0] for point in self.points])\n #for cluster in global_clusters:\n # self.colors[cluster] = [1, 1, 1]\n #print(np.sum(np.sum(global_clusters)))\n\n # Find the minimum and maximum voxel coordinates\n if extents is not None:\n # Check provided extents\n extents_transpose = np.array(extents).transpose()\n if extents_transpose.shape != (2, 3):\n raise ValueError(\"Extents are the wrong shape {}\".format(\n extents.shape))\n\n # Set voxel grid extents\n self.min_voxel_coord = np.floor(extents_transpose[0]/voxel_size)\n self.max_voxel_coord = np.ceil((extents_transpose[1]/voxel_size)-1)\n\n self.min_voxel_coord[1] = 0\n self.max_voxel_coord[1] = 0\n\n # Check that points are bounded by new extents\n if not (self.min_voxel_coord <= np.amin(voxel_coords,\n axis=0)).all():\n raise ValueError(\"Extents are smaller than min_voxel_coord\")\n if not (self.max_voxel_coord >= np.amax(voxel_coords,\n axis=0)).all():\n raise ValueError(\"Extents are smaller than max_voxel_coord\")\n\n else:\n # Automatically calculate extents\n self.min_voxel_coord = np.amin(voxel_coords, axis=0)\n self.max_voxel_coord = np.amax(voxel_coords, axis=0)\n\n # Get the voxel grid dimensions\n self.num_divisions = ((self.max_voxel_coord - self.min_voxel_coord)\n + 1).astype(np.int32)\n\n # Bring the min voxel to the origin\n self.voxel_indices = (voxel_coords - self.min_voxel_coord).astype(int)\n if \"cluster\" in maps:\n self.cluster_voxel_indices = (cluster_coords - self.min_voxel_coord).astype(int)\n\n if create_leaf_layout:\n # Create Voxel Object with -1 as empty/occluded, 0 as occupied\n self.leaf_layout_2d = self.VOXEL_EMPTY * \\\n np.ones(self.num_divisions.astype(int))\n\n # Fill out the leaf layout\n self.leaf_layout_2d[self.voxel_indices[:, 0], 0,\n self.voxel_indices[:, 2]] = \\\n self.VOXEL_FILLED\n\n\n def map_to_index(self, map_index):\n \"\"\"Converts map coordinate values to 1-based discretized grid index\n coordinate. Note: Any values outside the extent of the grid will be\n forced to be the maximum grid coordinate.\n\n :param map_index: N x 2 points\n\n :return: N x length(dim) (grid coordinate)\n [] if min_voxel_coord or voxel_size or grid_index or dim is not set\n \"\"\"\n if self.voxel_size == 0 \\\n or len(self.min_voxel_coord) == 0 \\\n or len(map_index) == 0:\n return []\n\n num_divisions_2d = self.num_divisions[[0, 2]]\n min_voxel_coord_2d = self.min_voxel_coord[[0, 2]]\n\n # Truncate index (same as np.floor for positive values) and clip\n # to valid voxel index range\n indices = np.int32(map_index / self.voxel_size) - min_voxel_coord_2d\n indices[:, 0] = np.clip(indices[:, 0], 0, num_divisions_2d[0])\n indices[:, 1] = np.clip(indices[:, 1], 0, num_divisions_2d[1])\n\n return indices\n\n\n def get_voxel_height(self, ground_plane, indices):\n if ground_plane is None:\n # Use first point in voxel as highest point\n return self.points[indices, 1]\n else:\n # Ground plane provided\n return geometry_utils.dist_to_plane(ground_plane, self.points[indices])\n\n" ]
[ [ "numpy.square", "numpy.amax", "numpy.abs", "numpy.unique", "numpy.clip", "numpy.amin", "numpy.ascontiguousarray", "numpy.int32", "numpy.lexsort", "numpy.dtype", "numpy.ceil", "numpy.append", "numpy.diff", "numpy.zeros_like", "numpy.floor", "numpy.var", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
basp/aya
[ "16614a62d0696ae38721a47fdafbc90ef295ebc2" ]
[ "perlin.py" ]
[ "# http://scratchapixel.com/old/lessons/3d-advanced-lessons/noise-part-1/\nimport numpy as np\n\nMAX_VERTICES = 256\nMAX_VERTICES_MASK = MAX_VERTICES - 1\n\nr = np.random.ranf(MAX_VERTICES)\nperm = [i & MAX_VERTICES_MASK for i in range(MAX_VERTICES * 2)]\nnp.random.shuffle(perm)\n\ndef lerp(v0, v1, t):\n\treturn (1.0 - t) * v0 + (t * v1)\n\ndef floor(x):\n\treturn int(x) - (x < 0 and int(x) != x)\n\ndef smoothstep(t):\n\treturn t * t * (3 - 2 * t)\n\ndef noise2d(x, y):\n\txi, yi = floor(x), floor(y)\n\ttx, ty = x - xi, y - yi\n\t\n\trx0 = xi & MAX_VERTICES_MASK\n\trx1 = (rx0 + 1) & MAX_VERTICES_MASK\n\try0 = yi & MAX_VERTICES_MASK\n\try1 = (ry0 + 1) & MAX_VERTICES_MASK \n\t\n\tc00 = r[perm[perm[rx0] + ry0]]\n\tc10 = r[perm[perm[rx1] + ry0]]\n\tc01 = r[perm[perm[rx0] + ry1]]\n\tc11 = r[perm[perm[rx1] + ry1]]\n\t\n\tsx = smoothstep(tx)\n\tsy = smoothstep(ty)\n\t\n\tnx0 = lerp(c00, c10, sx)\n\tnx1 = lerp(c01, c11, sx)\n\t\n\treturn lerp(nx0, nx1, sy)\n\t\ndef fbm(x, y, lacunarity = 2, gain = 0.5, octaves = 5):\n\tn = 0\n\tamp = 1\n\tfor i in range(octaves):\n\t\tn += noise2d(x, y) * amp\n\t\tx *= lacunarity\n\t\ty *= lacunarity\n\t\tamp *= gain\n\treturn n" ]
[ [ "numpy.random.ranf", "numpy.random.shuffle" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wenlanzsw/pyroms
[ "d1aa8647d4119aef07cbf576100c3e6d44d60931" ]
[ "setup.py" ]
[ "\"\"\"Tools to work with the Regional Ocean Modeling System (ROMS).\n\nBased on:\n + NumPy (http://numpy.scipy.org)\n + matplotlib with the basemap toolkit (http://matplotlib.sourceforge.net)\n + netCDF4 (http://www.cdc.noaa.gov/people/jeffrey.s.whitaker/python/netCDF4.html)\n\nContains:\n + grid\n + Grid - a class for holding horizontal and vertical ROMS grid information\n + nc_grid - make an instance of Grid based on a netcdf file\n + gridgen - create an instance of Grid using the gridgen program\n + ocean_time - retrieve time information from a netcdf file\n + roms_tools - functions for working with roms coordinates\n\"\"\"\n\nclassifiers = \"\"\"\\\nDevelopment Status :: beta\nEnvironment :: Console\nIntended Audience :: Science/Research\nIntended Audience :: Developers\nLicense :: MIT\nOperating System :: OS Independent\nProgramming Language :: Python\nTopic :: Scientific/Engineering\nTopic :: Software Development :: Libraries :: Python Modules\n\"\"\"\n\nfrom numpy.distutils.core import Extension\n\niso = Extension(name = '_iso',\n sources = ['pyroms/iso.f'])\n\nstep3d_t = Extension(name = '_step3d_t',\n sources = ['pyroms/step3d_t.f'])\n\ndelaunay = Extension(name = '_delaunay',\n sources=[\"pyroms/delaunay/_delaunay.cpp\",\n \"pyroms/delaunay/VoronoiDiagramGenerator.cpp\",\n \"pyroms/delaunay/delaunay_utils.cpp\",\n \"pyroms/delaunay/natneighbors.cpp\"])\n\ndoclines = __doc__.split(\"\\n\")\n\ngshhs_datafiles = ['gshhs-data/gshhs_c.b', \n 'gshhs-data/gshhs_l.b',\n 'gshhs-data/gshhs_i.b',\n 'gshhs-data/gshhs_h.b',\n 'gshhs-data/gshhs_f.b']\n\npackage_data = {'pyroms': gshhs_datafiles}\n\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n setup(name = \"pyroms\",\n version = '0.8.0',\n description = doclines[0],\n long_description = \"\\n\".join(doclines[2:]),\n author = \"Robert Hetland\",\n author_email = \"[email protected]\",\n url = \"http://code.google.com/p/pyroms/\",\n packages = ['pyroms', 'pyroms/delaunay'],\n license = 'MIT',\n platforms = [\"any\"],\n ext_modules = [iso, step3d_t, delaunay],\n classifiers = filter(None, classifiers.split(\"\\n\")),\n package_data = package_data,\n )\n " ]
[ [ "numpy.distutils.core.Extension" ] ]
[ { "matplotlib": [], "numpy": [ "1.11", "1.19", "1.24", "1.16", "1.23", "1.20", "1.7", "1.12", "1.21", "1.22", "1.14", "1.6", "1.13", "1.9", "1.17", "1.10", "1.18", "1.15", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
raspbian-packages/pandas
[ "fb33806b5286deb327b2e0fa96aedf25a6ed563f" ]
[ "asv_bench/benchmarks/gil.py" ]
[ "from .pandas_vb_common import *\nfrom pandas.core import common as com\n\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\ntry:\n from pandas.util.testing import test_parallel\n\n have_real_test_parallel = True\nexcept ImportError:\n have_real_test_parallel = False\n\n\n def test_parallel(num_threads=1):\n\n def wrapper(fname):\n return fname\n\n return wrapper\n\n\nclass nogil_groupby_base(object):\n goal_time = 0.2\n\n def setup(self):\n self.N = 1000000\n self.ngroups = 1000\n np.random.seed(1234)\n self.df = DataFrame({'key': np.random.randint(0, self.ngroups, size=self.N), 'data': np.random.randn(self.N), })\n if (not have_real_test_parallel):\n raise NotImplementedError\n\n\nclass nogil_groupby_count_2(nogil_groupby_base):\n\n def time_nogil_groupby_count_2(self):\n self.pg2()\n\n @test_parallel(num_threads=2)\n def pg2(self):\n self.df.groupby('key')['data'].count()\n\n\nclass nogil_groupby_last_2(nogil_groupby_base):\n\n def time_nogil_groupby_last_2(self):\n self.pg2()\n\n @test_parallel(num_threads=2)\n def pg2(self):\n self.df.groupby('key')['data'].last()\n\n\nclass nogil_groupby_max_2(nogil_groupby_base):\n\n def time_nogil_groupby_max_2(self):\n self.pg2()\n\n @test_parallel(num_threads=2)\n def pg2(self):\n self.df.groupby('key')['data'].max()\n\n\nclass nogil_groupby_mean_2(nogil_groupby_base):\n\n def time_nogil_groupby_mean_2(self):\n self.pg2()\n\n @test_parallel(num_threads=2)\n def pg2(self):\n self.df.groupby('key')['data'].mean()\n\n\nclass nogil_groupby_min_2(nogil_groupby_base):\n\n def time_nogil_groupby_min_2(self):\n self.pg2()\n\n @test_parallel(num_threads=2)\n def pg2(self):\n self.df.groupby('key')['data'].min()\n\n\nclass nogil_groupby_prod_2(nogil_groupby_base):\n\n def time_nogil_groupby_prod_2(self):\n self.pg2()\n\n @test_parallel(num_threads=2)\n def pg2(self):\n self.df.groupby('key')['data'].prod()\n\n\nclass nogil_groupby_sum_2(nogil_groupby_base):\n\n def time_nogil_groupby_sum_2(self):\n self.pg2()\n\n @test_parallel(num_threads=2)\n def pg2(self):\n self.df.groupby('key')['data'].sum()\n\n\nclass nogil_groupby_sum_4(nogil_groupby_base):\n\n def time_nogil_groupby_sum_4(self):\n self.pg4()\n\n def f(self):\n self.df.groupby('key')['data'].sum()\n\n def g4(self):\n for i in range(4):\n self.f()\n\n @test_parallel(num_threads=4)\n def pg4(self):\n self.f()\n\n\nclass nogil_groupby_sum_8(nogil_groupby_base):\n\n def time_nogil_groupby_sum_8(self):\n self.pg8()\n\n def f(self):\n self.df.groupby('key')['data'].sum()\n\n def g8(self):\n for i in range(8):\n self.f()\n\n @test_parallel(num_threads=8)\n def pg8(self):\n self.f()\n\n\nclass nogil_groupby_var_2(nogil_groupby_base):\n\n def time_nogil_groupby_var_2(self):\n self.pg2()\n\n @test_parallel(num_threads=2)\n def pg2(self):\n self.df.groupby('key')['data'].var()\n\n\nclass nogil_groupby_groups(object):\n goal_time = 0.2\n\n def setup(self):\n np.random.seed(1234)\n self.size = 2**22\n self.ngroups = 100\n self.data = Series(np.random.randint(0, self.ngroups, size=self.size))\n if (not have_real_test_parallel):\n raise NotImplementedError\n\n def f(self):\n self.data.groupby(self.data).groups\n\n\nclass nogil_groupby_groups_2(nogil_groupby_groups):\n\n def time_nogil_groupby_groups(self):\n self.pg2()\n\n @test_parallel(num_threads=2)\n def pg2(self):\n self.f()\n\n\nclass nogil_groupby_groups_4(nogil_groupby_groups):\n\n def time_nogil_groupby_groups(self):\n self.pg4()\n\n @test_parallel(num_threads=4)\n def pg4(self):\n self.f()\n\n\nclass nogil_groupby_groups_8(nogil_groupby_groups):\n\n def time_nogil_groupby_groups(self):\n self.pg8()\n\n @test_parallel(num_threads=8)\n def pg8(self):\n self.f()\n\n\nclass nogil_take1d_float64(object):\n goal_time = 0.2\n\n def setup(self):\n self.N = 1000000\n self.ngroups = 1000\n np.random.seed(1234)\n self.df = DataFrame({'key': np.random.randint(0, self.ngroups, size=self.N), 'data': np.random.randn(self.N), })\n if (not have_real_test_parallel):\n raise NotImplementedError\n self.N = 10000000.0\n self.df = DataFrame({'int64': np.arange(self.N, dtype='int64'), 'float64': np.arange(self.N, dtype='float64'), })\n self.indexer = np.arange(100, (len(self.df) - 100))\n\n def time_nogil_take1d_float64(self):\n self.take_1d_pg2_int64()\n\n @test_parallel(num_threads=2)\n def take_1d_pg2_int64(self):\n com.take_1d(self.df.int64.values, self.indexer)\n\n @test_parallel(num_threads=2)\n def take_1d_pg2_float64(self):\n com.take_1d(self.df.float64.values, self.indexer)\n\n\nclass nogil_take1d_int64(object):\n goal_time = 0.2\n\n def setup(self):\n self.N = 1000000\n self.ngroups = 1000\n np.random.seed(1234)\n self.df = DataFrame({'key': np.random.randint(0, self.ngroups, size=self.N), 'data': np.random.randn(self.N), })\n if (not have_real_test_parallel):\n raise NotImplementedError\n self.N = 10000000.0\n self.df = DataFrame({'int64': np.arange(self.N, dtype='int64'), 'float64': np.arange(self.N, dtype='float64'), })\n self.indexer = np.arange(100, (len(self.df) - 100))\n\n def time_nogil_take1d_int64(self):\n self.take_1d_pg2_float64()\n\n @test_parallel(num_threads=2)\n def take_1d_pg2_int64(self):\n com.take_1d(self.df.int64.values, self.indexer)\n\n @test_parallel(num_threads=2)\n def take_1d_pg2_float64(self):\n com.take_1d(self.df.float64.values, self.indexer)\n\n\nclass nogil_kth_smallest(object):\n number = 1\n repeat = 5\n\n def setup(self):\n if (not have_real_test_parallel):\n raise NotImplementedError\n np.random.seed(1234)\n self.N = 10000000\n self.k = 500000\n self.a = np.random.randn(self.N)\n self.b = self.a.copy()\n self.kwargs_list = [{'arr': self.a}, {'arr': self.b}]\n\n def time_nogil_kth_smallest(self):\n @test_parallel(num_threads=2, kwargs_list=self.kwargs_list)\n def run(arr):\n algos.kth_smallest(arr, self.k)\n run()\n\n\nclass nogil_datetime_fields(object):\n goal_time = 0.2\n\n def setup(self):\n self.N = 100000000\n self.dti = pd.date_range('1900-01-01', periods=self.N, freq='D')\n self.period = self.dti.to_period('D')\n if (not have_real_test_parallel):\n raise NotImplementedError\n\n def time_datetime_field_year(self):\n @test_parallel(num_threads=2)\n def run(dti):\n dti.year\n run(self.dti)\n\n def time_datetime_field_day(self):\n @test_parallel(num_threads=2)\n def run(dti):\n dti.day\n run(self.dti)\n\n def time_datetime_field_daysinmonth(self):\n @test_parallel(num_threads=2)\n def run(dti):\n dti.days_in_month\n run(self.dti)\n\n def time_datetime_field_normalize(self):\n @test_parallel(num_threads=2)\n def run(dti):\n dti.normalize()\n run(self.dti)\n\n def time_datetime_to_period(self):\n @test_parallel(num_threads=2)\n def run(dti):\n dti.to_period('S')\n run(self.dti)\n\n def time_period_to_datetime(self):\n @test_parallel(num_threads=2)\n def run(period):\n period.to_timestamp()\n run(self.period)\n\n\nclass nogil_rolling_algos_slow(object):\n goal_time = 0.2\n\n def setup(self):\n self.win = 100\n np.random.seed(1234)\n self.arr = np.random.rand(100000)\n if (not have_real_test_parallel):\n raise NotImplementedError\n\n def time_nogil_rolling_median(self):\n @test_parallel(num_threads=2)\n def run(arr, win):\n rolling_median(arr, win)\n run(self.arr, self.win)\n\n\nclass nogil_rolling_algos_fast(object):\n goal_time = 0.2\n\n def setup(self):\n self.win = 100\n np.random.seed(1234)\n self.arr = np.random.rand(1000000)\n if (not have_real_test_parallel):\n raise NotImplementedError\n\n def time_nogil_rolling_mean(self):\n @test_parallel(num_threads=2)\n def run(arr, win):\n rolling_mean(arr, win)\n run(self.arr, self.win)\n\n def time_nogil_rolling_min(self):\n @test_parallel(num_threads=2)\n def run(arr, win):\n rolling_min(arr, win)\n run(self.arr, self.win)\n\n def time_nogil_rolling_max(self):\n @test_parallel(num_threads=2)\n def run(arr, win):\n rolling_max(arr, win)\n run(self.arr, self.win)\n\n def time_nogil_rolling_var(self):\n @test_parallel(num_threads=2)\n def run(arr, win):\n rolling_var(arr, win)\n run(self.arr, self.win)\n\n def time_nogil_rolling_skew(self):\n @test_parallel(num_threads=2)\n def run(arr, win):\n rolling_skew(arr, win)\n run(self.arr, self.win)\n\n def time_nogil_rolling_kurt(self):\n @test_parallel(num_threads=2)\n def run(arr, win):\n rolling_kurt(arr, win)\n run(self.arr, self.win)\n\n def time_nogil_rolling_std(self):\n @test_parallel(num_threads=2)\n def run(arr, win):\n rolling_std(arr, win)\n run(self.arr, self.win)\n\n\nclass nogil_read_csv(object):\n number = 1\n repeat = 5\n\n def setup(self):\n if (not have_real_test_parallel):\n raise NotImplementedError\n # Using the values\n self.df = DataFrame(np.random.randn(10000, 50))\n self.df.to_csv('__test__.csv')\n\n self.rng = date_range('1/1/2000', periods=10000)\n self.df_date_time = DataFrame(np.random.randn(10000, 50), index=self.rng)\n self.df_date_time.to_csv('__test_datetime__.csv')\n\n self.df_object = DataFrame('foo', index=self.df.index, columns=self.create_cols('object'))\n self.df_object.to_csv('__test_object__.csv')\n\n def create_cols(self, name):\n return [('%s%03d' % (name, i)) for i in range(5)]\n\n @test_parallel(num_threads=2)\n def pg_read_csv(self):\n read_csv('__test__.csv', sep=',', header=None, float_precision=None)\n\n def time_nogil_read_csv(self):\n self.pg_read_csv()\n\n @test_parallel(num_threads=2)\n def pg_read_csv_object(self):\n read_csv('__test_object__.csv', sep=',')\n\n def time_nogil_read_csv_object(self):\n self.pg_read_csv_object()\n\n @test_parallel(num_threads=2)\n def pg_read_csv_datetime(self):\n read_csv('__test_datetime__.csv', sep=',', header=None)\n\n def time_nogil_read_csv_datetime(self):\n self.pg_read_csv_datetime()\n" ]
[ [ "pandas.core.common.take_1d", "pandas.util.testing.test_parallel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "1.4", "0.19", "1.1", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
IEavan/tournaments-analysis
[ "d91050867ff3ca891c0e326fcbf8009f353bf72e" ]
[ "tournaments.py" ]
[ "import numpy as np\nfrom player import Player\n\nclass Elimination():\n def __init__(self, players):\n if np.log2(len(players)) != int(np.log2(len(players))):\n raise ValueError(\"Number of players must be a power of 2\")\n self.players = players\n\n def get_brackets(self):\n brackets = []\n brackets.append(self.players)\n while len(brackets[-1]) > 1:\n next_bracket = []\n for i in range(0, len(brackets[-1]), 2):\n next_bracket.append(brackets[-1][i].get_winner(brackets[-1][i+1]))\n np.random.shuffle(next_bracket)\n brackets.append(next_bracket)\n return brackets\n\n def get_winner(self):\n brackets = self.get_brackets()\n return brackets[-1][0]\n" ]
[ [ "numpy.random.shuffle" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
damonchang23/3d_pose_baseline_pytorch
[ "5fedd6b2026be43155829a87d5c7ba6d5db64af6" ]
[ "src/model.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nimport torch.nn as nn\n\n\ndef weight_init(m):\n if isinstance(m, nn.Linear):\n nn.init.kaiming_normal_(m.weight)\n\n\nclass Linear(nn.Module):\n def __init__(self, linear_size, p_dropout=0.5):\n super(Linear, self).__init__()\n self.l_size = linear_size\n\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout(p_dropout)\n\n self.w1 = nn.Linear(self.l_size, self.l_size)\n self.batch_norm1 = nn.BatchNorm1d(self.l_size)\n\n self.w2 = nn.Linear(self.l_size, self.l_size)\n self.batch_norm2 = nn.BatchNorm1d(self.l_size)\n\n def forward(self, x):\n y = self.w1(x)\n y = self.batch_norm1(y)\n y = self.relu(y)\n y = self.dropout(y)\n\n y = self.w2(y)\n y = self.batch_norm2(y)\n y = self.relu(y)\n y = self.dropout(y)\n\n out = x + y\n\n return out\n\n\nclass LinearModel(nn.Module):\n def __init__(self,\n linear_size=1024,\n num_stage=2,\n p_dropout=0.5):\n super(LinearModel, self).__init__()\n\n self.linear_size = linear_size\n self.p_dropout = p_dropout\n self.num_stage = num_stage\n\n # 2d joints\n self.input_size = 16 * 2\n # 3d joints\n self.output_size = 16 * 3\n\n # process input to linear size\n self.w1 = nn.Linear(self.input_size, self.linear_size)\n self.batch_norm1 = nn.BatchNorm1d(self.linear_size)\n\n self.linear_stages = []\n for l in range(num_stage):\n self.linear_stages.append(Linear(self.linear_size, self.p_dropout))\n self.linear_stages = nn.ModuleList(self.linear_stages)\n\n # post processing\n self.w2 = nn.Linear(self.linear_size, self.output_size)\n\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout(self.p_dropout)\n\n def forward(self, x):\n # pre-processing\n y = self.w1(x)\n y = self.batch_norm1(y)\n y = self.relu(y)\n y = self.dropout(y)\n\n # linear layers\n for i in range(self.num_stage):\n y = self.linear_stages[i](y)\n\n y = self.w2(y)\n\n return y\n\n\n" ]
[ [ "torch.nn.BatchNorm1d", "torch.nn.Dropout", "torch.nn.ModuleList", "torch.nn.Linear", "torch.nn.ReLU", "torch.nn.init.kaiming_normal_" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Karlinik/RotationDetection
[ "efd20d56d3964b89fa356e79a052bb53f6ac8ddb" ]
[ "libs/configs/DOTA/retinanet/cfgs_res50_dota_atan_v2.py" ]
[ "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\n\nimport numpy as np\n\nfrom libs.configs._base_.models.retinanet_r50_fpn import *\nfrom libs.configs._base_.datasets.dota_detection import *\nfrom libs.configs._base_.schedules.schedule_1x import *\nfrom dataloader.pretrained_weights.pretrain_zoo import PretrainModelZoo\n\n# schedule\nBATCH_SIZE = 1\nGPU_GROUP = \"0\"\nNUM_GPU = len(GPU_GROUP.strip().split(','))\nSAVE_WEIGHTS_INTE = 27000\nDECAY_STEP = np.array(DECAY_EPOCH, np.int32) * SAVE_WEIGHTS_INTE\nMAX_ITERATION = SAVE_WEIGHTS_INTE * MAX_EPOCH\nWARM_SETP = int(WARM_EPOCH * SAVE_WEIGHTS_INTE)\n\n# dataset\n\n# model\n# backbone\npretrain_zoo = PretrainModelZoo()\nPRETRAINED_CKPT = pretrain_zoo.pretrain_weight_path(NET_NAME, ROOT_PATH)\nTRAINED_CKPT = os.path.join(ROOT_PATH, 'output/trained_weights')\n\n# bbox head\nANGLE_RANGE = 180\n\n# loss\nCLS_WEIGHT = 1.0\nREG_WEIGHT = 1.0 / 5.0\nREG_LOSS_MODE = None\n\nVERSION = 'RetinaNet_DOTA_1x_20210725'\n\n\"\"\"\nRetinaNet-H + theta=atan(sin(theta)/cos(theta)) + 180, sin^2(theta) + cos^2(theta) = 1\n[-90, 90] sin in [-1, 1] cos in [0, 1]\nFLOPs: 485784881; Trainable params: 33051321\nThis is your result for task 1:\n\nmAP: 0.6482820239385153\nap of each class: plane:0.8863486082518542, baseball-diamond:0.7510916490271552, bridge:0.4136498976633022, ground-track-field:0.6934357734426206, small-vehicle:0.5915433817529869, large-vehicle:0.4156886089040786, ship:0.6512479280213479, tennis-court:0.8965927064782218, basketball-court:0.778541563411186, storage-tank:0.7716242837257139, soccer-ball-field:0.5261143148330104, roundabout:0.6328490142731126, harbor:0.5072934651888339, swimming-pool:0.6566747539350666, helicopter:0.55153441016924\nThe submitted information is :\n\nDescription: RetinaNet_DOTA_1x_20210725_35.1w_v1\nUsername: SJTU-Det\nInstitute: SJTU\nEmailadress: [email protected]\nTeamMembers: yangxue\n\"\"\"\n\n\n\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
103yiran/open-vot
[ "9bb4427c300dc2bddf38e6a8c2c257a015d10d4f" ]
[ "lib/experiments/vot.py" ]
[ "from __future__ import absolute_import, division\n\nimport os\nimport cv2\nimport time\nimport numpy as np\nimport glob\nimport json\nimport ast\n\nfrom ..datasets.vot import VOT\nfrom ..utils import dict2tuple\nfrom ..utils.viz import show_frame\nfrom ..metrics import rect_iou, poly_iou\n\n\nclass ExperimentVOT(object):\n\n def __init__(self, vot_dir, version=2017,\n result_dir='results', report_dir='reports', **kargs):\n super(ExperimentVOT, self).__init__()\n self.dataset = VOT(vot_dir, version,\n anno_type='rect', download=True)\n self.result_dir = os.path.join(result_dir, 'vot%d' % version)\n self.report_dir = os.path.join(report_dir, 'vot%d' % version)\n self.parse_args(**kargs)\n # setup experiment functions\n self.setup_experiments()\n\n def parse_args(self, **kargs):\n self.cfg = {\n 'experiments': ['baseline', 'unsupervised', 'realtime'],\n 'repetitions': {\n 'baseline': 15,\n 'unsupervised': 1,\n 'realtime': 1},\n 'min_repetitions': 3,\n 'default_fps': 20,\n 'grace': 3,\n 'skip_initialize': 5}\n\n for key, val in kargs.items():\n self.cfg.update({key: val})\n self.cfg = dict2tuple(self.cfg)\n\n def setup_experiments(self):\n self.experiments = []\n for e in self.cfg.experiments:\n assert e in ('baseline', 'unsupervised', 'realtime')\n if e == 'baseline':\n self.experiments.append(self.run_baseline)\n elif e == 'unsupervised':\n self.experiments.append(self.run_unsupervised)\n elif e == 'realtime':\n self.experiments.append(self.run_realtime)\n\n def run(self, tracker, visualize=False):\n print('Running tracker %s on VOT%d...' %\n (tracker.name, self.dataset.version))\n for e in self.experiments:\n e(tracker, visualize)\n\n def run_baseline(self, tracker, visualize=False):\n print('Running baseline experiment...')\n\n # loop over the complete dataset\n for s, (img_files, anno) in enumerate(self.dataset):\n seq_name = self.dataset.seq_names[s]\n print('--Sequence %d/%d: %s' %\n (s + 1, len(self.dataset), seq_name))\n\n # run multiple repetitions for each sequence\n for r in range(self.cfg.repetitions['baseline']):\n # for deterministic tracker, skip repetitions\n if r == self.cfg.min_repetitions and self._check_deterministic('baseline', tracker.name, seq_name):\n print(' Detected a deterministic tracker, ' +\n 'skipping remaining trails.')\n break\n print(' Repetition: %d' % (r + 1))\n\n # tracking loop of reset-based experiment\n states = []\n elapsed_times = []\n failure = False\n skipped_frames = -1\n for f, img_file in enumerate(img_files):\n img = cv2.imread(img_file)\n if img.ndim == 2:\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n elif img.ndim == 3:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n start = time.time()\n if f == 0:\n # initial frame\n tracker.init(img, anno[f])\n states.append([1])\n elif not failure:\n # during success frames\n state = tracker.update(img)\n if rect_iou(state, anno[f]) == 0: # tracking failure\n failure = True\n skipped_frames = 1\n states.append([2])\n else:\n states.append(state)\n else:\n # during failure frames\n if skipped_frames == 5:\n tracker.init(img, anno[f])\n states.append([1])\n failure = False\n skipped_frames = -1\n else:\n skipped_frames += 1\n states.append([0])\n start = np.NaN\n elapsed_times.append(time.time() - start)\n\n if visualize:\n if len(states[-1]) == 1:\n show_frame(img, anno[f], color=(255, 255, 255)\n if img.shape[2] == 3 else 255)\n else:\n show_frame(img, state, color=(255, 0, 0)\n if img.shape[2] == 3 else 255)\n\n # record results\n self._record('baseline', tracker.name, seq_name, r,\n states, elapsed_times)\n\n def run_unsupervised(self, tracker, visualize=False):\n print('Running unsupervised experiment...')\n\n # loop over the complete dataset\n for s, (img_files, anno) in enumerate(self.dataset):\n seq_name = self.dataset.seq_names[s]\n print('--Sequence %d/%d: %s' %\n (s + 1, len(self.dataset), seq_name))\n\n # run multiple repetitions for each sequence\n for r in range(self.cfg.repetitions['unsupervised']):\n # for deterministic tracker, skip repetitions\n if r == self.cfg.min_repetitions and self._check_deterministic('unsupervised', seq_name):\n print(' Detected a deterministic tracker, ' +\n 'skipping remaining trails.')\n break\n print(' Repetition: %d' % (r + 1))\n\n # tracking loop\n states = []\n elapsed_times = []\n for f, img_file in enumerate(img_files):\n img = cv2.imread(img_file)\n if img.ndim == 2:\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n elif img.ndim == 3:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n start = time.time()\n if f == 0:\n tracker.init(img, anno[f])\n states.append([1])\n else:\n states.append(tracker.update(img))\n elapsed_times.append(time.time() - start)\n\n if visualize:\n show_frame(img, states[f] if f > 0 else anno[f])\n\n # record results\n self._record('unsupervised', tracker.name, seq_name, r,\n states, elapsed_times)\n\n def run_realtime(self, tracker, visualize=False):\n print('Running realtime experiment...')\n\n # loop over the complete dataset\n for s, (img_files, anno) in enumerate(self.dataset):\n seq_name = self.dataset.seq_names[s]\n print('--Sequence %d/%d: %s' %\n (s + 1, len(self.dataset), seq_name))\n\n # run multiple repetitions for each sequence\n for r in range(self.cfg.repetitions['realtime']):\n # for deterministic tracker, skip repetitions\n if r == self.cfg.min_repetitions and self._check_deterministic('realtime', tracker.name, seq_name):\n print(' Detected a deterministic tracker, ' +\n 'skipping remaining trails.')\n break\n print(' Repetition: %d' % (r + 1))\n\n # tracking loop of reset-based realtime experiment\n states = []\n elapsed_times = []\n init_frame = 0\n for f, img_file in enumerate(img_files):\n img = cv2.imread(img_file)\n if img.ndim == 2:\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n elif img.ndim == 3:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n start = time.time()\n if f == init_frame:\n # initial frame\n tracker.init(img, anno[f])\n end = time.time()\n states.append([1])\n\n # initialize parameters\n accum_time = 1. / self.cfg.default_fps\n grace = self.cfg.grace - 1\n failure = False\n skipped_frames = -1\n elif not failure:\n if grace > 0:\n # during grace frames\n state = tracker.update(img)\n end = time.time()\n\n accum_time += 1. / self.cfg.default_fps\n grace -= 1\n if grace == 0:\n # calculate the next frame according to the realtime setting\n next_frame = init_frame + round(np.floor(\n (accum_time + max(1. / self.cfg.default_fps, end - start)) * self.cfg.default_fps))\n elif f < next_frame:\n # during skipped frames\n state = state # assign with the last tracking result\n end = np.NaN\n else:\n # during normal frames\n state = tracker.update(img)\n end = time.time()\n\n accum_time += max(1. /\n self.cfg.default_fps, end - start)\n # calculate the next frame according to the realtime setting\n next_frame = init_frame + round(np.floor(\n (accum_time + max(1. / self.cfg.default_fps, end - start)) * self.cfg.default_fps))\n\n if rect_iou(state, anno[f]) > 0:\n states.append(state)\n else:\n states.append([2])\n end = np.NaN\n\n failure = True\n skipped_frames = 1\n else:\n # during failure frames\n if skipped_frames == self.cfg.skip_initialize:\n # initial frame\n tracker.init(img, anno[f])\n end = time.time()\n states.append([1])\n\n # initialize parameters\n accum_time = 1. / self.cfg.default_fps\n grace = self.cfg.grace - 1\n failure = False\n skipped_frames = -1\n else:\n skipped_frames += 1\n states.append([0])\n end = np.NaN\n elapsed_times.append(end - start)\n\n if visualize:\n if len(states[-1]) == 1:\n show_frame(img, anno[f], color=(255, 255, 255)\n if img.shape[2] == 3 else 255)\n else:\n show_frame(img, state, color=(255, 0, 0)\n if img.shape[2] == 3 else 255)\n\n # record results\n self._record('baseline', tracker.name, seq_name, r,\n states, elapsed_times)\n\n def report(self, tracker_names):\n for e in self.cfg.experiments:\n assert e in ('baseline', 'unsupervised', 'realtime')\n if e == 'baseline':\n self.report_baseline(tracker_names)\n elif e == 'unsupervised':\n self.report_unsupervised(tracker_names)\n elif e == 'realtime':\n self.report_realtime(tracker_names)\n\n def report_baseline(self, tracker_names):\n assert isinstance(tracker_names, (list, tuple))\n\n # assume tracker_names[0] is your tracker\n report_dir = os.path.join(\n self.report_dir, tracker_names[0], 'baseline')\n if not os.path.isdir(report_dir):\n os.makedirs(report_dir)\n\n performance = {}\n for name in tracker_names:\n seq_num = len(self.dataset)\n total_len = 0\n ious = []\n failures = []\n\n for s, (_, anno) in enumerate(self.dataset):\n seq_name = self.dataset.seq_names[s]\n total_len += len(anno)\n seq_ious = np.full((15, len(anno)), np.NaN, dtype=float)\n seq_failures = np.full(15, np.NaN, dtype=float)\n\n record_files = sorted(glob.glob(os.path.join(\n self.result_dir, name, 'baseline', seq_name,\n '%s_[0-9]*.txt' % seq_name)))\n\n for r, record_file in enumerate(record_files):\n results = self._read_record(record_file)\n assert(len(results) == len(anno))\n seq_ious[r, :] = self._iou(results, anno)\n seq_failures[r] = self._failure(results, anno)\n\n seq_ious = np.nanmean(seq_ious, axis=0)\n seq_failures[np.isnan(seq_failures)] = np.nanmean(seq_failures)\n\n if len(seq_ious) > 0:\n ious.append(seq_ious)\n if len(seq_failures) > 0:\n failures.append(seq_failures)\n\n failures = np.stack(failures, axis=0)\n failures = failures[~np.isnan(failures[:, 0]), :]\n avg_iou = np.nanmean(np.concatenate(ious))\n avg_failure = np.nanmean(np.sum(failures, axis=0))\n avg_failure_rate = np.nanmean(np.sum(failures, axis=0) / total_len)\n\n performance.update({name: {\n 'accuracy': avg_iou,\n 'failures': avg_failure,\n 'robustness': avg_failure_rate}})\n\n # report the performance\n report_file = os.path.join(report_dir, 'performance.json')\n with open(report_file, 'w') as f:\n json.dump(performance, f, indent=4)\n\n return performance\n\n def report_unsupervised(self, tracker_names):\n assert isinstance(tracker_names, (list, tuple))\n print('Report performance of unsupervised experiment')\n\n # assume tracker_names[0] is your tracker\n report_dir = os.path.join(\n self.report_dir, tracker_names[0], 'unsupervised')\n if not os.path.isdir(report_dir):\n os.makedirs(report_dir)\n\n performance = {}\n for name in tracker_names:\n print('--Processing tracker %s...' % name)\n ious = []\n\n for s, (img_files, anno) in enumerate(self.dataset):\n seq_name = self.dataset.seq_names[s]\n seq_ious = np.full((1, len(anno) - 1), np.NaN, dtype=float)\n bound = cv2.imread(img_files[0]).shape[1::-1]\n\n record_files = sorted(glob.glob(os.path.join(\n self.result_dir, name, 'unsupervised', seq_name,\n '%s_[0-9]*.txt' % seq_name)))\n\n for r, record_file in enumerate(record_files):\n results = self._read_record(record_file)\n assert len(results) == len(anno)\n seq_ious[r] = poly_iou(\n np.asarray(results[1:]), anno[1:], bound)\n\n ious.append(np.nanmean(seq_ious, axis=0))\n\n ious = np.concatenate(ious)\n ious[np.isnan(ious)] = 0\n avg_iou = ious.mean()\n\n performance.update({name: {\n 'avg_iou': avg_iou}})\n\n # report the performance\n report_file = os.path.join(report_dir, 'performance.json')\n with open(report_file, 'w') as f:\n json.dump(performance, f, indent=4)\n\n return performance\n\n def report_realtime(self, tracker_names):\n pass\n\n def _check_deterministic(self, experiment, tracker_name, seq_name):\n record_dir = os.path.join(\n self.result_dir, tracker_name, experiment, seq_name)\n record_files = sorted(glob.glob(os.path.join(\n record_dir, '%s_[0-9]*.txt' % seq_name)))\n if len(record_files) < self.cfg.min_repetitions:\n return False\n\n states = []\n for record_file in record_files:\n with open(record_file, 'r') as f:\n states.append(f.read())\n\n return len(set(states)) == 1\n\n def _record(self, experiment, tracker_name, seq_name, repetition,\n states, elapsed_times):\n record_dir = os.path.join(\n self.result_dir, tracker_name, experiment, seq_name)\n if not os.path.isdir(record_dir):\n os.makedirs(record_dir)\n\n # record states\n record_file = os.path.join(\n record_dir, '%s_%03d.txt' % (seq_name, repetition + 1))\n content = []\n for state in states:\n if len(state) == 1:\n content.append('%d' % state[0])\n else:\n content.append(str.join(',', ['%.3f' % s for s in state]))\n content = str.join('\\n', content)\n with open(record_file, 'w') as f:\n f.write(content)\n\n # record elapsed times\n time_file = os.path.join(record_dir, '%s_time.txt' % seq_name)\n if not os.path.isfile(time_file):\n content = np.zeros((\n len(elapsed_times), self.cfg.repetitions[experiment]))\n if content.ndim == 1:\n content = content[:, np.newaxis]\n else:\n content = np.loadtxt(time_file, delimiter=',')\n content[:, repetition] = elapsed_times\n np.savetxt(time_file, content, fmt='%.6f', delimiter=',')\n\n def _read_record(self, record_file):\n with open(record_file, 'r') as f:\n content = f.read().strip()\n states = [[ast.literal_eval(t) for t in line.split(',')]\n for line in content.split('\\n')]\n\n return states\n\n def _iou(self, results, anno):\n assert len(results) == len(anno)\n burnin = 10\n\n if burnin > 0:\n mask = np.asarray([(len(t) == 1 and t[0] == 1)\n for t in results], dtype=np.uint8)\n se = np.concatenate(\n (np.zeros(burnin - 1), np.ones(burnin))).astype(np.uint8)\n mask = cv2.dilate(mask[::-1], se).squeeze().astype(bool)[::-1]\n else:\n mask = np.zeros(len(results), dtype=bool)\n\n ious = np.full(len(anno), np.NaN, dtype=float)\n for f, state in enumerate(results):\n if not mask[f] and len(state) > 1:\n ious[f] = rect_iou(np.asarray(state), anno[f])\n\n return ious\n\n def _failure(self, results, anno):\n failures = [t for t in results if len(t) == 1 and t[0] == 2]\n\n return len(failures)\n" ]
[ [ "numpy.isnan", "numpy.asarray", "numpy.stack", "numpy.full", "numpy.concatenate", "numpy.ones", "numpy.nanmean", "numpy.savetxt", "numpy.zeros", "numpy.sum", "numpy.loadtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wer010/second.pytorch
[ "cb26f7f4d5a661d14e5b9721958c7b9071612737" ]
[ "second/data/nuscenes/eval/detection/data_classes.py" ]
[ "# nuScenes dev-kit.\n# Code written by Oscar Beijbom, 2019.\n# Licensed under the Creative Commons [see licence.txt]\n\nfrom collections import defaultdict\nfrom typing import List, Dict, Tuple\n\nimport numpy as np\nimport sys\nsys.path.append('/home/lichao/Projects/second.pytorch')\nfrom second.data.nuscenes.eval.detection.constants import DETECTION_NAMES, ATTRIBUTE_NAMES, TP_METRICS\n\n\nclass DetectionConfig:\n \"\"\" Data class that specifies the detection evaluation settings. \"\"\"\n\n def __init__(self,\n class_range: Dict[str, int],\n dist_fcn: str,\n dist_ths: List[float],\n dist_th_tp: float,\n min_recall: float,\n min_precision: float,\n max_boxes_per_sample: float,\n mean_ap_weight: int\n ):\n\n assert set(class_range.keys()) == set(DETECTION_NAMES), \"Class count mismatch.\"\n assert dist_th_tp in dist_ths, \"dist_th_tp must be in set of dist_ths.\"\n\n self.class_range = class_range\n self.dist_fcn = dist_fcn\n self.dist_ths = dist_ths\n self.dist_th_tp = dist_th_tp\n self.min_recall = min_recall\n self.min_precision = min_precision\n self.max_boxes_per_sample = max_boxes_per_sample\n self.mean_ap_weight = mean_ap_weight\n\n self.class_names = self.class_range.keys()\n\n def serialize(self) -> dict:\n \"\"\" Serialize instance into json-friendly format. \"\"\"\n return {\n 'class_range': self.class_range,\n 'dist_fcn': self.dist_fcn,\n 'dist_ths': self.dist_ths,\n 'dist_th_tp': self.dist_th_tp,\n 'min_recall': self.min_recall,\n 'min_precision': self.min_precision,\n 'max_boxes_per_sample': self.max_boxes_per_sample,\n 'mean_ap_weight': self.mean_ap_weight\n }\n\n @classmethod\n def deserialize(cls, content):\n \"\"\" Initialize from serialized dictionary. \"\"\"\n return cls(content['class_range'],\n content['dist_fcn'],\n content['dist_ths'],\n content['dist_th_tp'],\n content['min_recall'],\n content['min_precision'],\n content['max_boxes_per_sample'],\n content['mean_ap_weight'])\n\n\nclass EvalBox:\n \"\"\" Data class used during detection evaluation. Can be a prediction or ground truth.\"\"\"\n\n def __init__(self,\n sample_token: str = \"\",\n translation: Tuple[float, float, float] = (0, 0, 0),\n size: Tuple[float, float, float] = (0, 0, 0),\n rotation: Tuple[float, float, float, float] = (0, 0, 0, 0),\n velocity: Tuple[float, float] = (0, 0),\n detection_name: str = \"car\",\n attribute_name: str = \"\", # Box attribute. Each box can have at most 1 attribute.\n ego_dist: float = 0.0, # Distance to ego vehicle in meters.\n detection_score: float = -1.0, # Only applies to predictions.\n num_pts: int = -1): # Nbr. LIDAR or RADAR inside the box. Only for gt boxes.\n\n # Assert data for shape and NaNs.\n assert type(sample_token) == str\n\n assert len(translation) == 3\n assert not np.any(np.isnan(translation))\n\n assert len(size) == 3\n assert not np.any(np.isnan(size))\n\n assert len(rotation) == 4\n assert not np.any(np.isnan(rotation))\n\n assert len(velocity) == 2 # Velocity can be NaN from our database for certain annotations.\n\n assert detection_name in DETECTION_NAMES\n\n assert attribute_name in ATTRIBUTE_NAMES or attribute_name == ''\n\n assert type(ego_dist) == float\n assert not np.any(np.isnan(ego_dist))\n\n assert type(detection_score) == float\n assert not np.any(np.isnan(detection_score))\n\n assert type(num_pts) == int\n\n assert not np.any(np.isnan(num_pts))\n\n # Assign.\n self.sample_token = sample_token\n self.translation = translation\n self.size = size\n self.rotation = rotation\n self.velocity = velocity\n self.detection_name = detection_name\n self.attribute_name = attribute_name\n self.ego_dist = ego_dist\n self.detection_score = detection_score\n self.num_pts = num_pts\n\n def __repr__(self):\n return str(self.serialize())\n\n def __eq__(self, other):\n return (self.sample_token == other.sample_token and\n self.translation == other.translation and\n self.size == other.size and\n self.rotation == other.rotation and\n self.velocity == other.velocity and\n self.detection_name == other.detection_name and\n self.attribute_name == other.attribute_name and\n self.ego_dist == other.ego_dist and\n self.detection_score == other.detection_score and\n self.num_pts == other.num_pts)\n\n def serialize(self) -> dict:\n \"\"\" Serialize instance into json-friendly format. \"\"\"\n return {\n 'sample_token': self.sample_token,\n 'translation': self.translation,\n 'size': self.size,\n 'rotation': self.rotation,\n 'velocity': self.velocity,\n 'detection_name': self.detection_name,\n 'attribute_name': self.attribute_name,\n 'ego_dist': self.ego_dist,\n 'detection_score': self.detection_score,\n 'num_pts': self.num_pts\n }\n\n @classmethod\n def deserialize(cls, content):\n \"\"\" Initialize from serialized content. \"\"\"\n return cls(sample_token=content['sample_token'],\n translation=tuple(content['translation']),\n size=tuple(content['size']),\n rotation=tuple(content['rotation']),\n velocity=tuple(content['velocity']),\n detection_name=content['detection_name'],\n attribute_name=content['attribute_name'],\n ego_dist=0.0 if 'ego_dist' not in content else float(content['ego_dist']),\n detection_score=-1.0 if 'detection_score' not in content else float(content['detection_score']),\n num_pts=-1 if 'num_pts' not in content else int(content['num_pts']))\n\n\nclass EvalBoxes:\n \"\"\" Data class that groups EvalBox instances by sample. \"\"\"\n\n def __init__(self):\n self.boxes = defaultdict(list)\n\n def __repr__(self):\n return \"EvalBoxes with {} boxes across {} samples\".format(len(self.all), len(self.sample_tokens))\n\n def __getitem__(self, item) -> List[EvalBox]:\n return self.boxes[item]\n\n def __eq__(self, other):\n if not set(self.sample_tokens) == set(other.sample_tokens):\n return False\n ok = True\n for token in self.sample_tokens:\n if not len(self[token]) == len(other[token]):\n return False\n for box1, box2 in zip(self[token], other[token]):\n ok = ok and box1 == box2\n return ok\n\n @property\n def all(self) -> List[EvalBox]:\n \"\"\" Returns all EvalBoxes in a list. \"\"\"\n ab = []\n for sample_token in self.sample_tokens:\n ab.extend(self[sample_token])\n return ab\n\n @property\n def sample_tokens(self) -> List[str]:\n \"\"\" Returns a list of all keys. \"\"\"\n return list(self.boxes.keys())\n\n def add_boxes(self, sample_token: str, boxes: List[EvalBox]) -> None:\n \"\"\" Adds a list of boxes. \"\"\"\n self.boxes[sample_token].extend(boxes)\n\n def serialize(self) -> dict:\n \"\"\" Serialize instance into json-friendly format. \"\"\"\n return {key: [box.serialize() for box in boxes] for key, boxes in self.boxes.items()}\n\n @classmethod\n def deserialize(cls, content):\n \"\"\" Initialize from serialized content. \"\"\"\n eb = cls()\n for sample_token, boxes in content.items():\n eb.add_boxes(sample_token, [EvalBox.deserialize(box) for box in boxes])\n return eb\n\n\nclass MetricData:\n \"\"\" This class holds accumulated and interpolated data required to calculate the metrics. \"\"\"\n\n nelem = 101\n\n def __init__(self,\n recall: np.array,\n precision: np.array,\n confidence: np.array,\n trans_err: np.array,\n vel_err: np.array,\n scale_err: np.array,\n orient_err: np.array,\n attr_err: np.array,\n ):\n\n # Assert lengths\n assert len(recall) == self.nelem\n assert len(precision) == self.nelem\n assert len(confidence) == self.nelem\n assert len(trans_err) == self.nelem\n assert len(vel_err) == self.nelem\n assert len(scale_err) == self.nelem\n assert len(orient_err) == self.nelem\n assert len(attr_err) == self.nelem\n\n # Assert ordering\n assert all(confidence == sorted(confidence, reverse=True)) # Confidences should be descending.\n assert all(recall == sorted(recall)) # Recalls should be ascending.\n\n # Set attributes explicitly to help IDEs figure out what is going on.\n self.recall = recall\n self.precision = precision\n self.confidence = confidence\n self.trans_err = trans_err\n self.vel_err = vel_err\n self.scale_err = scale_err\n self.orient_err = orient_err\n self.attr_err = attr_err\n\n def __eq__(self, other):\n eq = True\n for key in self.serialize().keys():\n eq = eq and np.array_equal(getattr(self, key), getattr(other, key))\n return eq\n\n @property\n def max_recall_ind(self):\n \"\"\" Returns index of max recall achieved. \"\"\"\n\n # Last instance of confidence > 0 is index of max achieved recall.\n non_zero = np.nonzero(self.confidence)[0]\n if len(non_zero) == 0: # If there are no matches, all the confidence values will be zero.\n max_recall_ind = 0\n else:\n max_recall_ind = non_zero[-1]\n\n return max_recall_ind\n\n @property\n def max_recall(self):\n \"\"\" Returns max recall achieved. \"\"\"\n\n return self.recall[self.max_recall_ind]\n\n def serialize(self):\n \"\"\" Serialize instance into json-friendly format. \"\"\"\n return {\n 'recall': self.recall.tolist(),\n 'precision': self.precision.tolist(),\n 'confidence': self.confidence.tolist(),\n 'trans_err': self.trans_err.tolist(),\n 'vel_err': self.vel_err.tolist(),\n 'scale_err': self.scale_err.tolist(),\n 'orient_err': self.orient_err.tolist(),\n 'attr_err': self.attr_err.tolist(),\n }\n\n @classmethod\n def deserialize(cls, content):\n \"\"\" Initialize from serialized content. \"\"\"\n return cls(recall=np.array(content['recall']),\n precision=np.array(content['precision']),\n confidence=np.array(content['confidence']),\n trans_err=np.array(content['trans_err']),\n vel_err=np.array(content['vel_err']),\n scale_err=np.array(content['scale_err']),\n orient_err=np.array(content['orient_err']),\n attr_err=np.array(content['attr_err']))\n\n @classmethod\n def no_predictions(cls):\n \"\"\" Returns a md instance corresponding to having no predictions. \"\"\"\n return cls(recall=np.linspace(0, 1, cls.nelem),\n precision=np.zeros(cls.nelem),\n confidence=np.zeros(cls.nelem),\n trans_err=np.ones(cls.nelem),\n vel_err=np.ones(cls.nelem),\n scale_err=np.ones(cls.nelem),\n orient_err=np.ones(cls.nelem),\n attr_err=np.ones(cls.nelem))\n\n @classmethod\n def random_md(cls):\n return cls(recall=np.linspace(0, 1, cls.nelem),\n precision=np.random.random(cls.nelem),\n confidence=np.linspace(0, 1, cls.nelem)[::-1],\n trans_err=np.random.random(cls.nelem),\n vel_err=np.random.random(cls.nelem),\n scale_err=np.random.random(cls.nelem),\n orient_err=np.random.random(cls.nelem),\n attr_err=np.random.random(cls.nelem))\n\n\nclass MetricDataList:\n \"\"\" This stores a set of MetricData in a dict indexed by (detection-name, match-distance). \"\"\"\n\n def __init__(self):\n self.md = {}\n\n def __getitem__(self, key):\n return self.md[key]\n\n def __eq__(self, other):\n eq = True\n for key in self.md.keys():\n eq = eq and self[key] == other[key]\n return eq\n\n def get_class_data(self, detection_name: str) -> List[Tuple[MetricData, float]]:\n \"\"\" Get all the MetricData entries for a certain detection_name. \"\"\"\n return [(md, dist_th) for (name, dist_th), md in self.md.items() if name == detection_name]\n\n def get_dist_data(self, dist_th: float) -> List[Tuple[MetricData, str]]:\n \"\"\" Get all the MetricData entries for a certain match_distance. \"\"\"\n return [(md, detection_name) for (detection_name, dist), md in self.md.items() if dist == dist_th]\n\n def set(self, detection_name: str, match_distance: float, data: MetricData):\n \"\"\" Sets the MetricData entry for a certain detectdion_name and match_distance. \"\"\"\n self.md[(detection_name, match_distance)] = data\n\n def serialize(self) -> dict:\n return {key[0] + ':' + str(key[1]): value.serialize() for key, value in self.md.items()}\n\n @classmethod\n def deserialize(cls, content):\n mdl = cls()\n for key, md in content.items():\n name, distance = key.split(':')\n mdl.set(name, float(distance), MetricData.deserialize(md))\n return mdl\n\n\nclass DetectionMetrics:\n \"\"\" Stores average precision and true positive metrics. Provides properties to summarize. \"\"\"\n\n def __init__(self, cfg: DetectionConfig):\n\n self.cfg = cfg\n self._label_aps = defaultdict(lambda: defaultdict(float))\n self._label_tp_errors = defaultdict(lambda: defaultdict(float))\n self.eval_time = None\n\n def add_label_ap(self, detection_name: str, dist_th: float, ap: float):\n self._label_aps[detection_name][dist_th] = ap\n\n def get_label_ap(self, detection_name: str, dist_th: float) -> float:\n return self._label_aps[detection_name][dist_th]\n\n def add_label_tp(self, detection_name: str, metric_name: str, tp: float):\n self._label_tp_errors[detection_name][metric_name] = tp\n\n def get_label_tp(self, detection_name: str, metric_name: str) -> float:\n return self._label_tp_errors[detection_name][metric_name]\n\n def add_runtime(self, eval_time: float):\n self.eval_time = eval_time\n\n @property\n def mean_dist_aps(self) -> Dict[str, float]:\n \"\"\" Calculates the mean over distance thresholds for each label. \"\"\"\n return {class_name: np.mean(list(d.values())) for class_name, d in self._label_aps.items()}\n\n @property\n def mean_ap(self) -> float:\n \"\"\" Calculates the mean AP by averaging over distance thresholds and classes. \"\"\"\n return float(np.mean(list(self.mean_dist_aps.values())))\n\n @property\n def tp_errors(self) -> Dict[str, float]:\n \"\"\" Calculates the mean true positive error across all classes for each metric. \"\"\"\n errors = {}\n for metric_name in TP_METRICS:\n class_errors = []\n for detection_name in self.cfg.class_names:\n\n class_errors.append(self.get_label_tp(detection_name, metric_name))\n\n errors[metric_name] = float(np.nanmean(class_errors))\n\n return errors\n\n @property\n def tp_scores(self) -> Dict[str, float]:\n scores = {}\n tp_errors = self.tp_errors\n for metric_name in TP_METRICS:\n\n # We convert the true positive errors to \"scores\" by 1-error.\n score = 1.0 - tp_errors[metric_name]\n\n # Some of the true positive errors are unbounded, so we bound the scores to min 0.\n score = max(0.0, score)\n\n scores[metric_name] = score\n\n return scores\n\n @property\n def nd_score(self) -> float:\n \"\"\"\n Compute the nuTonomy detection score (NDS, weighted sum of the individual scores).\n :return: The NDS.\n \"\"\"\n\n # Summarize.\n total = float(self.cfg.mean_ap_weight * self.mean_ap + np.sum(list(self.tp_scores.values())))\n\n # Normalize.\n total = total / float(self.cfg.mean_ap_weight + len(self.tp_scores.keys()))\n\n return total\n\n def serialize(self):\n return {'label_aps': self._label_aps,\n 'mean_dist_aps': self.mean_dist_aps,\n 'mean_ap': self.mean_ap,\n 'label_tp_errors': self._label_tp_errors,\n 'tp_errors': self.tp_errors,\n 'tp_scores': self.tp_scores,\n 'nd_score': self.nd_score,\n 'eval_time': self.eval_time}\n" ]
[ [ "numpy.random.random", "numpy.nonzero", "numpy.linspace", "numpy.isnan", "numpy.ones", "numpy.nanmean", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shagunsodhani/pytorch_sparse
[ "2984f28815c90dd5bae09aa6fdacf1c8a149eb9a" ]
[ "test/test_spspmm.py" ]
[ "from itertools import product\n\nimport pytest\nimport torch\nfrom torch_sparse import spspmm\n\nfrom .utils import dtypes, devices, tensor\n\n\[email protected]('dtype,device', product(dtypes, devices))\ndef test_spspmm(dtype, device):\n indexA = torch.tensor([[0, 0, 1, 2, 2], [1, 2, 0, 0, 1]], device=device)\n valueA = tensor([1, 2, 3, 4, 5], dtype, device)\n sizeA = torch.Size([3, 3])\n indexB = torch.tensor([[0, 2], [1, 0]], device=device)\n valueB = tensor([2, 4], dtype, device)\n sizeB = torch.Size([3, 2])\n\n indexC, valueC = spspmm(indexA, valueA, indexB, valueB, 3, 3, 2)\n assert indexC.tolist() == [[0, 1, 2], [0, 1, 1]]\n assert valueC.tolist() == [8, 6, 8]\n\n A = torch.sparse_coo_tensor(indexA, valueA, sizeA, device=device)\n A = A.to_dense().requires_grad_()\n B = torch.sparse_coo_tensor(indexB, valueB, sizeB, device=device)\n B = B.to_dense().requires_grad_()\n torch.matmul(A, B).sum().backward()\n\n valueA = valueA.requires_grad_()\n valueB = valueB.requires_grad_()\n indexC, valueC = spspmm(indexA, valueA, indexB, valueB, 3, 3, 2)\n valueC.sum().backward()\n\n assert valueA.grad.tolist() == A.grad[indexA[0], indexA[1]].tolist()\n assert valueB.grad.tolist() == B.grad[indexB[0], indexB[1]].tolist()\n" ]
[ [ "torch.sparse_coo_tensor", "torch.matmul", "torch.Size", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
covid19-specialist/ssd.pytorch
[ "acafba6e42896f1814d3d7f6807d0ce478715fbb" ]
[ "test.py" ]
[ "from __future__ import print_function\nimport sys\nimport os\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nimport torchvision.transforms as transforms\n# from torch.autograd import Variable\nfrom data import WHEAT_ROOT, WHEAT_CLASSES\nfrom PIL import Image\nfrom data import WHEATAnnotationTransform, WHEATDetection, BaseTransform, WHEAT_CLASSES, rev_label_map as labelmap\nimport torch.utils.data as data\nfrom ssd import build_ssd\n\nparser = argparse.ArgumentParser(description='Single Shot MultiBox Detection')\nparser.add_argument('--trained_model', default='weights/ssd_300_VOC0712.pth',\n type=str, help='Trained state_dict file path to open')\nparser.add_argument('--save_folder', default='eval/', type=str,\n help='Dir to save results')\nparser.add_argument('--visual_threshold', default=0.6, type=float,\n help='Final confidence threshold')\nparser.add_argument('--cuda', default=True, type=bool,\n help='Use cuda to train model')\nparser.add_argument('--wheat_root', default=WHEAT_ROOT, help='Location of VOC root directory')\nparser.add_argument('-f', default=None, type=str, help=\"Dummy arg so we can load in Jupyter Notebooks\")\nargs = parser.parse_args()\n\n# args = dict()\n# args['trained_model'] = 'weights/ssd300_mAP_77.43_v2.pth'\n# args['save_folder'] = 'eval/'\n# args['visual_threshold'] = 0.6\n# args['cuda'] = True\n# args['wheat_root'] = WHEAT_ROOT\n# args['f'] = None\n\nif args.cuda and torch.cuda.is_available():\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\nelse:\n torch.set_default_tensor_type('torch.FloatTensor')\n\nif not os.path.exists(args.save_folder):\n os.mkdir(args.save_folder)\n\n\ndef test_net(save_folder, net, cuda, testset, transform, thresh):\n # dump predictions and assoc. ground truth to text file for now\n filename = save_folder+'test1.txt'\n num_images = len(testset)\n for i in range(num_images):\n print('Testing image {:d}/{:d}....'.format(i+1, num_images))\n img = testset.pull_image(i)\n img_id, annotation = testset.pull_anno(i)\n x = torch.from_numpy(transform(img)[0]).permute(2, 0, 1)\n #handbook\n# x = Variable(x.unsqueeze(0))\n x = x.unsqueeze(0)\n #handbook\n\n with open(filename, mode='a') as f:\n f.write('\\nGROUND TRUTH FOR: '+img_id+'\\n')\n for box in annotation:\n f.write('label: '+' || '.join(str(b) for b in box)+'\\n')\n if cuda:\n #handbook\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n# x = x.cuda()\n x = x.to(device)\n\n with torch.no_grad():\n y = net(x) # forward pass\n \n detections = y.data\n # scale each detection back up to the image\n scale = torch.Tensor([img.shape[1], img.shape[0],\n img.shape[1], img.shape[0]])\n pred_num = 0\n for i in range(1, detections.size(1)):\n j = 0\n while detections[0, i, j, 0] >= 0.6:\n if pred_num == 0:\n with open(filename, mode='a') as f:\n f.write('PREDICTIONS: '+'\\n')\n score = detections[0, i, j, 0]\n label_name = labelmap[i]\n pt = (detections[0, i, j, 1:]*scale).cpu().numpy()\n coords = (pt[0], pt[1], pt[2], pt[3])\n pred_num += 1\n with open(filename, mode='a') as f:\n f.write(str(pred_num)+' label: '+label_name+' score: ' +\n str(score) + ' '+' || '.join(str(c) for c in coords) + '\\n')\n j += 1\n\n\ndef test_wheat():\n # load net\n num_classes = len(labelmap) + 1 # +1 background\n ssd_net = build_ssd('test', 300, num_classes) # initialize SSD\n \n if args.cuda:\n #handbook\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n# net = net.cuda()\n net = ssd_net.to(device)\n cudnn.benchmark = True\n \n net.load_weights(args.trained_model)\n net.eval()\n print('Finished loading model!')\n \n # load data\n testset = WHEATDetection(args.wheat_root, 'test', None, WHEATAnnotationTransform())\n \n # evaluation\n test_net(args.save_folder, net, args.cuda, testset,\n BaseTransform(net.size, (104, 117, 123)),\n thresh=args.visual_threshold)\n\nif __name__ == '__main__':\n test_wheat()\n" ]
[ [ "torch.set_default_tensor_type", "torch.Tensor", "torch.no_grad", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ParikhKadam/pytorch3d
[ "5cd70067e2ba642d98fd36e8e31273366d1599cb", "5cd70067e2ba642d98fd36e8e31273366d1599cb" ]
[ "tests/test_cubify.py", "tests/test_acos_linear_extrapolation.py" ]
[ "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport unittest\n\nimport torch\nfrom pytorch3d.ops import cubify\n\nfrom .common_testing import TestCaseMixin\n\n\nclass TestCubify(TestCaseMixin, unittest.TestCase):\n def test_allempty(self):\n N, V = 32, 14\n device = torch.device(\"cuda:0\")\n voxels = torch.zeros((N, V, V, V), dtype=torch.float32, device=device)\n meshes = cubify(voxels, 0.5)\n self.assertTrue(meshes.isempty())\n\n def test_cubify(self):\n N, V = 4, 2\n device = torch.device(\"cuda:0\")\n voxels = torch.zeros((N, V, V, V), dtype=torch.float32, device=device)\n\n # 1st example: (top left corner, znear) is on\n voxels[0, 0, 0, 0] = 1.0\n # 2nd example: all are on\n voxels[1] = 1.0\n # 3rd example: empty\n # 4th example\n voxels[3, :, :, 1] = 1.0\n voxels[3, 1, 1, 0] = 1.0\n\n # compute cubify\n meshes = cubify(voxels, 0.5)\n\n # 1st-check\n verts, faces = meshes.get_mesh_verts_faces(0)\n self.assertClose(faces.max().cpu(), torch.tensor(verts.size(0) - 1))\n self.assertClose(\n verts,\n torch.tensor(\n [\n [-1.0, -1.0, -1.0],\n [-1.0, -1.0, 1.0],\n [1.0, -1.0, -1.0],\n [1.0, -1.0, 1.0],\n [-1.0, 1.0, -1.0],\n [-1.0, 1.0, 1.0],\n [1.0, 1.0, -1.0],\n [1.0, 1.0, 1.0],\n ],\n dtype=torch.float32,\n device=device,\n ),\n )\n self.assertClose(\n faces,\n torch.tensor(\n [\n [0, 1, 4],\n [1, 5, 4],\n [4, 5, 6],\n [5, 7, 6],\n [0, 4, 6],\n [0, 6, 2],\n [0, 3, 1],\n [0, 2, 3],\n [6, 7, 3],\n [6, 3, 2],\n [1, 7, 5],\n [1, 3, 7],\n ],\n dtype=torch.int64,\n device=device,\n ),\n )\n # 2nd-check\n verts, faces = meshes.get_mesh_verts_faces(1)\n self.assertClose(faces.max().cpu(), torch.tensor(verts.size(0) - 1))\n self.assertClose(\n verts,\n torch.tensor(\n [\n [-1.0, -1.0, -1.0],\n [-1.0, -1.0, 1.0],\n [-1.0, -1.0, 3.0],\n [1.0, -1.0, -1.0],\n [1.0, -1.0, 1.0],\n [1.0, -1.0, 3.0],\n [3.0, -1.0, -1.0],\n [3.0, -1.0, 1.0],\n [3.0, -1.0, 3.0],\n [-1.0, 1.0, -1.0],\n [-1.0, 1.0, 1.0],\n [-1.0, 1.0, 3.0],\n [1.0, 1.0, -1.0],\n [1.0, 1.0, 3.0],\n [3.0, 1.0, -1.0],\n [3.0, 1.0, 1.0],\n [3.0, 1.0, 3.0],\n [-1.0, 3.0, -1.0],\n [-1.0, 3.0, 1.0],\n [-1.0, 3.0, 3.0],\n [1.0, 3.0, -1.0],\n [1.0, 3.0, 1.0],\n [1.0, 3.0, 3.0],\n [3.0, 3.0, -1.0],\n [3.0, 3.0, 1.0],\n [3.0, 3.0, 3.0],\n ],\n dtype=torch.float32,\n device=device,\n ),\n )\n self.assertClose(\n faces,\n torch.tensor(\n [\n [0, 1, 9],\n [1, 10, 9],\n [0, 9, 12],\n [0, 12, 3],\n [0, 4, 1],\n [0, 3, 4],\n [1, 2, 10],\n [2, 11, 10],\n [1, 5, 2],\n [1, 4, 5],\n [2, 13, 11],\n [2, 5, 13],\n [3, 12, 14],\n [3, 14, 6],\n [3, 7, 4],\n [3, 6, 7],\n [14, 15, 7],\n [14, 7, 6],\n [4, 8, 5],\n [4, 7, 8],\n [15, 16, 8],\n [15, 8, 7],\n [5, 16, 13],\n [5, 8, 16],\n [9, 10, 17],\n [10, 18, 17],\n [17, 18, 20],\n [18, 21, 20],\n [9, 17, 20],\n [9, 20, 12],\n [10, 11, 18],\n [11, 19, 18],\n [18, 19, 21],\n [19, 22, 21],\n [11, 22, 19],\n [11, 13, 22],\n [20, 21, 23],\n [21, 24, 23],\n [12, 20, 23],\n [12, 23, 14],\n [23, 24, 15],\n [23, 15, 14],\n [21, 22, 24],\n [22, 25, 24],\n [24, 25, 16],\n [24, 16, 15],\n [13, 25, 22],\n [13, 16, 25],\n ],\n dtype=torch.int64,\n device=device,\n ),\n )\n\n # 3rd-check\n verts, faces = meshes.get_mesh_verts_faces(2)\n self.assertTrue(verts.size(0) == 0)\n self.assertTrue(faces.size(0) == 0)\n\n # 4th-check\n verts, faces = meshes.get_mesh_verts_faces(3)\n self.assertClose(\n verts,\n torch.tensor(\n [\n [1.0, -1.0, -1.0],\n [1.0, -1.0, 1.0],\n [1.0, -1.0, 3.0],\n [3.0, -1.0, -1.0],\n [3.0, -1.0, 1.0],\n [3.0, -1.0, 3.0],\n [-1.0, 1.0, 1.0],\n [-1.0, 1.0, 3.0],\n [1.0, 1.0, -1.0],\n [1.0, 1.0, 1.0],\n [1.0, 1.0, 3.0],\n [3.0, 1.0, -1.0],\n [3.0, 1.0, 1.0],\n [3.0, 1.0, 3.0],\n [-1.0, 3.0, 1.0],\n [-1.0, 3.0, 3.0],\n [1.0, 3.0, -1.0],\n [1.0, 3.0, 1.0],\n [1.0, 3.0, 3.0],\n [3.0, 3.0, -1.0],\n [3.0, 3.0, 1.0],\n [3.0, 3.0, 3.0],\n ],\n dtype=torch.float32,\n device=device,\n ),\n )\n self.assertClose(\n faces,\n torch.tensor(\n [\n [0, 1, 8],\n [1, 9, 8],\n [0, 8, 11],\n [0, 11, 3],\n [0, 4, 1],\n [0, 3, 4],\n [11, 12, 4],\n [11, 4, 3],\n [1, 2, 9],\n [2, 10, 9],\n [1, 5, 2],\n [1, 4, 5],\n [12, 13, 5],\n [12, 5, 4],\n [2, 13, 10],\n [2, 5, 13],\n [6, 7, 14],\n [7, 15, 14],\n [14, 15, 17],\n [15, 18, 17],\n [6, 14, 17],\n [6, 17, 9],\n [6, 10, 7],\n [6, 9, 10],\n [7, 18, 15],\n [7, 10, 18],\n [8, 9, 16],\n [9, 17, 16],\n [16, 17, 19],\n [17, 20, 19],\n [8, 16, 19],\n [8, 19, 11],\n [19, 20, 12],\n [19, 12, 11],\n [17, 18, 20],\n [18, 21, 20],\n [20, 21, 13],\n [20, 13, 12],\n [10, 21, 18],\n [10, 13, 21],\n ],\n dtype=torch.int64,\n device=device,\n ),\n )\n\n def test_align(self):\n N, V = 1, 2\n device = torch.device(\"cuda:0\")\n voxels = torch.ones((N, V, V, V), dtype=torch.float32, device=device)\n\n # topleft align\n mesh = cubify(voxels, 0.5)\n verts, faces = mesh.get_mesh_verts_faces(0)\n self.assertClose(verts.min(), torch.tensor(-1.0, device=device))\n self.assertClose(verts.max(), torch.tensor(3.0, device=device))\n\n # corner align\n mesh = cubify(voxels, 0.5, align=\"corner\")\n verts, faces = mesh.get_mesh_verts_faces(0)\n self.assertClose(verts.min(), torch.tensor(-1.0, device=device))\n self.assertClose(verts.max(), torch.tensor(1.0, device=device))\n\n # center align\n mesh = cubify(voxels, 0.5, align=\"center\")\n verts, faces = mesh.get_mesh_verts_faces(0)\n self.assertClose(verts.min(), torch.tensor(-2.0, device=device))\n self.assertClose(verts.max(), torch.tensor(2.0, device=device))\n\n # invalid align\n with self.assertRaisesRegex(ValueError, \"Align mode must be one of\"):\n cubify(voxels, 0.5, align=\"\")\n\n # invalid align\n with self.assertRaisesRegex(ValueError, \"Align mode must be one of\"):\n cubify(voxels, 0.5, align=\"topright\")\n\n # inside occupancy, similar to GH#185 use case\n N, V = 1, 4\n voxels = torch.zeros((N, V, V, V), dtype=torch.float32, device=device)\n voxels[0, : V // 2, : V // 2, : V // 2] = 1.0\n mesh = cubify(voxels, 0.5, align=\"corner\")\n verts, faces = mesh.get_mesh_verts_faces(0)\n self.assertClose(verts.min(), torch.tensor(-1.0, device=device))\n self.assertClose(verts.max(), torch.tensor(0.0, device=device))\n\n @staticmethod\n def cubify_with_init(batch_size: int, V: int):\n device = torch.device(\"cuda:0\")\n voxels = torch.rand((batch_size, V, V, V), dtype=torch.float32, device=device)\n torch.cuda.synchronize()\n\n def convert():\n cubify(voxels, 0.5)\n torch.cuda.synchronize()\n\n return convert\n", "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\n\nimport unittest\n\nimport numpy as np\nimport torch\nfrom pytorch3d.common.compat import lstsq\nfrom pytorch3d.transforms import acos_linear_extrapolation\n\nfrom .common_testing import TestCaseMixin\n\n\nclass TestAcosLinearExtrapolation(TestCaseMixin, unittest.TestCase):\n def setUp(self) -> None:\n super().setUp()\n torch.manual_seed(42)\n np.random.seed(42)\n\n @staticmethod\n def init_acos_boundary_values(batch_size: int = 10000):\n \"\"\"\n Initialize a tensor containing values close to the bounds of the\n domain of `acos`, i.e. close to -1 or 1; and random values between (-1, 1).\n \"\"\"\n device = torch.device(\"cuda:0\")\n # one quarter are random values between -1 and 1\n x_rand = 2 * torch.rand(batch_size // 4, dtype=torch.float32, device=device) - 1\n x = [x_rand]\n for bound in [-1, 1]:\n for above_bound in [True, False]:\n for noise_std in [1e-4, 1e-2]:\n n_generate = (batch_size - batch_size // 4) // 8\n x_add = (\n bound\n + (2 * float(above_bound) - 1)\n * torch.randn(\n n_generate, device=device, dtype=torch.float32\n ).abs()\n * noise_std\n )\n x.append(x_add)\n x = torch.cat(x)\n return x\n\n @staticmethod\n def acos_linear_extrapolation(batch_size: int):\n x = TestAcosLinearExtrapolation.init_acos_boundary_values(batch_size)\n torch.cuda.synchronize()\n\n def compute_acos():\n acos_linear_extrapolation(x)\n torch.cuda.synchronize()\n\n return compute_acos\n\n def _test_acos_outside_bounds(self, x, y, dydx, bound):\n \"\"\"\n Check that `acos_linear_extrapolation` yields points on a line with correct\n slope, and that the function is continuous around `bound`.\n \"\"\"\n bound_t = torch.tensor(bound, device=x.device, dtype=x.dtype)\n # fit a line: slope * x + bias = y\n x_1 = torch.stack([x, torch.ones_like(x)], dim=-1)\n slope, bias = lstsq(x_1, y[:, None]).view(-1)[:2]\n desired_slope = (-1.0) / torch.sqrt(1.0 - bound_t**2)\n # test that the desired slope is the same as the fitted one\n self.assertClose(desired_slope.view(1), slope.view(1), atol=1e-2)\n # test that the autograd's slope is the same as the desired one\n self.assertClose(desired_slope.expand_as(dydx), dydx, atol=1e-2)\n # test that the value of the fitted line at x=bound equals\n # arccos(x), i.e. the function is continuous around the bound\n y_bound_lin = (slope * bound_t + bias).view(1)\n y_bound_acos = bound_t.acos().view(1)\n self.assertClose(y_bound_lin, y_bound_acos, atol=1e-2)\n\n def _one_acos_test(self, x: torch.Tensor, lower_bound: float, upper_bound: float):\n \"\"\"\n Test that `acos_linear_extrapolation` returns correct values for\n `x` between/above/below `lower_bound`/`upper_bound`.\n \"\"\"\n x.requires_grad = True\n x.grad = None\n y = acos_linear_extrapolation(x, [lower_bound, upper_bound])\n # compute the gradient of the acos w.r.t. x\n y.backward(torch.ones_like(y))\n dacos_dx = x.grad\n x_lower = x <= lower_bound\n x_upper = x >= upper_bound\n x_mid = (~x_lower) & (~x_upper)\n # test that between bounds, the function returns plain acos\n self.assertClose(x[x_mid].acos(), y[x_mid])\n # test that outside the bounds, the function is linear with the right\n # slope and continuous around the bound\n self._test_acos_outside_bounds(\n x[x_upper], y[x_upper], dacos_dx[x_upper], upper_bound\n )\n self._test_acos_outside_bounds(\n x[x_lower], y[x_lower], dacos_dx[x_lower], lower_bound\n )\n\n def test_acos(self, batch_size: int = 10000):\n \"\"\"\n Tests whether the function returns correct outputs\n inside/outside the bounds.\n \"\"\"\n x = TestAcosLinearExtrapolation.init_acos_boundary_values(batch_size)\n bounds = 1 - 10.0 ** torch.linspace(-1, -5, 5)\n for lower_bound in -bounds:\n for upper_bound in bounds:\n if upper_bound < lower_bound:\n continue\n self._one_acos_test(x, float(lower_bound), float(upper_bound))\n\n def test_finite_gradient(self, batch_size: int = 10000):\n \"\"\"\n Tests whether gradients stay finite close to the bounds.\n \"\"\"\n x = TestAcosLinearExtrapolation.init_acos_boundary_values(batch_size)\n x.requires_grad = True\n bounds = 1 - 10.0 ** torch.linspace(-1, -5, 5)\n for lower_bound in -bounds:\n for upper_bound in bounds:\n if upper_bound < lower_bound:\n continue\n x.grad = None\n y = acos_linear_extrapolation(\n x,\n [float(lower_bound), float(upper_bound)],\n )\n self.assertTrue(torch.isfinite(y).all())\n loss = y.mean()\n loss.backward()\n self.assertIsNotNone(x.grad)\n self.assertTrue(torch.isfinite(x.grad).all())\n" ]
[ [ "torch.cuda.synchronize", "torch.ones", "torch.zeros", "torch.tensor", "torch.rand", "torch.device" ], [ "torch.cuda.synchronize", "torch.linspace", "numpy.random.seed", "torch.cat", "torch.sqrt", "torch.manual_seed", "torch.randn", "torch.tensor", "torch.isfinite", "torch.rand", "torch.device", "torch.ones_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
linea-it/tno_astrometry
[ "4d48e979937e2106da598dc0b2d53152b09a7002" ]
[ "praia_target.py" ]
[ "from astropy.utils import iers\nfrom astropy.time import Time\nfrom astropy.coordinates import GCRS, EarthLocation\nimport os\nimport subprocess\n\nimport numpy as np\nimport spiceypy as spice\n# Deligar o auto Download do Finals2000\n# https://docs.astropy.org/en/stable/utils/iers.html#working-offline\niers.conf.auto_download = False\n\n\npraia_target_params = 'praia_target.dat'\ntargets_file = 'targets.txt'\ntargets_offset_file = 'target_offset.txt'\n\n\ndef findIDSPK(n, key):\n loc = 2 # order setting bsp files (1=DEXXX.bsp, 2=Ast.bsp)\n m, header, flag = spice.dafec(loc, n)\n spk = ''\n for row in header:\n if row[:len(key)] == key:\n spk = row[len(key):].strip()\n return spk\n\n\ndef ra2HMS(radeg='', ndecimals=0):\n raH = int(radeg)\n raM = int((radeg - raH)*60)\n raS = 60*((radeg - raH)*60 - raM)\n style = '{:02d} {:02d} {:0' + \\\n str(ndecimals+3) + '.' + str(ndecimals) + 'f}'\n RA = style.format(raH, raM, raS)\n return RA\n\n\ndef dec2DMS(decdeg='', ndecimals=0):\n ds = '+'\n if decdeg < 0:\n ds, decdeg = '-', abs(decdeg)\n deg = int(decdeg)\n decM = abs(int((decdeg - deg)*60))\n decS = 60*(abs((decdeg - deg)*60) - decM)\n style = '{}{:02d} {:02d} {:0' + \\\n str(ndecimals+3) + '.' + str(ndecimals) + 'f}'\n DEC = style.format(ds, deg, decM, decS)\n return DEC\n\n\ndef geoTopoVector(longitude, latitude, elevation, jd):\n\n loc = EarthLocation(longitude, latitude, elevation)\n\n time = Time(jd, scale='utc', format='jd')\n itrs = loc.get_itrs(obstime=time)\n gcrs = itrs.transform_to(GCRS(obstime=time))\n\n r = gcrs.cartesian\n\n # convert from m to km\n x = r.x.value/1000.0\n y = r.y.value/1000.0\n z = r.z.value/1000.0\n\n return x, y, z\n\n\ndef create_targets_file(name, dates, bsp_object, bsp_planets, leap_Sec, location):\n # Load the asteroid and planetary ephemeris and the leap second (in order)\n spice.furnsh(bsp_planets)\n spice.furnsh(leap_Sec)\n spice.furnsh(bsp_object)\n\n # Values specific for extract all comments of header from bsp files (JPL, NIMA)\n source = {'NIMA': (45, 'ASTEROID_SPK_ID ='),\n 'JPL': (74, 'Target SPK ID :')}\n n, key = source['NIMA']\n idspk = findIDSPK(n, key)\n if idspk == '':\n n, key = source['JPL']\n idspk = findIDSPK(n, key)\n\n # Convert dates from JD to et format. \"JD\" is added due to spice requirement\n datesET = [spice.utc2et(jd + \" JD\") for jd in dates]\n\n # Compute geocentric positions (x,y,z) for each date with light time correction\n rAst, ltAst = spice.spkpos(idspk, datesET, 'J2000', 'LT', 'EARTH')\n\n # Location\n lon, lat, ele = location[0], location[1], location[2]\n\n # Create targets file\n output = os.path.join(os.getenv(\"DATA_DIR\"), targets_file)\n with open(output, 'w') as outFile:\n for i, r_geo in enumerate(rAst):\n # Convert from longitude, latitude, elevation to r(x,y,z)\n r = geoTopoVector(lon, lat, ele, float(dates[i]))\n\n #r_topo = r_geo - r\n r_topo = [r_geo[0]-r[0], r_geo[1]-r[1], r_geo[2]-r[2]]\n\n # Convert rectangular coordinates (x,y,z) to range, right ascension, and declination.\n d, rarad, decrad = spice.recrad(r_topo)\n\n # Transform RA and Decl. from radians to degrees and then to hexadecimal format.\n ra = ra2HMS(np.degrees(rarad)/15.0, 6)\n dec = dec2DMS(np.degrees(decrad), 5)\n\n # Save parameters in specific format\n outFile.write(\" \" + ra + \" \" + dec + \" \" +\n dates[i] + \" \" + name + \"\\n\")\n\n outFile.close()\n\n return output\n\n\ndef create_params_file(praia_astrometry_output, targets, targets_offset):\n\n with open(os.path.join(os.getenv(\"APP_PATH\"), \"src/praia_target.template.dat\")) as template:\n\n data = template.read()\n data = data.replace('{PRAIA_ASTROMETRY_OUTPUT}',\n praia_astrometry_output.ljust(50))\n data = data.replace('{TARGET_FILE}', targets.ljust(50))\n data = data.replace('{TARGET_OFFSET_FILE}', targets_offset.ljust(50))\n\n params_file = os.path.join(os.getenv(\"DATA_DIR\"), praia_target_params)\n with open(params_file, 'w') as new_file:\n new_file.write(data)\n new_file.close()\n\n template.close()\n\n return params_file\n\n\ndef run_praia_target(praia_astrometry_output, targets):\n\n targets_offset = os.path.join(os.getenv(\"DATA_DIR\"), targets_offset_file)\n\n params_file = create_params_file(\n praia_astrometry_output, targets, targets_offset)\n\n praia_target = os.getenv(\"PRAIA_TARGET\")\n\n exec_log = os.path.join(os.getenv(\"DATA_DIR\"), \"praia_target.log\")\n\n with open(exec_log, 'w') as fp:\n process = subprocess.Popen([\"%s < %s\" % (praia_target, params_file)],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n\n out, error = process.communicate()\n\n fp.write(out.decode(\"utf-8\"))\n fp.write(error.decode(\"utf-8\"))\n\n if process.returncode > 0:\n raise Exception(\"Failed to run PRAIA Target. \\n\" +\n error.decode(\"utf-8\"))\n\n return targets_offset\n\n\ndef create_obs_file(targets_offset, asteroid, obs_code, cat_code):\n mag, ra, dec, jd = np.loadtxt(targets_offset, usecols=(\n 10, 35, 36, 43), ndmin=2, unpack=True)\n\n raHMS = [ra2HMS(alpha) for alpha in ra]\n decDMS = [dec2DMS(delta) for delta in dec]\n\n output = os.path.join(os.getenv(\"DATA_DIR\"), \"%s.txt\" % asteroid)\n\n with open(output, 'w') as outFile:\n for i in range(len(mag)):\n outFile.write(ra2HMS(ra[i], 4) + \" \")\n outFile.write(dec2DMS(dec[i], 3) + \" \")\n outFile.write('{:06.3f}'.format(mag[i]) + \" \")\n outFile.write('{:016.8f}'.format(jd[i]) + \" \")\n outFile.write(obs_code + \" \")\n outFile.write(cat_code + \"\\n\")\n\n outFile.close()\n\n return output\n" ]
[ [ "numpy.degrees", "numpy.loadtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
specialforcea/labscript_suite
[ "a4ad5255207cced671990fff94647b1625aa0049" ]
[ "userlib/analysislib/paco_analysis/common/get_raw_images.py" ]
[ "import h5py\nimport numpy as np\n\ndef get_raw_images(fpath):\n with h5py.File(fpath) as h5_file:\n if '/data/imagesYZ_2_Flea3' in h5_file:\n image_group = 'imagesYZ_2_Flea3'\n if '/data/imagesXY_1_Flea3' in h5_file:\n image_group = 'imagesXY_1_Flea3'\n if False: #'/data/imagesXY_2_Flea3' in h5_file:\n image_group = 'imagesXY_2_Flea3'\n if '/data/imagesYZ_1_Flea3' in h5_file:\n image_group = 'imagesYZ_1_Flea3'\n atoms = np.array(h5_file['data'][image_group]['Raw'])[0]\n probe = np.array(h5_file['data'][image_group]['Raw'])[1]\n bckg = np.array(h5_file['data'][image_group]['Raw'])[2]\n return atoms, probe, bckg" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SJTU-Thinklab-Det/DOTA-DOAI
[ "eb252da4a32c5b961720a129266881c848659263" ]
[ "FPN_Tensorflow_Rotation/libs/configs/DOTA1.0/cfgs_dota1.0_res152_v1.py" ]
[ "# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, absolute_import\nimport os\nimport tensorflow as tf\n\n\"\"\"\nres152D_freezeC1C2_rmaskP2_Concat_800train_augMS_8conv_CTX\n\nThis is your result for task 1:\n\n mAP: 0.7898724310364561\n ap of each class:\n plane:0.9006183729548372,\n baseball-diamond:0.84372788104372,\n bridge:0.567618431335344,\n ground-track-field:0.758221344745048,\n small-vehicle:0.7932960821323363,\n large-vehicle:0.7450420960292438,\n ship:0.8650554150856641,\n tennis-court:0.907718083481144,\n basketball-court:0.8850621616004604,\n storage-tank:0.8684151065606698,\n soccer-ball-field:0.6960451226690271,\n roundabout:0.690465622928499,\n harbor:0.761470680192509,\n swimming-pool:0.7992065528123767,\n helicopter:0.766123511975963\n\nThe submitted information is :\n\nDescription: FPN_Res152D_DOTA1.0_20191106_v1_120w_ms\nUsername: DetectionTeamCSU\nInstitute: CSU\nEmailadress: [email protected]\nTeamMembers: YangXue\n\n\n\"\"\"\n\n# ------------------------------------------------\nVERSION = 'FPN_Res152D_DOTA1.0_20191106_v1'\nNET_NAME = 'resnet152_v1d'\nADD_BOX_IN_TENSORBOARD = True\n\n# ---------------------------------------- System_config\nROOT_PATH = os.path.abspath('../')\nprint (20*\"++--\")\nprint (ROOT_PATH)\nGPU_GROUP = \"0,1\"\nNUM_GPU = len(GPU_GROUP.strip().split(','))\nSHOW_TRAIN_INFO_INTE = 50\nSMRY_ITER = 2000\nSAVE_WEIGHTS_INTE = 30000 * 2\n\nSUMMARY_PATH = ROOT_PATH + '/output/summary'\nTEST_SAVE_PATH = ROOT_PATH + '/tools/test_result'\n\nif NET_NAME.startswith(\"resnet\"):\n weights_name = NET_NAME\nelif NET_NAME.startswith(\"MobilenetV2\"):\n weights_name = \"mobilenet/mobilenet_v2_1.0_224\"\nelse:\n raise Exception('net name must in [resnet_v1_101, resnet_v1_50, MobilenetV2]')\n\nPRETRAINED_CKPT = ROOT_PATH + '/data/pretrained_weights/' + weights_name + '.ckpt'\nTRAINED_CKPT = os.path.join(ROOT_PATH, 'output/trained_weights')\nEVALUATE_DIR = ROOT_PATH + '/output/evaluate_result_pickle/'\n\n# ------------------------------------------ Train config\nRESTORE_FROM_RPN = False\nIS_FILTER_OUTSIDE_BOXES = False\nFREEZE_BLOCKS = [True, True, False, False, False] # for gluoncv backbone\nFIXED_BLOCKS = 0 # allow 0~3\nUSE_07_METRIC = True\nCUDA9 = True\n\nRPN_LOCATION_LOSS_WEIGHT = 1.\nRPN_CLASSIFICATION_LOSS_WEIGHT = 1.0\nFAST_RCNN_LOCATION_LOSS_WEIGHT = 1.0\nFAST_RCNN_CLASSIFICATION_LOSS_WEIGHT = 1.0\nRPN_SIGMA = 3.0\nFASTRCNN_SIGMA = 1.0\n\nMUTILPY_BIAS_GRADIENT = 2.0 # if None, will not multipy\nGRADIENT_CLIPPING_BY_NORM = 10.0 # if None, will not clip\n\nBATCH_SIZE = 1\nEPSILON = 1e-5\nMOMENTUM = 0.9\nLR = 0.001 * BATCH_SIZE * NUM_GPU\nDECAY_STEP = [SAVE_WEIGHTS_INTE*12, SAVE_WEIGHTS_INTE*16, SAVE_WEIGHTS_INTE*20]\nMAX_ITERATION = SAVE_WEIGHTS_INTE*20\nWARM_SETP = int(1.0 / 4.0 * SAVE_WEIGHTS_INTE)\n\n# -------------------------------------------- Data_preprocess_config\nDATASET_NAME = 'DOTA' # 'ship', 'spacenet', 'pascal', 'coco'\nPIXEL_MEAN = [123.68, 116.779, 103.939] # R, G, B. In tf, channel is RGB. In openCV, channel is BGR\nPIXEL_MEAN_ = [0.485, 0.456, 0.406]\nPIXEL_STD = [0.229, 0.224, 0.225]\n\nIMG_SHORT_SIDE_LEN = [800, 900, 1000, 1100, 600, 400]\nIMG_MAX_LENGTH = 1100\nCLASS_NUM = 15\n\nIMG_ROTATE = True\nRGB2GRAY = True\nVERTICAL_FLIP = True\nHORIZONTAL_FLIP = True\nIMAGE_PYRAMID = True\n\n# --------------------------------------------- Network_config\nINITIALIZER = tf.random_normal_initializer(mean=0.0, stddev=0.01)\nBBOX_INITIALIZER = tf.random_normal_initializer(mean=0.0, stddev=0.001)\nWEIGHT_DECAY = 0.00004 if NET_NAME.startswith('Mobilenet') else 0.0001\n\n# ---------------------------------------------Anchor config\nUSE_CENTER_OFFSET = False\n\nLEVLES = ['P2', 'P3', 'P4', 'P5', 'P6']\nBASE_ANCHOR_SIZE_LIST = [32, 64, 128, 256, 512] # addjust the base anchor size for voc.\nANCHOR_STRIDE_LIST = [4, 8, 16, 32, 64]\nANCHOR_SCALES = [1.0]\nANCHOR_RATIOS = [0.5, 1., 2.0, 1/4.0, 4.0, 1/6.0, 6.0]\nROI_SCALE_FACTORS = [10., 10., 5.0, 5.0, 2.0]\nANCHOR_SCALE_FACTORS = None\n\n# --------------------------------------------FPN config\nSHARE_HEADS = True\nKERNEL_SIZE = 3\nRPN_IOU_POSITIVE_THRESHOLD = 0.7\nRPN_IOU_NEGATIVE_THRESHOLD = 0.3\nTRAIN_RPN_CLOOBER_POSITIVES = False\n\nRPN_MINIBATCH_SIZE = 512 # 256\nRPN_POSITIVE_RATE = 0.5\nRPN_NMS_IOU_THRESHOLD = 0.7 # 0.7\nRPN_TOP_K_NMS_TRAIN = 12000\nRPN_MAXIMUM_PROPOSAL_TARIN = 2000\n\nRPN_TOP_K_NMS_TEST = 6000\nRPN_MAXIMUM_PROPOSAL_TEST = 1000\n\n# -------------------------------------------Fast-RCNN config\nROI_SIZE = 14\nROI_POOL_KERNEL_SIZE = 2\nUSE_DROPOUT = False\nKEEP_PROB = 1.0\nSHOW_SCORE_THRSHOLD = 0.6 # only show in tensorboard\n\nSOFT_NMS = False\nFAST_RCNN_NMS_IOU_THRESHOLD = 0.3 # 0.5\nFAST_RCNN_NMS_MAX_BOXES_PER_CLASS = 200\nFAST_RCNN_IOU_POSITIVE_THRESHOLD = 0.5\nFAST_RCNN_IOU_NEGATIVE_THRESHOLD = 0.0 # 0.1 < IOU < 0.5 is negative\nFAST_RCNN_MINIBATCH_SIZE = 512 # if is -1, that is train with OHEM\nFAST_RCNN_POSITIVE_RATE = 0.25\n\nADD_GTBOXES_TO_TRAIN = False\n\n# -------------------------------------------mask config\nUSE_SUPERVISED_MASK = True\nMASK_TYPE = 'r' # r or h\nBINARY_MASK = False\nSIGMOID_ON_DOT = False\nMASK_ACT_FET = True # weather use mask generate 256 channels to dot feat.\nGENERATE_MASK_LIST = [\"P2\", \"P3\", \"P4\", \"P5\"]\nADDITION_LAYERS = [4, 4, 4, 4] # add 4 layer to generate P2_mask, 2 layer to generate P3_mask\nENLAEGE_RF_LIST = [\"P2\", \"P3\", \"P4\", \"P5\"]\nSUPERVISED_MASK_LOSS_WEIGHT = 0.1\n\n# -------------------------------------------Tricks config\nUSE_CONCAT = True\nCONCAT_CHANNEL = 1024 # 256\nROTATE_NMS_USE_GPU = True # When Train, use GPU NMS, When Test, Use CPU NMS.\n\nADD_GLOBAL_CTX = True\nADD_EXTR_CONVS_FOR_REG = 8 # use 0 to do not use any extra convs" ]
[ [ "tensorflow.random_normal_initializer" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
brianx0215/deep-reinforcement-learning
[ "606ccb5eb1b302514567e33dcfdb372942671af7" ]
[ "p1_navigation/dqn_agent.py" ]
[ "import numpy as np\nimport random\nfrom collections import namedtuple, deque\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nBUFFER_SIZE = int(1e5) # replay buffer size\nBATCH_SIZE = 64 # minibatch size\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # interpolation parameter for soft update of target parameters\nLR = 1e-3 # learning rate\nUPDATE_EVERY = 4 # how often to update the network\n\nuse_cuda = torch.cuda.is_available()\n\nclass DQN(nn.Module):\n #Customized DQN class for Udacity deep reinforcement learning project 1\n def __init__(self, state_size, action_size, seed):\n super(DQN, self).__init__()\n self.seed = torch.manual_seed(seed)\n self.fc1 = nn.Linear(state_size, 64)\n self.fc2 = nn.Linear(64, 64)\n self.fc3 = nn.Linear(64, action_size)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\ndef conv(in_channels, out_channels, kernel_size, stride = 1, padding = 1, batch_norm = True):\n layers = []\n conv_layer = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias = False)\n layers.append(conv_layer)\n \n if batch_norm:\n layers.append(nn.BatchNorm2d(out_channels))\n \n return nn.Sequential(*layers)\n\nclass CNNDQN(nn.Module):\n #Customized CNN and DQN class for Udacity deep reinforcement learning project 1\n #The class is referenced from the projects in Udacity deep learning course.\n def __init__(self, state_size, action_size, seed):\n super(CNNDQN, self).__init__()\n self.seed = torch.manual_seed(seed)\n\n self.conv1 = conv(3, 4, 3, batch_norm = False)\n self.conv2 = conv(4, 8, 3)\n self.conv3 = conv(8, 16, 3)\n\n self.pool = nn.MaxPool2d(2, 2)\n \n self.fc1 = nn.Linear(800, 64)\n self.fc2 = nn.Linear(64, 64)\n self.fc3 = nn.Linear(64, action_size)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = self.pool(F.relu(self.conv3(x)))\n x = x.view(-1, 800)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\nclass Agent():\n # The agent interacts with and learns from the banana environment.\n\n def __init__(self, state_size, action_size, visual_input, seed):\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(seed)\n\n # we use Double DQN for the agent\n if visual_input:\n self.dqn_local = CNNDQN(state_size, action_size, seed)\n self.dqn_target = CNNDQN(state_size, action_size, seed)\n else:\n self.dqn_local = DQN(state_size, action_size, seed)\n self.dqn_target = DQN(state_size, action_size, seed)\n \n self.optimizer = optim.Adam(self.dqn_local.parameters(), lr=LR)\n if use_cuda:\n dqn_local, dqn_target = dqn_local.cuda(), dqn_target.cuda()\n self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)\n self.step_counter = 0\n \n def step(self, state, action, reward, next_state, done):\n # Record the experience, update the network when running enough step.\n self.memory.add(state, action, reward, next_state, done)\n\n self.step_counter = (self.step_counter + 1) % UPDATE_EVERY\n if self.step_counter == 0:\n if len(self.memory) >= BATCH_SIZE:\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, state, eps=0.0):\n #Returns action for given state as per current policy.\n\n state = torch.from_numpy(state).float().unsqueeze(0)\n if use_cuda:\n state = state.cuda()\n self.dqn_local.eval()\n with torch.no_grad():\n action_values = self.dqn_local(state)\n\n # Epsilon-greedy action selection\n if random.random() > eps:\n return np.argmax(action_values.cpu().data.numpy())\n else:\n return random.choice(np.arange(self.action_size))\n\n def learn(self, experiences, gamma):\n #Update value parameters using given batch of experience tuples.\n\n states, actions, rewards, next_states, dones = experiences\n self.dqn_local.train()\n # Get max predicted Q values (for next states) from target model\n Q_targets_next = self.dqn_target(next_states).detach().max(1)[0]\n\n # Compute Q targets for current states\n Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))\n\n # Get expected Q values from local model\n # 64, 4 64\n Q_expected = self.dqn_local(states).gather(1, actions.unsqueeze(1)).squeeze(1)\n loss = F.mse_loss(Q_expected, Q_targets)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n #update target network\n self.soft_update(self.dqn_local, self.dqn_target, TAU) \n\n def soft_update(self, local_model, target_model, tau):\n #Soft update model parameters.\n #θ_target = τ * θ_local + (1 - τ) * θ_target\n\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)\n\n def save(self, path):\n torch.save(self.dqn_local.state_dict(), path)\n \n def load(self, path):\n self.dqn_local.load_state_dict(torch.load(path))\n self.dqn_target = self.dqn_local\n\nclass ReplayBuffer:\n #Fixed-size buffer to store experience tuples.\n\n def __init__(self, action_size, buffer_size, batch_size, seed):\n\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size) \n self.batch_size = batch_size\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n \n def add(self, state, action, reward, next_state, done):\n \"\"\"Add a new experience to memory.\"\"\"\n e = self.experience(state, action, reward, next_state, done)\n self.memory.append(e)\n \n def sample(self):\n #Randomly sample a batch of experiences from memory.\n experiences = random.sample(self.memory, k=self.batch_size)\n\n states = torch.FloatTensor([e.state for e in experiences if e is not None])\n actions = torch.LongTensor([e.action for e in experiences if e is not None])\n rewards = torch.FloatTensor([e.reward for e in experiences if e is not None])\n next_states = torch.FloatTensor([e.next_state for e in experiences if e is not None])\n dones = torch.FloatTensor([e.done for e in experiences if e is not None])\n \n if use_cuda:\n states, actions, rewards, next_states, dones = states.cuda(), actions.cuda(), rewards.cuda(), next_states.cuda(), dones.cuda()\n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n return len(self.memory)\n\n" ]
[ [ "torch.nn.Sequential", "torch.LongTensor", "torch.load", "torch.manual_seed", "numpy.arange", "torch.nn.Conv2d", "torch.from_numpy", "torch.nn.Linear", "torch.nn.MaxPool2d", "torch.nn.functional.mse_loss", "torch.FloatTensor", "torch.no_grad", "torch.cuda.is_available", "torch.nn.BatchNorm2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pdturney/modeling-symbiosis-revised
[ "cf342667def566e1ad26dbe46e4e8acfb9be7cf9" ]
[ "model_functions.py" ]
[ "\"\"\"\r\nModel Functions\r\n\r\nPeter Turney, May 18, 2020\r\n\"\"\"\r\nimport golly as g\r\nimport model_classes as mclass\r\nimport model_parameters as mparam\r\nimport random as rand\r\nimport numpy as np\r\nimport copy\r\nimport time\r\nimport pickle\r\nimport os\r\nimport re\r\nimport sys\r\n\"\"\"\r\nVarious functions for working with Golly\r\n\"\"\"\r\n#\r\n# show_message(g, log_handle, message) -- returns NULL\r\n#\r\ndef show_message(g, log_handle, message):\r\n \"\"\"\r\n A function for writing a message to both the Golly window\r\n and the log file.\r\n \"\"\"\r\n log_handle.write(message)\r\n g.show(message)\r\n#\r\n# set_mag(g) -- returns mag\r\n#\r\ndef set_mag(g):\r\n \"\"\"\r\n A function for setting the Golly screen magnification\r\n \"\"\"\r\n # the maximum of the X span and the Y span\r\n g_maxspan = np.amax([g.getwidth(), g.getheight()])\r\n # the Golly magnification ratio is 2 to the power of mag\r\n if (g_maxspan < 80):\r\n mag = 5 # 2^5 = 32\r\n elif (g_maxspan < 160):\r\n mag = 4 # 2^4 = 16\r\n elif (g_maxspan < 320):\r\n mag = 3 # 2^3 = 8\r\n elif (g_maxspan < 640):\r\n mag = 2 # 2^2 = 4\r\n elif (g_maxspan < 1280):\r\n mag = 1 # 2^1 = 2\r\n else:\r\n mag = 0 # 2^0 = 1\r\n return mag\r\n#\r\n# show_parameters() -- returns a list of parameters and values\r\n#\r\ndef show_parameters():\r\n \"\"\"\r\n Make a list of the parameters in mparam and show\r\n the value of each parameter.\r\n \"\"\"\r\n parameter_names = sorted(dir(mparam))\r\n display_list = []\r\n for name in parameter_names:\r\n # skip over system names\r\n # - system names have the form \"__file__\"\r\n if (name[0] != \"_\"): \r\n value = str(getattr(mparam, name))\r\n display_list.append(name + \" = \" + value)\r\n return display_list\r\n#\r\n# get_minmax(g) -- returns [g_xmin, g_xmax, g_ymin, g_ymax]\r\n#\r\ndef get_minmax(g):\r\n \"\"\"\r\n Calculate the min and max of the Golly toroid coordinates\r\n \"\"\"\r\n # get height and width\r\n g_xspan = g.getwidth()\r\n g_yspan = g.getheight()\r\n # calculate min and max\r\n g_xmin = - int(g_xspan / 2)\r\n g_xmax = g_xspan + g_xmin\r\n g_ymin = - int(g_yspan / 2)\r\n g_ymax = g_yspan + g_ymin\r\n #\r\n return [g_xmin, g_xmax, g_ymin, g_ymax]\r\n#\r\n# count_pops(g) -- returns [count1, count2]\r\n#\r\ndef count_pops(g):\r\n \"\"\"\r\n Count the populations of state 1 (red) and state 2 (blue)\r\n \"\"\"\r\n # find the min and max of the Golly toroid coordinates\r\n [g_xmin, g_xmax, g_ymin, g_ymax] = get_minmax(g)\r\n #\r\n count1 = 0\r\n count2 = 0\r\n #\r\n for x in range(g_xmin, g_xmax):\r\n for y in range(g_ymin, g_ymax):\r\n a = g.getcell(x, y)\r\n if (a == 1):\r\n count1 = count1 + 1\r\n if (a == 2):\r\n count2 = count2 + 1\r\n #\r\n return [count1, count2]\r\n#\r\n# initialize_population(pop_size, s_xspan, s_yspan, seed_density)\r\n# -- returns population\r\n#\r\ndef initialize_population(pop_size, s_xspan, s_yspan, seed_density):\r\n \"\"\"\r\n Randomly initialize the population of seeds.\r\n \"\"\"\r\n #\r\n # Initialize the population: a list of seeds.\r\n #\r\n # Here a seed is an initial Game of Life pattern (it is\r\n # not a random number seed).\r\n #\r\n population = []\r\n #\r\n for i in range(pop_size):\r\n # Make an empty seed (all zeros). \r\n seed = mclass.Seed(s_xspan, s_yspan, pop_size) \r\n # Randomly set some cells to state 1 (red).\r\n seed.randomize(seed_density) \r\n # Set the count of living cells.\r\n seed.num_living = seed.count_ones()\r\n # Set the position of the new seed in the population array.\r\n seed.address = i \r\n # Add the seed to the population.\r\n population.append(seed) \r\n #\r\n return population\r\n#\r\n# dimensions(s1, s2, width_factor, height_factor, time_factor)\r\n# -- returns [g_width, g_height, g_time]\r\n#\r\ndef dimensions(s1, s2, width_factor, height_factor, time_factor):\r\n \"\"\"\r\n Define the dimensions of the Golly universe, based on the\r\n sizes of the two seeds and various multiplicative factors.\r\n \"\"\"\r\n #\r\n # Suggested values:\r\n #\r\n # width_factor = 6.0\r\n # height_factor = 3.0\r\n # time_factor = 6.0\r\n #\r\n assert width_factor > 2.0 # need space for two seeds, left and right\r\n assert height_factor > 1.0 # need space for tallest seed\r\n assert time_factor > 1.0 # time should increase with increased space\r\n #\r\n # Find the maximum of the dimensions of the two seeds.\r\n #\r\n max_size = np.amax([s1.xspan, s1.yspan, s2.xspan, s2.yspan])\r\n #\r\n # Apply the various factors.\r\n #\r\n g_width = int(max_size * width_factor)\r\n g_height = int(max_size * height_factor)\r\n g_time = int((g_width + g_height) * time_factor)\r\n #\r\n return [g_width, g_height, g_time]\r\n#\r\n# score_pair(g, seed1, seed2, width_factor, height_factor, \\\r\n# time_factor, num_trials) -- returns [score1, score2]\r\n#\r\ndef score_pair(g, seed1, seed2, width_factor, height_factor, \\\r\n time_factor, num_trials):\r\n \"\"\"\r\n Put seed1 and seed2 into the Immigration Game g and see which \r\n one wins and which one loses. Note that this function does\r\n not update the histories of the seeds. For updating histories,\r\n use update_history().\r\n \"\"\"\r\n #\r\n # Make copies of the original two seeds, so that the following\r\n # manipulations do not change the originals.\r\n #\r\n s1 = copy.deepcopy(seed1)\r\n s2 = copy.deepcopy(seed2)\r\n #\r\n # Check the number of living cells in the seeds. If the number\r\n # is zero, it is probably a mistake. The number is initially\r\n # set to zero and it should be updated when the seed is filled\r\n # with living cells. We could use s1.count_ones() here, but\r\n # we're trying to be efficient by counting only once and \r\n # storing the count.\r\n #\r\n assert s1.num_living > 0\r\n assert s2.num_living > 0\r\n #\r\n # Initialize scores\r\n #\r\n score1 = 0.0\r\n score2 = 0.0\r\n #\r\n # Run several trials with different rotations and locations.\r\n #\r\n for trial in range(num_trials):\r\n #\r\n # Randomly rotate and flip s1 and s2\r\n #\r\n s1 = s1.random_rotate()\r\n s2 = s2.random_rotate()\r\n #\r\n # Switch cells in the second seed (s2) from state 1 (red) to state 2 (blue)\r\n #\r\n s2.red2blue()\r\n #\r\n # Rule file\r\n #\r\n rule_name = \"Immigration\"\r\n #\r\n # Set toroidal universe of height yspan and width xspan\r\n # Base the s1ze of the universe on the s1zes of the seeds\r\n #\r\n # g = the Golly universe\r\n #\r\n [g_width, g_height, g_time] = dimensions(s1, s2, \\\r\n width_factor, height_factor, time_factor)\r\n #\r\n # set algorithm -- \"HashLife\" or \"QuickLife\"\r\n #\r\n g.setalgo(\"QuickLife\") # use \"HashLife\" or \"QuickLife\"\r\n g.autoupdate(False) # do not update the view unless requested\r\n g.new(rule_name) # initialize cells to state 0\r\n g.setrule(rule_name + \":T\" + str(g_width) + \",\" + str(g_height)) # make a toroid\r\n #\r\n # Find the min and max of the Golly toroid coordinates\r\n #\r\n [g_xmin, g_xmax, g_ymin, g_ymax] = get_minmax(g)\r\n #\r\n # Set magnification for Golly viewer\r\n #\r\n g.setmag(set_mag(g))\r\n #\r\n # Randomly place seed s1 somewhere in the left s1de of the toroid\r\n #\r\n s1.insert(g, g_xmin, -1, g_ymin, g_ymax)\r\n #\r\n # Randomly place seed s2 somewhere in the right s1de of the toroid\r\n #\r\n s2.insert(g, +1, g_xmax, g_ymin, g_ymax)\r\n #\r\n # Run for a fixed number of generations.\r\n # Base the number of generations on the sizes of the seeds.\r\n # Note that these are generations ins1de one Game of Life, not\r\n # generations in an evolutionary sense. Generations in the \r\n # Game of Life correspond to growth and decay of a phenotype,\r\n # whereas generations in evolution correspond to the reproduction\r\n # of a genotype.\r\n #\r\n g.run(g_time) # run the Game of Life for g_time time steps\r\n g.update() # need to update Golly to get counts\r\n #\r\n # Count the populations of the two colours. State 1 = red = seed1.\r\n # State 2 = blue = seed2.\r\n #\r\n [count1, count2] = count_pops(g)\r\n #\r\n # We need to make an adjustment to these counts. We don't want to \r\n # use the total count of living cells; instead we want to use\r\n # the increase in the number of living cells over the course of\r\n # the contest between the two organisms. The idea here is that\r\n # we want to reward seeds according to their growth during the\r\n # contest, not according to their initial states. This should\r\n # avoid an evolutionary bias towards larger seeds simply due\r\n # to size rather than due to functional properties. It should\r\n # also encourage efficient use of living cells, as opposed to\r\n # simply ignoring useless living cells.\r\n #\r\n # s1.num_living = initial number of living cells in s1\r\n # s2.num_living = initial number of living cells in s2\r\n #\r\n if (s1.num_living < count1):\r\n count1 = count1 - s1.num_living\r\n else:\r\n count1 = 0\r\n #\r\n if (s2.num_living < count2):\r\n count2 = count2 - s2.num_living\r\n else:\r\n count2 = 0\r\n #\r\n # Now we are ready to determine the winner.\r\n #\r\n if (count1 > count2):\r\n score1 = score1 + 1.0\r\n elif (count2 > count1):\r\n score2 = score2 + 1.0\r\n else:\r\n score1 = score1 + 0.5\r\n score2 = score2 + 0.5\r\n #\r\n #\r\n # Normalize the scores\r\n #\r\n score1 = score1 / num_trials\r\n score2 = score2 / num_trials\r\n #\r\n return [score1, score2]\r\n#\r\n# update_history(g, pop, i, j, width_factor, height_factor, \\\r\n# time_factor, num_trials) -- returns NULL\r\n#\r\ndef update_history(g, pop, i, j, width_factor, height_factor, \\\r\n time_factor, num_trials):\r\n \"\"\"\r\n Put the i-th and j-th seeds into the Immigration Game g and\r\n see which one wins and which one loses. The history of the \r\n seeds will be updated in pop.\r\n \"\"\"\r\n #\r\n # If i == j, let's just call it a tie.\r\n #\r\n if (i == j):\r\n pop[i].history[i] = 0.5\r\n return\r\n #\r\n # Call score_pair()\r\n #\r\n [scorei, scorej] = score_pair(g, pop[i], pop[j], width_factor, \\\r\n height_factor, time_factor, num_trials)\r\n #\r\n # Update pop[i] and pop[j] with the new scores. \r\n #\r\n pop[i].history[j] = scorei\r\n pop[j].history[i] = scorej\r\n # \r\n # returns NULL\r\n # \r\n#\r\n# update_similarity(pop, i, j) -- returns NULL\r\n#\r\ndef update_similarity(pop, i, j):\r\n \"\"\"\r\n Calculate the similarity between the two given seeds and \r\n update their internal records with the result.\r\n \"\"\"\r\n #\r\n # If i == j, the similarity score is the maximum.\r\n #\r\n if (i == j):\r\n pop[i].similarities[i] = 1.0\r\n return\r\n #\r\n # Calculate the similarity and update the population record.\r\n #\r\n sim = similarity(pop[i], pop[j])\r\n pop[i].similarities[j] = sim\r\n pop[j].similarities[i] = sim\r\n # \r\n # returns NULL\r\n # \r\n#\r\n# find_top_seeds(population, sample_size) -- returns sample_pop\r\n#\r\ndef find_top_seeds(population, sample_size):\r\n \"\"\"\r\n Find the best (fittest) sample_size seeds in the population.\r\n \"\"\"\r\n pop_size = len(population)\r\n assert pop_size > sample_size\r\n assert sample_size > 0\r\n # calculate fitness for each seed in the population, from their history\r\n scored_pop = []\r\n for i in range(pop_size):\r\n item = [population[i].fitness(), population[i]]\r\n scored_pop.append(item)\r\n # sort population in order of decreasing fitness (reverse=True)\r\n scored_pop.sort(key = lambda x: x[0], reverse=True) # sort by fitness\r\n # take the top sample_size items from scored_pop and\r\n # remove their attached fitness numbers\r\n sample_pop = []\r\n for i in range(sample_size):\r\n sample_pop.append(scored_pop[i][1]) # drop fitness number\r\n # return the cleaned-up list of sample_size seeds\r\n return sample_pop\r\n#\r\n# random_sample(population, sample_size) -- returns sample_pop\r\n#\r\ndef random_sample(population, sample_size):\r\n \"\"\"\r\n Get a random sample of sample_size seeds from the population.\r\n \"\"\"\r\n #\r\n # To avoid duplicates in the sample, randomize the order of the\r\n # population and then take the first sample_size seeds\r\n # from the randomized list.\r\n #\r\n pop_size = len(population)\r\n assert pop_size > sample_size\r\n assert sample_size > 0\r\n # attach a random number to each seed in the population\r\n randomized_pop = []\r\n for i in range(pop_size):\r\n # item = [random real number between 0 and 1, the i-th seed]\r\n item = [rand.uniform(0, 1), population[i]]\r\n randomized_pop.append(item)\r\n # sort randomized_pop in order of the attached random numbers\r\n randomized_pop.sort(key = lambda x: x[0]) # sort by random number\r\n # take the top sample_size items from randomized_pop and\r\n # remove their attached random numbers\r\n sample_pop = []\r\n for i in range(sample_size):\r\n sample_pop.append(randomized_pop[i][1]) # drop random number\r\n # return the cleaned-up list of sample_size seeds\r\n return sample_pop\r\n#\r\n# find_best_seed(sample) -- returns best_seed\r\n#\r\ndef find_best_seed(sample):\r\n \"\"\"\r\n In the list of seeds in sample, find the seed (not necessarily\r\n unique) with maximum fitness.\r\n \"\"\"\r\n sample_size = len(sample)\r\n assert sample_size > 0\r\n best_seed = sample[0]\r\n best_score = best_seed.fitness()\r\n for i in range(len(sample)):\r\n if (sample[i].fitness() > best_score):\r\n best_seed = sample[i]\r\n best_score = best_seed.fitness()\r\n return best_seed\r\n#\r\n# find_worst_seed(sample) -- returns worst_seed\r\n#\r\ndef find_worst_seed(sample):\r\n \"\"\"\r\n In the list of seeds in sample, find the seed (not necessarily\r\n unique) with minimum fitness.\r\n \"\"\"\r\n sample_size = len(sample)\r\n assert sample_size > 0\r\n worst_seed = sample[0]\r\n worst_score = worst_seed.fitness()\r\n for i in range(len(sample)):\r\n if (sample[i].fitness() < worst_score):\r\n worst_seed = sample[i]\r\n worst_score = worst_seed.fitness()\r\n return worst_seed\r\n#\r\n# average_fitness(sample) -- returns average\r\n#\r\ndef average_fitness(sample):\r\n \"\"\"\r\n Given a list of sample seeds, return their average fitness,\r\n relative to the whole population.\r\n \"\"\"\r\n sample_size = len(sample)\r\n assert sample_size > 0\r\n total_fitness = 0.0\r\n for i in range(len(sample)):\r\n total_fitness = total_fitness + sample[i].fitness()\r\n average = total_fitness / sample_size\r\n return average\r\n#\r\n# archive_elite(population, elite_size, log_directory, log_name, run_id_number) \r\n# -- returns NULL\r\n#\r\ndef archive_elite(population, elite_size, log_directory, log_name, run_id_number):\r\n \"\"\"\r\n Store an archive file of the elite members of the population,\r\n for future testing. The elite consists of the top elite_size\r\n most fit seeds in the current population.\r\n \"\"\"\r\n history_sample = find_top_seeds(population, elite_size)\r\n history_name = log_name + \"-pickle-\" + str(run_id_number)\r\n history_path = log_directory + \"/\" + history_name + \".bin\"\r\n history_handle = open(history_path, \"wb\") # wb = write binary\r\n pickle.dump(history_sample, history_handle)\r\n history_handle.close()\r\n # \r\n # returns NULL\r\n # \r\n#\r\n# similarity(seed0, seed1) -- returns similarity\r\n#\r\ndef similarity(seed0, seed1):\r\n \"\"\"\r\n Measure the bit-wise similarity of two seeds. If the seeds\r\n have different sizes, return zero.\r\n \"\"\"\r\n # Make sure the seeds are the same size.\r\n if (seed0.xspan != seed1.xspan):\r\n return 0.0\r\n if (seed0.yspan != seed1.yspan):\r\n return 0.0\r\n # Initialize count.\r\n num_agree = 0.0\r\n # Count agreements.\r\n for x in range(seed0.xspan):\r\n for y in range(seed0.yspan):\r\n if (seed0.cells[x][y] == seed1.cells[x][y]):\r\n num_agree = num_agree + 1.0\r\n # Calculate a similarity score ranging from zero to one.\r\n similarity = num_agree / (seed0.xspan * seed0.yspan)\r\n # Return the degree of similarity between the two seeds.\r\n return similarity\r\n#\r\n# find_similar_seeds(target_seed, pop, min_similarity, max_similarity)\r\n# -- returns similar_seeds\r\n# \r\ndef find_similar_seeds(target_seed, pop, min_similarity, max_similarity):\r\n \"\"\"\r\n Given a target seed, find seeds in the population with similarities\r\n to the target in the range from min_similarity to max_similarity.\r\n This function assumes that target_seed is in the population and\r\n the list target_seed.similarities is up-to-date. \r\n \"\"\"\r\n similar_seeds = []\r\n for i in range(len(pop)):\r\n if ((target_seed.similarities[i] >= min_similarity) and \\\r\n (target_seed.similarities[i] <= max_similarity) and \\\r\n (target_seed.address != i)):\r\n similar_seeds.append(pop[i])\r\n # return the seeds that satisfy the conditions\r\n return similar_seeds\r\n#\r\n# mate(seed0, seed1) -- returns child_seed\r\n#\r\ndef mate(seed0, seed1):\r\n \"\"\"\r\n Apply crossover to seed0 and seed1. We only have one crossover point,\r\n because multiple crossover points would be more disruptive to the\r\n structure of the seeds.\r\n \"\"\"\r\n # This function is designed with the assumption that the seeds are \r\n # the same size.\r\n assert seed0.xspan == seed1.xspan\r\n assert seed0.yspan == seed1.yspan\r\n # Note the spans of seed0 and seed1.\r\n xspan = seed0.xspan\r\n yspan = seed0.yspan\r\n # Randomly swap the seeds. Because s0 is always the top part of\r\n # a split that cuts across the Y axis and the left part of a split \r\n # that cuts across the X axis, we need to swap the seeds in order\r\n # to add some variety.\r\n if (rand.uniform(0, 1) < 0.5):\r\n s0 = seed0\r\n s1 = seed1\r\n else:\r\n s0 = seed1\r\n s1 = seed0\r\n # Initialize the child to zero.\r\n child_seed = mclass.Seed(xspan, yspan, mparam.pop_size) \r\n # Randomly choose whether to split on the X axis or\r\n # the Y axis.\r\n if (rand.uniform(0, 1) < 0.5):\r\n # Choose the Y axis split point. There will always be\r\n # at least one row on either side of the split point.\r\n assert yspan > 1\r\n y_split_point = rand.randrange(yspan - 1)\r\n for x in range(xspan):\r\n for y in range(yspan):\r\n if (y <= y_split_point):\r\n child_seed.cells[x][y] = s0.cells[x][y]\r\n else:\r\n child_seed.cells[x][y] = s1.cells[x][y]\r\n else:\r\n # Choose the X axis split point. There will always be\r\n # at least one column on either side of the split point.\r\n assert xspan > 1\r\n x_split_point = rand.randrange(xspan - 1)\r\n for x in range(xspan):\r\n for y in range(yspan):\r\n if (x <= x_split_point):\r\n child_seed.cells[x][y] = s0.cells[x][y]\r\n else:\r\n child_seed.cells[x][y] = s1.cells[x][y]\r\n # Return the resulting child.\r\n return child_seed\r\n#\r\n# uniform_asexual(candidate_seed, pop, n) -- returns [pop, message]\r\n#\r\ndef uniform_asexual(candidate_seed, pop, n):\r\n \"\"\"\r\n Create a new seed by randomly mutating an existing seed. The\r\n new seed is generated by selecting a parent seed and flipping\r\n bits in the parent. The size of the seed does not change; it\r\n is uniform.\r\n \"\"\"\r\n # The most fit member of the tournament.\r\n s0 = candidate_seed\r\n # Mutate the best seed to make a new child. The only mutation\r\n # here is flipping bits.\r\n mutation_rate = mparam.mutation_rate\r\n s1 = copy.deepcopy(s0)\r\n s1.flip_bits(mutation_rate)\r\n s1.num_living = s1.count_ones() # update count of living cells\r\n # Find the least fit old seed in the population. It's not a problem\r\n # if there are ties.\r\n s2 = find_worst_seed(pop)\r\n # Now we have:\r\n #\r\n # s0 = fit parent seed\r\n # s1 = the mutated new child\r\n # s2 = the least fit old seed, which will be replaced by the mutated child\r\n #\r\n # Replace the least fit old seed in the population (s2) with the\r\n # new child (s1).\r\n i = s2.address # find the position of the old seed (s2)\r\n s1.address = i # copy the old position of the old seed into s1, the child\r\n pop[i] = s1 # replace s2 (old seed) in population (pop) with s1 (new child)\r\n # Build a history for the new seed, by matching it against all seeds\r\n # in the population.\r\n width_factor = mparam.width_factor\r\n height_factor = mparam.height_factor\r\n time_factor = mparam.time_factor\r\n num_trials = mparam.num_trials\r\n pop_size = len(pop)\r\n for j in range(pop_size):\r\n update_history(g, pop, i, j, width_factor, height_factor, \\\r\n time_factor, num_trials)\r\n update_similarity(pop, i, j)\r\n # Report on the new history of the new seed\r\n message = \"Run: {}\".format(n) + \\\r\n \" Parent fitness (s0): {:.3f}\".format(s0.fitness()) + \\\r\n \" Child fitness (s1): {:.3f}\".format(s1.fitness()) + \\\r\n \" Replaced seed fitness (s2): {:.3f}\\n\".format(s2.fitness())\r\n # It is possible that s1 is worse than s2, if there was a bad mutation in s1.\r\n # Let's not worry about that, since s1 will soon be replaced if it is less\r\n # fit than the least fit seed (that is, s2).\r\n return [pop, message]\r\n#\r\n# variable_asexual(candidate_seed, pop, n, max_seed_area) \r\n# -- returns [pop, message]\r\n#\r\ndef variable_asexual(candidate_seed, pop, n, max_seed_area):\r\n \"\"\"\r\n Create a new seed by randomly mutating, growing, and shrinking\r\n an existing seed. The new seed is generated by selecting a parent \r\n seed and randomly flipping bits, removing rows and columns, or\r\n adding rows and columns. The size of the seed is variable; it \r\n may increase or decrease in size.\r\n \"\"\"\r\n # The most fit member of the tournament.\r\n s0 = candidate_seed\r\n # Mutate the best seed to make a new child. The mutations here\r\n # are flipping bits, removing rows and columns (shrinking), and\r\n # adding rows and columns (growing).\r\n prob_grow = mparam.prob_grow\r\n prob_flip = mparam.prob_flip\r\n prob_shrink = mparam.prob_shrink\r\n seed_density = mparam.seed_density\r\n mutation_rate = mparam.mutation_rate\r\n s1 = copy.deepcopy(s0)\r\n s1 = s1.mutate(prob_grow, prob_flip, prob_shrink, seed_density, mutation_rate)\r\n s1.num_living = s1.count_ones() # update count of living cells\r\n # Make sure the area of the new seed is not greater than the maximum.\r\n # If it is too big, then default to uniform_asexual reproduction.\r\n if ((s1.xspan * s1.yspan) > max_seed_area):\r\n return uniform_asexual(candidate_seed, pop, n)\r\n # Find the least fit old seed in the population. It's not a problem\r\n # if there are ties.\r\n s2 = find_worst_seed(pop)\r\n # Now we have:\r\n #\r\n # s0 = fit parent seed\r\n # s1 = the mutated new child\r\n # s2 = the least fit old seed, which will be replaced by the mutated child\r\n #\r\n # Replace the least fit old seed in the population (s2) with the\r\n # new child (s1).\r\n i = s2.address # find the position of the old seed (s2)\r\n s1.address = i # copy the old position of the old seed into s1, the child\r\n pop[i] = s1 # replace s2 (old seed) in population (pop) with s1 (new child)\r\n # Build a history for the new seed, by matching it against all seeds\r\n # in the population.\r\n width_factor = mparam.width_factor\r\n height_factor = mparam.height_factor\r\n time_factor = mparam.time_factor\r\n num_trials = mparam.num_trials\r\n pop_size = len(pop)\r\n for j in range(pop_size):\r\n update_history(g, pop, i, j, width_factor, height_factor, \\\r\n time_factor, num_trials)\r\n update_similarity(pop, i, j)\r\n # Report on the new history of the new seed\r\n message = \"Run: {}\".format(n) + \\\r\n \" Parent fitness (s0): {:.3f}\".format(s0.fitness()) + \\\r\n \" Child fitness (s1): {:.3f}\".format(s1.fitness()) + \\\r\n \" Replaced seed fitness (s2): {:.3f}\\n\".format(s2.fitness())\r\n # It is possible that s1 is worse than s2, if there was a bad mutation in s1.\r\n # Let's not worry about that, since s1 will soon be replaced if it is less\r\n # fit than the least fit seed (that is, s2).\r\n return [pop, message]\r\n#\r\n# sexual(candidate_seed, pop, n, max_seed_area) -- returns [pop, message]\r\n#\r\ndef sexual(candidate_seed, pop, n, max_seed_area):\r\n \"\"\"\r\n Create a new seed either asexually or sexually. First a single parent\r\n is chosen from the population. If a second parent can be found that\r\n is sufficiently similar to the first parent, then the child will have\r\n two parents (sexual reproduction). If no similar second parent can be\r\n found, then the child will have one parent (asexual reproduction).\r\n \"\"\"\r\n # Let s0 be the most fit member of the tournament.\r\n s0 = candidate_seed\r\n # Find similar seeds in the population (members of the same species).\r\n min_similarity = mparam.min_similarity\r\n max_similarity = mparam.max_similarity\r\n similar_seeds = find_similar_seeds(s0, pop, min_similarity, max_similarity)\r\n num_similar_seeds = len(similar_seeds)\r\n # If no similar seeds were found, then use variable asexual reproduction.\r\n if (num_similar_seeds == 0):\r\n return variable_asexual(candidate_seed, pop, n, max_seed_area)\r\n # Run a new tournament to select a second seed s1 as a mate for s0.\r\n tournament_size = mparam.tournament_size\r\n if (num_similar_seeds <= tournament_size):\r\n s1 = find_best_seed(similar_seeds)\r\n else:\r\n tournament_sample = random_sample(similar_seeds, tournament_size)\r\n s1 = find_best_seed(tournament_sample)\r\n # Mate the parents to make a new child.\r\n s2 = mate(s0, s1)\r\n # Mutate the child.\r\n prob_grow = mparam.prob_grow\r\n prob_flip = mparam.prob_flip\r\n prob_shrink = mparam.prob_shrink\r\n seed_density = mparam.seed_density\r\n mutation_rate = mparam.mutation_rate\r\n s3 = s2.mutate(prob_grow, prob_flip, prob_shrink, seed_density, mutation_rate)\r\n s3.num_living = s3.count_ones() # update count of living cells\r\n # Make sure the area of the new seed is not greater than the maximum.\r\n # If it is too big, then default to uniform_asexual reproduction.\r\n if ((s3.xspan * s3.yspan) > max_seed_area):\r\n return uniform_asexual(candidate_seed, pop, n)\r\n # Find the least fit old seed in the population. It's not a problem\r\n # if there are ties.\r\n s4 = find_worst_seed(pop)\r\n # Now we have:\r\n #\r\n # s0 = parent 0\r\n # s1 = parent 1\r\n # s2 = the new child, before mutation\r\n # s3 = the mutated new child\r\n # s4 = the least fit old seed, which will be replaced by the mutated child\r\n #\r\n # Replace the least fit old seed in the population (s4) with the\r\n # new child (s3).\r\n i = s4.address # find the position of the old seed (s4)\r\n s3.address = i # copy the old position of the old seed into s3, the child\r\n pop[i] = s3 # replace s4 (old seed) in population (pop) with s3 (new child)\r\n # Build a history for the new seed, by matching it against all seeds\r\n # in the population.\r\n width_factor = mparam.width_factor\r\n height_factor = mparam.height_factor\r\n time_factor = mparam.time_factor\r\n num_trials = mparam.num_trials\r\n pop_size = len(pop)\r\n for j in range(pop_size):\r\n update_history(g, pop, i, j, width_factor, height_factor, \\\r\n time_factor, num_trials)\r\n update_similarity(pop, i, j)\r\n # Report on the new history of the new seed\r\n message = \"Run: {}\".format(n) + \\\r\n \" Parent 0 fitness (s0): {:.3f}\".format(s0.fitness()) + \\\r\n \" Parent 1 fitness (s1): {:.3f}\".format(s1.fitness()) + \\\r\n \" Child fitness (s3): {:.3f}\".format(s3.fitness()) + \\\r\n \" Replaced seed fitness (s4): {:.3f}\\n\".format(s4.fitness())\r\n # It is possible that s3 is worse than s4, if there was a bad mutation in s3.\r\n # Let's not worry about that, since s3 will soon be replaced if it is less\r\n # fit than the least fit seed (that is, s4).\r\n return [pop, message]\r\n#\r\n# fusion(candidate_seed, pop, n, max_seed_area) -- returns [pop, message]\r\n#\r\ndef fusion(candidate_seed, pop, n, max_seed_area):\r\n \"\"\"\r\n Fuse two seeds together. Randomly rotate the seeds before\r\n joining them. Let's put one seed on the left and the other \r\n seed on the right. Insert one empty column between the two \r\n seeds, as a kind of buffer, so that the two seeds do not \r\n immediately interact. This empty column also helps fission\r\n later on, to split joined seeds at the same point where they\r\n were initially joined.\r\n \"\"\"\r\n # The most fit member of the tournament.\r\n s0 = candidate_seed\r\n # Run another tournament to select a second seed. The second\r\n # seed might be identical to the first seed. That's OK.\r\n tournament_size = mparam.tournament_size\r\n tournament_sample = random_sample(pop, tournament_size)\r\n s1 = find_best_seed(tournament_sample)\r\n # If the flag fusion_test_flag is set to 1, then randomize s1\r\n # by shuffling its cells. This operation is expected to reduce\r\n # the fitness of the new fusion seed. Usually fusion_test_flag\r\n # should be set to 0. Note that s1.shuffle() makes a copy, so the\r\n # original of s1 is not affected by the shuffling.\r\n if (mparam.fusion_test_flag == 1):\r\n s1 = s1.shuffle()\r\n # Randomly rotate the seeds. These rotations (s2 and s3) are copies. \r\n # The originals (s0 and s1) are not affected by the rotations.\r\n s2 = s0.random_rotate()\r\n s3 = s1.random_rotate()\r\n # Get dimensions for the new fusion seed.\r\n pop_size = mparam.pop_size\r\n xspan = s2.xspan + s3.xspan + 1 # left width + right width + empty gap\r\n yspan = max(s2.yspan, s3.yspan) # the larger of the two heights\r\n # Make sure the area of the new seed is not greater than the maximum.\r\n # If it is too big, then default to sexual reproduction.\r\n if ((xspan * yspan) > max_seed_area):\r\n return sexual(candidate_seed, pop, n, max_seed_area)\r\n # Copy s2 into the left side of s4.\r\n s4 = mclass.Seed(xspan, yspan, pop_size) # cells initialized to zero\r\n for x in range(s2.xspan):\r\n for y in range(s2.yspan):\r\n s4.cells[x][y] = s2.cells[x][y]\r\n # Copy s3 into the right side of s4.\r\n for x in range(s3.xspan):\r\n for y in range(s3.yspan):\r\n s4.cells[x + s2.xspan + 1][y] = s3.cells[x][y]\r\n # Update count of living cells\r\n s4.num_living = s4.count_ones()\r\n # Find the least fit old seed in the population. It's not a problem\r\n # if there are ties.\r\n s5 = find_worst_seed(pop)\r\n # Now we have:\r\n #\r\n # s0 = seed 0\r\n # s1 = seed 1\r\n # s2 = rotated seed 0\r\n # s3 = rotated seed 1\r\n # s4 = the fusion of s2 and s3\r\n # s5 = the least fit old seed, which will be replaced by s4\r\n #\r\n # NOTE: we're not applying mutation here, because this is not a form\r\n # of reproduction. It's a merger of two seeds. \r\n #\r\n # Replace the least fit old seed in the population (s5) with the\r\n # new fusion seed (s4).\r\n i = s5.address # find the position of the old seed (s5)\r\n s4.address = i # copy the old position of the old seed into s4, the new fusion seed\r\n pop[i] = s4 # replace s5 (old seed) in population (pop) with s4 (new fusion seed)\r\n # Build a history for the new seed, by matching it against all seeds\r\n # in the population.\r\n width_factor = mparam.width_factor\r\n height_factor = mparam.height_factor\r\n time_factor = mparam.time_factor\r\n num_trials = mparam.num_trials\r\n for j in range(pop_size):\r\n update_history(g, pop, i, j, width_factor, height_factor, \\\r\n time_factor, num_trials)\r\n update_similarity(pop, i, j)\r\n # If the flag immediate_symbiosis_flag is set to \"1\", then\r\n # we must test to see whether s4 is more fit than both s1 and s2.\r\n if (mparam.immediate_symbiosis_flag == 1):\r\n if ((s0.fitness() >= s4.fitness()) or (s1.fitness() >= s4.fitness)):\r\n # If either of the parts (s0 or s1) has a fitness greater than\r\n # or equal to the fitness of s4, then default to sexual reproduction.\r\n # Symbiosis means that the whole is more fit than the parts.\r\n # When the flag immediate_symbiosis_flag is set to \"1\", we\r\n # insist that symbiosis should happen immediately, rather than\r\n # hoping that it will happen in some future generation.\r\n return sexual(candidate_seed, pop, n, max_seed_area)\r\n # Report on the new history of the new seed.\r\n message = \"Run: {}\".format(n) + \\\r\n \" Seed 0 fitness (s0): {:.3f}\".format(s0.fitness()) + \\\r\n \" Seed 1 fitness (s1): {:.3f}\".format(s1.fitness()) + \\\r\n \" Fusion fitness (s4): {:.3f}\".format(s4.fitness()) + \\\r\n \" Replaced seed fitness (s5): {:.3f}\\n\".format(s5.fitness())\r\n # Return with the updated population and a message.\r\n return [pop, message]\r\n#\r\n# fission(candidate_seed, pop, n, max_seed_area) -- returns [pop, message]\r\n#\r\ndef fission(candidate_seed, pop, n, max_seed_area):\r\n \"\"\"\r\n In fusion, we use the convention of putting one seed on \r\n the left and the other seed on the right, before we fuse\r\n the two seeds. In fission, we assume that fission will \r\n split the left part from the right part. Find the most \r\n sparse column in the candidate seed and split the seed along \r\n this column. If both parts are at least the minimum allowed \r\n seed size, randomly choose one of them. If only one part\r\n is at least the minimum allowed seed size, choose that\r\n one part. If neither part is at least the minimum allowed \r\n seed size, then default to sexual reproduction.\r\n \"\"\"\r\n # The most fit member of the tournament.\r\n s0 = candidate_seed\r\n # Minimum xspan. Only xspan is relevant, since we are splitting\r\n # left and right parts.\r\n min_s_xspan = mparam.min_s_xspan\r\n # See whether the seed is big enough to split. If it is too\r\n # small, then default to sexual reproduction.\r\n if (s0.xspan <= min_s_xspan):\r\n return sexual(candidate_seed, pop, n, max_seed_area)\r\n # Location of the most sparse column. If there are ties, the\r\n # first sparse column will be chosen.\r\n sparse_col = np.argmin(np.sum(s0.cells, axis = 0))\r\n # Left and right parts.\r\n left_cells = s0.cells[0:sparse_col, :]\r\n right_cells = s0.cells[(sparse_col + 1):, :]\r\n # Initialize a seed for the left or right part.\r\n s1 = copy.deepcopy(s0)\r\n # If both parts are big enough, randomly choose one of them.\r\n if ((left_cells.shape[0] >= min_s_xspan) \\\r\n and (right_cells.shape[0] >= min_s_xspan)):\r\n if (rand.uniform(0, 1) < 0.5):\r\n s1.cells = left_cells\r\n else:\r\n s1.cells = right_cells\r\n # If only the left part is big enough, use the left part.\r\n elif (left_cells.shape[0] >= min_s_xspan):\r\n s1.cells = left_cells\r\n # If only the right part is big enough, use the right part.\r\n elif (right_cells.shape[0] >= min_s_xspan):\r\n s1.cells = right_cells\r\n # If neither part is big enough, use sexual reproduction\r\n else: \r\n return sexual(candidate_seed, pop, n, max_seed_area)\r\n # Set the correct dimensions for the new seed\r\n s1.xspan = s1.cells.shape[0]\r\n s1.yspan = s1.cells.shape[1]\r\n # Update count of living cells\r\n s1.num_living = s1.count_ones()\r\n # Find the least fit old seed in the population. It's not a problem\r\n # if there are ties.\r\n s2 = find_worst_seed(pop)\r\n # Now we have:\r\n #\r\n # s0 = seed 0\r\n # s1 = left or right side of seed 0\r\n # s2 = the least fit old seed, which will be replaced by s1\r\n #\r\n # Replace the least fit old seed in the population (s2) with the\r\n # chosen part (s1).\r\n i = s2.address # find the position of the old seed (s2)\r\n s1.address = i # copy the old position of the old seed into s1\r\n pop[i] = s1 # replace s2 (old seed) in population (pop) with s1\r\n # Build a history for the new seed, by matching it against all seeds\r\n # in the population.\r\n width_factor = mparam.width_factor\r\n height_factor = mparam.height_factor\r\n time_factor = mparam.time_factor\r\n num_trials = mparam.num_trials\r\n pop_size = len(pop)\r\n for j in range(pop_size):\r\n update_history(g, pop, i, j, width_factor, height_factor, \\\r\n time_factor, num_trials)\r\n update_similarity(pop, i, j)\r\n # Report on the new history of the new seed\r\n message = \"Run: {}\".format(n) + \\\r\n \" Whole fitness (s0): {:.3f}\".format(s0.fitness()) + \\\r\n \" Fragment fitness (s1): {:.3f}\".format(s1.fitness()) + \\\r\n \" Replaced seed fitness (s2): {:.3f}\\n\".format(s2.fitness())\r\n # Return with the updated population and a message.\r\n return [pop, message]\r\n#\r\n# symbiotic(candidate_seed, pop, n, max_seed_area) \r\n# -- returns [pop, message]\r\n#\r\ndef symbiotic(candidate_seed, pop, n, max_seed_area):\r\n \"\"\"\r\n Create a new seed by joining two existing seeds (fusion) or\r\n by splitting one seed into two seeds (fission). If fission\r\n is chosen, only one of the two resulting seeds is used.\r\n If neither fission nor fusion is chosen, we default to \r\n sexual reproduction.\r\n \"\"\"\r\n # Decide whether to use fission, fusion, or sexual reproduction.\r\n # To avoid bias, it makes sense to set these two probabilities to\r\n # the same value. Because fusion can result in large seeds, which\r\n # will slow down the simulation, it makes sense to set the\r\n # probability of fusion relatively low.\r\n #\r\n prob_fission = mparam.prob_fission\r\n prob_fusion = mparam.prob_fusion\r\n #\r\n uniform_random = rand.uniform(0, 1)\r\n #\r\n if (uniform_random < prob_fission):\r\n # this will be invoked with a probability of prob_fission\r\n return fission(candidate_seed, pop, n, max_seed_area)\r\n elif (uniform_random < (prob_fission + prob_fusion)):\r\n # this will be invoked with a probability of prob_fusion\r\n return fusion(candidate_seed, pop, n, max_seed_area)\r\n else:\r\n # if neither fission nor fusion, then sexual reproduction\r\n return sexual(candidate_seed, pop, n, max_seed_area)\r\n#\r\n# hash_pickles(pickle_list) -- returns pickle_hash\r\n#\r\ndef hash_pickles(pickle_list):\r\n \"\"\"\r\n Assume we have a list of pickle files of the following general form:\r\n ------------------------------------------------\r\n log-2019-02-22-12h-45m-00s-pickle-0.bin,\r\n log-2019-02-22-12h-45m-00s-pickle-1.bin, \r\n ...\r\n log-2019-02-22-12h-45m-00s-pickle-100.bin,\r\n log-2019-02-22-12h-45m-12s-pickle-0.bin,\r\n log-2019-02-22-12h-45m-12s-pickle-1.bin, \r\n ...\r\n log-2019-02-22-12h-45m-12s-pickle-100.bin\r\n ------------------------------------------------\r\n We split each pickle name into a base part (\"log-2019-02-22-12h-45m-00s\")\r\n and a numerical part (\"0\", \"1\", ..., \"100\") and we return a hash table\r\n that maps each unique base part to the maximum numerical part for that\r\n given base part (e.g., in examples above, the maximum is 100).\r\n \"\"\"\r\n # initialize the hash of pickles\r\n pickle_hash = {}\r\n # process the items in the pickle list\r\n for pickle in pickle_list:\r\n # extract the base part of the pickle\r\n pickle_base_search = re.search(r'(log-.+\\d\\ds)-pickle-', pickle)\r\n assert pickle_base_search, \"No pickles were found in the directory.\"\r\n pickle_base = pickle_base_search.group(1)\r\n # extract the numerical part of the pickle\r\n pickle_num_search = re.search(r'-pickle-(\\d+)\\.bin', pickle)\r\n assert pickle_num_search, \"No pickles were found in the directory.\"\r\n pickle_num = int(pickle_num_search.group(1))\r\n # use the base part of the pickle as the hash key\r\n # and set the value to the largest numerical part\r\n if (pickle_base in pickle_hash):\r\n current_largest = pickle_hash[pickle_base]\r\n if (pickle_num > current_largest):\r\n pickle_hash[pickle_base] = pickle_num\r\n else:\r\n pickle_hash[pickle_base] = pickle_num\r\n #\r\n return pickle_hash\r\n#\r\n# choose_pickles(g) -- returns [pickle_dir, analysis_dir, \r\n# sorted_pickle_names, smallest_pickle_size]\r\n#\r\ndef choose_pickles(g):\r\n \"\"\"\r\n Present a GUI to ask the users which folder of pickles they\r\n would like to analyze.\r\n \"\"\"\r\n #\r\n # Open a dialog window and ask the user to select a folder.\r\n #\r\n g.note(\"Analyze Pickles\\n\\n\" + \\\r\n \"Select a FOLDER of pickled seeds (not a FILE of seeds).\\n\" + \\\r\n \"The pickles will be analyzed and the results will be\\n\" + \\\r\n \"stored in the same directory as the pickles.\\n\")\r\n #\r\n pickle_dir = g.opendialog(\"Choose a folder of pickled seeds\", \\\r\n \"dir\", g.getdir(\"app\"))\r\n #\r\n analysis_dir = pickle_dir\r\n #\r\n g.note(\"Verify Selection\\n\\n\" + \\\r\n \"The folder of pickled seeds:\\n\\n\" + \\\r\n \" \" + pickle_dir + \"\\n\\n\" + \\\r\n \"The folder for the analysis results:\\n\\n\" + \\\r\n \" \" + analysis_dir + \"\\n\\n\" + \\\r\n \"Exit now if this is incorrect.\")\r\n #\r\n # Make a list of the pickles in pickle_dir.\r\n #\r\n pickle_list = []\r\n for file in os.listdir(pickle_dir):\r\n if file.endswith(\".bin\"):\r\n pickle_list.append(file)\r\n #\r\n # Verify that there are some \".bin\" files in the list.\r\n #\r\n if (len(pickle_list) == 0):\r\n g.note(\"No pickles were found in the directory:\\n\\n\" + \\\r\n \" \" + pickle_dir + \"\\n\\n\" + \\\r\n \"Exiting now.\")\r\n sys.exit(0)\r\n #\r\n # Make a hash table that maps pickle names to the last\r\n # generation number of the given group of pickles.\r\n #\r\n pickle_hash = hash_pickles(pickle_list)\r\n #\r\n # Calculate the size of the smallest group of pickles.\r\n #\r\n smallest_pickle_size = min(pickle_hash.values())\r\n #\r\n # Report the base parts of the pickles and their maximum\r\n # values\r\n #\r\n sorted_pickle_names = sorted(pickle_hash.keys())\r\n pickle_note = \"\"\r\n for pickle_base in sorted_pickle_names:\r\n pickle_note = pickle_note + \\\r\n pickle_base + \" ranges from 0 to \" + \\\r\n str(pickle_hash[pickle_base]) + \"\\n\"\r\n g.note(\"These pickles were found:\\n\\n\" +\r\n pickle_note + \"\\n\" + \\\r\n \"The analysis will range from 0 to \" + \\\r\n str(smallest_pickle_size) + \"\\n\\n\" + \\\r\n \"Exit now if this is not what you expected.\")\r\n #\r\n return [pickle_dir, analysis_dir, \\\r\n sorted_pickle_names, smallest_pickle_size]\r\n#\r\n# validate_designed_seed(g, seed_path, max_area) -- returns 0 for bad, 1 for good\r\n#\r\ndef validate_designed_seed(g, seed_path, max_area):\r\n \"\"\"\r\n This function checks whether we can convert a human-made pattern file\r\n into a seed.\r\n \"\"\"\r\n #\r\n # We only want *.rle or *.lif\r\n #\r\n file_base, file_extension = os.path.splitext(seed_path)\r\n if (file_extension != \".rle\") and (file_extension != \".lif\"):\r\n return 0\r\n #\r\n # Golly has two kinds of cell lists, one that contains an even number \r\n # of members and one that contains an odd number of members. The \r\n # former is intended for two states (0 and 1) and the latter is intended \r\n # for more than two states. Here we are only interested in patterns designed \r\n # for the Game of Life, which only has two states.\r\n #\r\n cell_list = g.load(seed_path)\r\n #\r\n # Make sure cell_list is not too small\r\n #\r\n too_small = 5\r\n #\r\n if (len(cell_list) <= too_small):\r\n return 0\r\n #\r\n # We can only handle cell_list if it has an even number of members.\r\n #\r\n if (len(cell_list) % 2 != 0):\r\n return 0\r\n #\r\n # See how big this pattern is.\r\n #\r\n min_x = cell_list[0]\r\n max_x = cell_list[0]\r\n min_y = cell_list[1]\r\n max_y = cell_list[1]\r\n #\r\n for i in range(0, len(cell_list), 2):\r\n pair = (cell_list[i], cell_list[i + 1])\r\n (x, y) = pair\r\n if (x < min_x):\r\n min_x = x\r\n if (x > max_x):\r\n max_x = x\r\n if (y < min_y):\r\n min_y = y\r\n if (y > max_y):\r\n max_y = y\r\n #\r\n # Make sure it's not too big.\r\n #\r\n if (max_x * max_y > max_area):\r\n return 0\r\n #\r\n # Make sure it's not too small.\r\n #\r\n if (max_x == 0) or (max_y == 0):\r\n return 0\r\n #\r\n # Passed all tests.\r\n #\r\n return 1\r\n#\r\n# load_designed_seed(g, seed_path) -- returns seed\r\n#\r\ndef load_designed_seed(g, seed_path):\r\n \"\"\"\r\n Given the path to a human-designed Game of Life pattern, load the\r\n file and convert it to a seed.\r\n \"\"\"\r\n #\r\n # Golly has two kinds of cell lists, one that contains an even number \r\n # of members and one that contains an odd number of members. The \r\n # former is intended for two states (0 and 1) and the latter is intended \r\n # for more than two states. Here we are only interested in patterns designed \r\n # for the Game of Life, which only has two states.\r\n #\r\n cell_list = g.load(seed_path)\r\n #\r\n # Make sure that cell_list is the type of list that contains an even\r\n # number of members. Make sure cell_list is not unreasonably small.\r\n #\r\n assert len(cell_list) % 2 == 0\r\n assert len(cell_list) > 10\r\n #\r\n # Convert cell_list to a list of (x, y) pairs.\r\n #\r\n pair_list = []\r\n min_x = cell_list[0]\r\n max_x = cell_list[0]\r\n min_y = cell_list[1]\r\n max_y = cell_list[1]\r\n #\r\n for i in range(0, len(cell_list), 2):\r\n pair = (cell_list[i], cell_list[i + 1])\r\n pair_list.append(pair)\r\n (x, y) = pair\r\n if (x < min_x):\r\n min_x = x\r\n if (x > max_x):\r\n max_x = x\r\n if (y < min_y):\r\n min_y = y\r\n if (y > max_y):\r\n max_y = y\r\n #\r\n # Convert pair_list to a seed. Start with a seed full of\r\n # zeros and set the cells given in pair_list to ones.\r\n #\r\n assert min_x == 0\r\n assert min_y == 0\r\n assert max_x > 0\r\n assert max_y > 0\r\n #\r\n s_xspan = max_x + 1\r\n s_yspan = max_y + 1\r\n #\r\n seed = mclass.Seed(s_xspan, s_yspan, mparam.pop_size)\r\n #\r\n for pair in pair_list:\r\n (x, y) = pair\r\n seed.cells[x][y] = 1\r\n #\r\n # Count the initial number of living cells in the seed\r\n # and store the count.\r\n #\r\n seed.num_living = seed.count_ones()\r\n #\r\n assert seed.num_living > 0\r\n #\r\n return seed\r\n#\r\n#\r\n" ]
[ [ "numpy.amax", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Stanislas0/grb
[ "96fc521f57fdb06ab6a3c442fcf4a8bc97894829" ]
[ "grb/utils/trainer.py" ]
[ "import os\nimport time\n\nimport torch\nimport torch.nn.functional as F\n\nimport grb.utils as utils\nfrom grb.evaluator import metric\n\n\nclass Trainer(object):\n def __init__(self,\n dataset,\n optimizer,\n loss,\n adj_norm_func=None,\n feat_norm=None,\n lr_scheduler=None,\n early_stop=None,\n eval_metric=metric.eval_acc,\n device='cpu'):\n\n # Load dataset\n self.adj = dataset.adj\n self.features = dataset.features\n self.labels = dataset.labels\n self.train_mask = dataset.train_mask\n self.val_mask = dataset.val_mask\n self.test_mask = dataset.test_mask\n self.num_classes = dataset.num_classes\n self.adj_norm_func = adj_norm_func\n\n self.device = device\n self.features = utils.feat_preprocess(features=self.features,\n feat_norm=feat_norm,\n device=self.device)\n self.labels = utils.label_preprocess(labels=self.labels,\n device=self.device)\n\n # Settings\n self.optimizer = optimizer\n self.loss = loss\n self.eval_metric = eval_metric\n\n # Learning rate scheduling\n if lr_scheduler:\n self.lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n self.optimizer,\n mode='min',\n patience=100,\n factor=0.75,\n min_lr=0.0,\n verbose=True)\n else:\n self.lr_scheduler = lr_scheduler\n\n # Early stop\n if early_stop:\n self.early_stop = EarlyStop()\n else:\n self.early_stop = early_stop\n\n def train(self,\n model,\n n_epoch,\n save_dir=None,\n save_name=None,\n eval_every=10,\n save_after=0,\n train_mode=\"trasductive\",\n dropout=0,\n verbose=True):\n model.to(self.device)\n model.train()\n\n if save_dir is None:\n cur_time = time.strftime(\"%Y_%m_%d_%H_%M_%S\", time.localtime())\n save_dir = \"./tmp_{}\".format(cur_time)\n else:\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n if save_name is None:\n save_name = \"checkpoint.pt\"\n else:\n if save_name.split(\".\")[-1] != \"pt\":\n save_name = save_name + \".pt\"\n\n train_score_list = []\n val_score_list = []\n best_val_score = 0.0\n features = self.features\n train_mask = self.train_mask\n val_mask = self.val_mask\n labels = self.labels\n\n if train_mode == \"inductive\":\n # Inductive setting\n train_val_mask = torch.logical_or(train_mask, val_mask)\n train_val_index = torch.where(train_val_mask)[0]\n train_index, val_index = torch.where(train_mask)[0], torch.where(val_mask)[0]\n train_index_induc, val_index_induc = utils.get_index_induc(train_index, val_index)\n train_mask_induc = torch.zeros(len(train_val_index), dtype=bool)\n train_mask_induc[train_index_induc] = True\n val_mask_induc = torch.zeros(len(train_val_index), dtype=bool)\n val_mask_induc[val_index_induc] = True\n\n features_train = features[train_mask]\n features_val = features[train_val_mask]\n adj_train = utils.adj_preprocess(self.adj,\n adj_norm_func=self.adj_norm_func,\n mask=self.train_mask,\n model_type=model.model_type,\n device=self.device)\n adj_val = utils.adj_preprocess(self.adj,\n adj_norm_func=self.adj_norm_func,\n mask=train_val_mask,\n model_type=model.model_type,\n device=self.device)\n\n for epoch in range(n_epoch):\n logits = model(features_train, adj_train, dropout)\n if self.loss == F.nll_loss:\n out = F.log_softmax(logits, 1)\n train_loss = self.loss(out, labels[train_mask])\n logits_val = model(features_val, adj_val, dropout)\n out_val = F.log_softmax(logits_val, 1)\n val_loss = self.loss(out_val[val_mask_induc], labels[val_mask])\n elif self.loss == F.cross_entropy:\n out = logits\n train_loss = self.loss(out, labels[train_mask])\n logits_val = model(features_val, adj_val, dropout)\n out_val = logits_val\n val_loss = self.loss(out_val[val_mask_induc], labels[val_mask])\n elif self.loss == F.binary_cross_entropy:\n out = F.sigmoid(logits)\n train_loss = self.loss(out, labels[train_mask].float())\n logits_val = model(features_val, adj_val, dropout)\n out_val = F.sigmoid(logits_val)\n val_loss = self.loss(out_val[val_mask_induc], labels[val_mask].float())\n elif self.loss == F.binary_cross_entropy_with_logits:\n out = logits\n train_loss = self.loss(out, labels[train_mask].float())\n logits_val = model(features_val, adj_val, dropout)\n out_val = F.sigmoid(logits_val)\n val_loss = self.loss(out_val[val_mask_induc], labels[val_mask].float())\n\n self.optimizer.zero_grad()\n train_loss.backward()\n self.optimizer.step()\n\n if self.lr_scheduler:\n self.lr_scheduler.step(val_loss)\n if self.early_stop:\n self.early_stop(val_loss)\n if self.early_stop.stop:\n print(\"Training early stopped.\")\n utils.save_model(model, save_dir, \"checkpoint_final.pt\")\n return\n\n if epoch % eval_every == 0:\n train_score = self.eval_metric(out, labels[train_mask], mask=None)\n val_score = self.eval_metric(out_val, labels[train_val_mask], mask=val_mask_induc)\n train_score_list.append(train_score)\n val_score_list.append(val_score)\n if val_score > best_val_score:\n best_val_score = val_score\n if epoch > save_after:\n print(\"Epoch {:05d} | Best validation score: {:.4f}\".format(epoch, best_val_score))\n utils.save_model(model, save_dir, save_name)\n if verbose:\n print(\n 'Epoch {:05d} | Train loss {:.4f} | Train score {:.4f} '\n '| Val loss {:.4f} | Val score {:.4f}'.format(\n epoch, train_loss, train_score, val_loss, val_score))\n else:\n # Transductive setting\n adj = utils.adj_preprocess(self.adj,\n adj_norm_func=self.adj_norm_func,\n mask=None,\n model_type=model.model_type,\n device=self.device)\n for epoch in range(n_epoch):\n logits = model(features, adj, dropout)\n if self.loss == F.nll_loss:\n out = F.log_softmax(logits, 1)\n train_loss = self.loss(out[train_mask], labels[train_mask])\n val_loss = self.loss(out[val_mask], labels[val_mask])\n elif self.loss == F.cross_entropy:\n out = logits\n train_loss = self.loss(out[train_mask], labels[train_mask])\n val_loss = self.loss(out[val_mask], labels[val_mask])\n elif self.loss == F.binary_cross_entropy:\n out = F.sigmoid(logits)\n train_loss = self.loss(out[train_mask], labels[train_mask].float())\n val_loss = self.loss(out[val_mask], labels[val_mask].float())\n elif self.loss == F.binary_cross_entropy_with_logits:\n out = logits\n train_loss = self.loss(out[train_mask], labels[train_mask].float())\n val_loss = self.loss(out[val_mask], labels[val_mask].float())\n\n self.optimizer.zero_grad()\n train_loss.backward()\n self.optimizer.step()\n\n if self.lr_scheduler:\n self.lr_scheduler.step(val_loss)\n if self.early_stop:\n self.early_stop(val_loss)\n if self.early_stop.stop:\n print(\"Training early stopped.\")\n utils.save_model(model, save_dir, \"checkpoint_final.pt\")\n return\n\n if epoch % eval_every == 0:\n train_score = self.eval_metric(out, labels, train_mask)\n val_score = self.eval_metric(out, labels, val_mask)\n train_score_list.append(train_score)\n val_score_list.append(val_score)\n if val_score > best_val_score:\n best_val_score = val_score\n if epoch > save_after:\n print(\"Epoch {:05d} | Best validation score: {:.4f}\".format(epoch, best_val_score))\n utils.save_model(model, save_dir, save_name)\n if verbose:\n print(\n 'Epoch {:05d} | Train loss {:.4f} | Train score {:.4f} '\n '| Val loss {:.4f} | Val score {:.4f}'.format(\n epoch, train_loss, train_score, val_loss, val_score))\n\n utils.save_model(model, save_dir, \"checkpoint_final.pt\")\n\n def inference(self, model):\n model.to(self.device)\n model.eval()\n adj = utils.adj_preprocess(self.adj,\n adj_norm_func=self.adj_norm_func,\n model_type=model.model_type,\n device=self.device)\n logits = model(self.features, adj, dropout=0)\n if self.loss == F.nll_loss:\n out = F.log_softmax(logits, 1)\n elif self.loss == F.binary_cross_entropy:\n out = F.sigmoid(logits)\n else:\n out = logits\n test_score = self.eval_metric(out, self.labels, self.test_mask)\n\n return logits, test_score\n\n\nclass EarlyStop(object):\n def __init__(self, patience=1000, epsilon=1e-5):\n self.patience = patience\n self.epsilon = epsilon\n self.min_loss = None\n self.stop = False\n self.count = 0\n\n def __call__(self, loss):\n if self.min_loss is None:\n self.min_loss = loss\n elif self.min_loss - loss > self.epsilon:\n self.count = 0\n self.min_loss = loss\n elif self.min_loss - loss < self.epsilon:\n self.count += 1\n if self.count > self.patience:\n self.stop = True\n" ]
[ [ "torch.optim.lr_scheduler.ReduceLROnPlateau", "torch.nn.functional.log_softmax", "torch.nn.functional.sigmoid", "torch.where", "torch.logical_or" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
glhr/yolact
[ "5e573ce940a76a54ef58fd0d3d7891f61816c1bc" ]
[ "yolact.py" ]
[ "import torch, torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.models.resnet import Bottleneck\nimport numpy as np\nfrom itertools import product\nfrom math import sqrt\nfrom typing import List\nfrom collections import defaultdict\n\nfrom data.config import cfg, mask_type\nfrom layers import Detect\nfrom layers.interpolate import InterpolateModule\nfrom backbone import construct_backbone\n\nimport torch.backends.cudnn as cudnn\nfrom utils import timer\nfrom utils.functions import MovingAverage, make_net\n\n# This is required for Pytorch 1.0.1 on Windows to initialize Cuda on some driver versions.\n# See the bug report here: https://github.com/pytorch/pytorch/issues/17108\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# As of March 10, 2019, Pytorch DataParallel still doesn't support JIT Script Modules\nuse_jit = torch.cuda.device_count() <= 1\nif not use_jit:\n print('Multiple GPUs detected! Turning off JIT.')\n\nScriptModuleWrapper = torch.jit.ScriptModule if use_jit else nn.Module\nscript_method_wrapper = torch.jit.script_method if use_jit else lambda fn, _rcn=None: fn\n\n\n\nclass Concat(nn.Module):\n def __init__(self, nets, extra_params):\n super().__init__()\n\n self.nets = nn.ModuleList(nets)\n self.extra_params = extra_params\n\n def forward(self, x):\n # Concat each along the channel dimension\n return torch.cat([net(x) for net in self.nets], dim=1, **self.extra_params)\n\nprior_cache = defaultdict(lambda: None)\n\nclass PredictionModule(nn.Module):\n \"\"\"\n The (c) prediction module adapted from DSSD:\n https://arxiv.org/pdf/1701.06659.pdf\n\n Note that this is slightly different to the module in the paper\n because the Bottleneck block actually has a 3x3 convolution in\n the middle instead of a 1x1 convolution. Though, I really can't\n be arsed to implement it myself, and, who knows, this might be\n better.\n\n Args:\n - in_channels: The input feature size.\n - out_channels: The output feature size (must be a multiple of 4).\n - aspect_ratios: A list of lists of priorbox aspect ratios (one list per scale).\n - scales: A list of priorbox scales relative to this layer's convsize.\n For instance: If this layer has convouts of size 30x30 for\n an image of size 600x600, the 'default' (scale\n of 1) for this layer would produce bounding\n boxes with an area of 20x20px. If the scale is\n .5 on the other hand, this layer would consider\n bounding boxes with area 10x10px, etc.\n - parent: If parent is a PredictionModule, this module will use all the layers\n from parent instead of from this module.\n \"\"\"\n\n def __init__(self, in_channels, out_channels=1024, aspect_ratios=[[1]], scales=[1], parent=None, index=0):\n super().__init__()\n\n self.num_classes = cfg.num_classes\n self.mask_dim = cfg.mask_dim # Defined by Yolact\n self.num_priors = sum(len(x)*len(scales) for x in aspect_ratios)\n self.parent = [parent] # Don't include this in the state dict\n self.index = index\n self.num_heads = cfg.num_heads # Defined by Yolact\n\n if cfg.mask_proto_split_prototypes_by_head and cfg.mask_type == mask_type.lincomb:\n self.mask_dim = self.mask_dim // self.num_heads\n\n if cfg.mask_proto_prototypes_as_features:\n in_channels += self.mask_dim\n\n if parent is None:\n if cfg.extra_head_net is None:\n out_channels = in_channels\n else:\n self.upfeature, out_channels = make_net(in_channels, cfg.extra_head_net)\n\n if cfg.use_prediction_module:\n self.block = Bottleneck(out_channels, out_channels // 4)\n self.conv = nn.Conv2d(out_channels, out_channels, kernel_size=1, bias=True)\n self.bn = nn.BatchNorm2d(out_channels)\n\n self.bbox_layer = nn.Conv2d(out_channels, self.num_priors * 4, **cfg.head_layer_params)\n self.conf_layer = nn.Conv2d(out_channels, self.num_priors * self.num_classes, **cfg.head_layer_params)\n self.mask_layer = nn.Conv2d(out_channels, self.num_priors * self.mask_dim, **cfg.head_layer_params)\n\n if cfg.use_mask_scoring:\n self.score_layer = nn.Conv2d(out_channels, self.num_priors, **cfg.head_layer_params)\n\n if cfg.use_instance_coeff:\n self.inst_layer = nn.Conv2d(out_channels, self.num_priors * cfg.num_instance_coeffs, **cfg.head_layer_params)\n\n # What is this ugly lambda doing in the middle of all this clean prediction module code?\n def make_extra(num_layers):\n if num_layers == 0:\n return lambda x: x\n else:\n # Looks more complicated than it is. This just creates an array of num_layers alternating conv-relu\n return nn.Sequential(*sum([[\n nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),\n nn.ReLU(inplace=True)\n ] for _ in range(num_layers)], []))\n\n self.bbox_extra, self.conf_extra, self.mask_extra = [make_extra(x) for x in cfg.extra_layers]\n\n if cfg.mask_type == mask_type.lincomb and cfg.mask_proto_coeff_gate:\n self.gate_layer = nn.Conv2d(out_channels, self.num_priors * self.mask_dim, kernel_size=3, padding=1)\n\n self.aspect_ratios = aspect_ratios\n self.scales = scales\n\n self.priors = None\n self.last_conv_size = None\n self.last_img_size = None\n\n def forward(self, x):\n \"\"\"\n Args:\n - x: The convOut from a layer in the backbone network\n Size: [batch_size, in_channels, conv_h, conv_w])\n\n Returns a tuple (bbox_coords, class_confs, mask_output, prior_boxes) with sizes\n - bbox_coords: [batch_size, conv_h*conv_w*num_priors, 4]\n - class_confs: [batch_size, conv_h*conv_w*num_priors, num_classes]\n - mask_output: [batch_size, conv_h*conv_w*num_priors, mask_dim]\n - prior_boxes: [conv_h*conv_w*num_priors, 4]\n \"\"\"\n # In case we want to use another module's layers\n src = self if self.parent[0] is None else self.parent[0]\n\n conv_h = x.size(2)\n conv_w = x.size(3)\n\n if cfg.extra_head_net is not None:\n x = src.upfeature(x)\n\n if cfg.use_prediction_module:\n # The two branches of PM design (c)\n a = src.block(x)\n\n b = src.conv(x)\n b = src.bn(b)\n b = F.relu(b)\n\n # TODO: Possibly switch this out for a product\n x = a + b\n\n bbox_x = src.bbox_extra(x)\n conf_x = src.conf_extra(x)\n mask_x = src.mask_extra(x)\n\n bbox = src.bbox_layer(bbox_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, 4)\n conf = src.conf_layer(conf_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.num_classes)\n\n if cfg.eval_mask_branch:\n mask = src.mask_layer(mask_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.mask_dim)\n else:\n mask = torch.zeros(x.size(0), bbox.size(1), self.mask_dim, device=bbox.device)\n\n if cfg.use_mask_scoring:\n score = src.score_layer(x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, 1)\n\n if cfg.use_instance_coeff:\n inst = src.inst_layer(x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, cfg.num_instance_coeffs)\n\n # See box_utils.decode for an explanation of this\n if cfg.use_yolo_regressors:\n bbox[:, :, :2] = torch.sigmoid(bbox[:, :, :2]) - 0.5\n bbox[:, :, 0] /= conv_w\n bbox[:, :, 1] /= conv_h\n\n if cfg.eval_mask_branch:\n if cfg.mask_type == mask_type.direct:\n mask = torch.sigmoid(mask)\n elif cfg.mask_type == mask_type.lincomb:\n mask = cfg.mask_proto_coeff_activation(mask)\n\n if cfg.mask_proto_coeff_gate:\n gate = src.gate_layer(x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.mask_dim)\n mask = mask * torch.sigmoid(gate)\n\n if cfg.mask_proto_split_prototypes_by_head and cfg.mask_type == mask_type.lincomb:\n mask = F.pad(mask, (self.index * self.mask_dim, (self.num_heads - self.index - 1) * self.mask_dim), mode='constant', value=0)\n\n priors = self.make_priors(conv_h, conv_w, x.device)\n\n preds = { 'loc': bbox, 'conf': conf, 'mask': mask, 'priors': priors }\n\n if cfg.use_mask_scoring:\n preds['score'] = score\n\n if cfg.use_instance_coeff:\n preds['inst'] = inst\n\n return preds\n\n def make_priors(self, conv_h, conv_w, device):\n \"\"\" Note that priors are [x,y,width,height] where (x,y) is the center of the box. \"\"\"\n global prior_cache\n size = (conv_h, conv_w)\n\n with timer.env('makepriors'):\n if self.last_img_size != (cfg._tmp_img_w, cfg._tmp_img_h):\n prior_data = []\n\n # Iteration order is important (it has to sync up with the convout)\n for j, i in product(range(conv_h), range(conv_w)):\n # +0.5 because priors are in center-size notation\n x = (i + 0.5) / conv_w\n y = (j + 0.5) / conv_h\n\n for ars in self.aspect_ratios:\n for scale in self.scales:\n for ar in ars:\n if not cfg.backbone.preapply_sqrt:\n ar = sqrt(ar)\n\n if cfg.backbone.use_pixel_scales:\n w = scale * ar / cfg.max_size\n h = scale / ar / cfg.max_size\n else:\n w = scale * ar / conv_w\n h = scale / ar / conv_h\n\n # This is for backward compatability with a bug where I made everything square by accident\n if cfg.backbone.use_square_anchors:\n h = w\n\n prior_data += [x, y, w, h]\n\n self.priors = torch.Tensor(prior_data, device=device).view(-1, 4).detach()\n self.priors.requires_grad = False\n self.last_img_size = (cfg._tmp_img_w, cfg._tmp_img_h)\n self.last_conv_size = (conv_w, conv_h)\n prior_cache[size] = None\n elif self.priors.device != device:\n # This whole weird situation is so that DataParalell doesn't copy the priors each iteration\n if prior_cache[size] is None:\n prior_cache[size] = {}\n\n if device not in prior_cache[size]:\n prior_cache[size][device] = self.priors.to(device)\n\n self.priors = prior_cache[size][device]\n\n return self.priors\n\nclass FPN(ScriptModuleWrapper):\n \"\"\"\n Implements a general version of the FPN introduced in\n https://arxiv.org/pdf/1612.03144.pdf\n\n Parameters (in cfg.fpn):\n - num_features (int): The number of output features in the fpn layers.\n - interpolation_mode (str): The mode to pass to F.interpolate.\n - num_downsample (int): The number of downsampled layers to add onto the selected layers.\n These extra layers are downsampled from the last selected layer.\n\n Args:\n - in_channels (list): For each conv layer you supply in the forward pass,\n how many features will it have?\n \"\"\"\n __constants__ = ['interpolation_mode', 'num_downsample', 'use_conv_downsample', 'relu_pred_layers',\n 'lat_layers', 'pred_layers', 'downsample_layers', 'relu_downsample_layers']\n\n def __init__(self, in_channels):\n super().__init__()\n\n self.lat_layers = nn.ModuleList([\n nn.Conv2d(x, cfg.fpn.num_features, kernel_size=1)\n for x in reversed(in_channels)\n ])\n\n # This is here for backwards compatability\n padding = 1 if cfg.fpn.pad else 0\n self.pred_layers = nn.ModuleList([\n nn.Conv2d(cfg.fpn.num_features, cfg.fpn.num_features, kernel_size=3, padding=padding)\n for _ in in_channels\n ])\n\n if cfg.fpn.use_conv_downsample:\n self.downsample_layers = nn.ModuleList([\n nn.Conv2d(cfg.fpn.num_features, cfg.fpn.num_features, kernel_size=3, padding=1, stride=2)\n for _ in range(cfg.fpn.num_downsample)\n ])\n\n self.interpolation_mode = cfg.fpn.interpolation_mode\n self.num_downsample = cfg.fpn.num_downsample\n self.use_conv_downsample = cfg.fpn.use_conv_downsample\n self.relu_downsample_layers = cfg.fpn.relu_downsample_layers\n self.relu_pred_layers = cfg.fpn.relu_pred_layers\n\n @script_method_wrapper\n def forward(self, convouts:List[torch.Tensor]):\n \"\"\"\n Args:\n - convouts (list): A list of convouts for the corresponding layers in in_channels.\n Returns:\n - A list of FPN convouts in the same order as x with extra downsample layers if requested.\n \"\"\"\n\n out = []\n x = torch.zeros(1, device=convouts[0].device)\n for i in range(len(convouts)):\n out.append(x)\n\n # For backward compatability, the conv layers are stored in reverse but the input and output is\n # given in the correct order. Thus, use j=-i-1 for the input and output and i for the conv layers.\n j = len(convouts)\n for lat_layer in self.lat_layers:\n j -= 1\n\n if j < len(convouts) - 1:\n _, _, h, w = convouts[j].size()\n x = F.interpolate(x, size=(h, w), mode=self.interpolation_mode, align_corners=False)\n\n x = x + lat_layer(convouts[j])\n out[j] = x\n\n # This janky second loop is here because TorchScript.\n j = len(convouts)\n for pred_layer in self.pred_layers:\n j -= 1\n out[j] = pred_layer(out[j])\n\n if self.relu_pred_layers:\n F.relu(out[j], inplace=True)\n\n cur_idx = len(out)\n\n # In the original paper, this takes care of P6\n if self.use_conv_downsample:\n for downsample_layer in self.downsample_layers:\n out.append(downsample_layer(out[-1]))\n else:\n for idx in range(self.num_downsample):\n # Note: this is an untested alternative to out.append(out[-1][:, :, ::2, ::2]). Thanks TorchScript.\n out.append(nn.functional.max_pool2d(out[-1], 1, stride=2))\n\n if self.relu_downsample_layers:\n for idx in range(len(out) - cur_idx):\n out[idx] = F.relu(out[idx + cur_idx], inplace=False)\n\n return out\n\nclass FastMaskIoUNet(ScriptModuleWrapper):\n\n def __init__(self):\n super().__init__()\n input_channels = 1\n last_layer = [(cfg.num_classes-1, 1, {})]\n self.maskiou_net, _ = make_net(input_channels, cfg.maskiou_net + last_layer, include_last_relu=True)\n\n def forward(self, x):\n x = self.maskiou_net(x)\n maskiou_p = F.max_pool2d(x, kernel_size=x.size()[2:]).squeeze(-1).squeeze(-1)\n\n return maskiou_p\n\n\n\nclass Yolact(nn.Module):\n \"\"\"\n\n\n ██╗ ██╗ ██████╗ ██╗ █████╗ ██████╗████████╗\n ╚██╗ ██╔╝██╔═══██╗██║ ██╔══██╗██╔════╝╚══██╔══╝\n ╚████╔╝ ██║ ██║██║ ███████║██║ ██║\n ╚██╔╝ ██║ ██║██║ ██╔══██║██║ ██║\n ██║ ╚██████╔╝███████╗██║ ██║╚██████╗ ██║\n ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝\n\n\n You can set the arguments by changing them in the backbone config object in config.py.\n\n Parameters (in cfg.backbone):\n - selected_layers: The indices of the conv layers to use for prediction.\n - pred_scales: A list with len(selected_layers) containing tuples of scales (see PredictionModule)\n - pred_aspect_ratios: A list of lists of aspect ratios with len(selected_layers) (see PredictionModule)\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n self.backbone = construct_backbone(cfg.backbone)\n\n if cfg.freeze_bn:\n self.freeze_bn()\n\n # Compute mask_dim here and add it back to the config. Make sure Yolact's constructor is called early!\n if cfg.mask_type == mask_type.direct:\n cfg.mask_dim = cfg.mask_size**2\n elif cfg.mask_type == mask_type.lincomb:\n if cfg.mask_proto_use_grid:\n self.grid = torch.Tensor(np.load(cfg.mask_proto_grid_file))\n self.num_grids = self.grid.size(0)\n else:\n self.num_grids = 0\n\n self.proto_src = cfg.mask_proto_src\n\n if self.proto_src is None: in_channels = 3\n elif cfg.fpn is not None: in_channels = cfg.fpn.num_features\n else: in_channels = self.backbone.channels[self.proto_src]\n in_channels += self.num_grids\n\n # The include_last_relu=false here is because we might want to change it to another function\n self.proto_net, cfg.mask_dim = make_net(in_channels, cfg.mask_proto_net, include_last_relu=False)\n\n if cfg.mask_proto_bias:\n cfg.mask_dim += 1\n\n\n self.selected_layers = cfg.backbone.selected_layers\n src_channels = self.backbone.channels\n\n if cfg.use_maskiou:\n self.maskiou_net = FastMaskIoUNet()\n\n if cfg.fpn is not None:\n # Some hacky rewiring to accomodate the FPN\n self.fpn = FPN([src_channels[i] for i in self.selected_layers])\n self.selected_layers = list(range(len(self.selected_layers) + cfg.fpn.num_downsample))\n src_channels = [cfg.fpn.num_features] * len(self.selected_layers)\n\n\n self.prediction_layers = nn.ModuleList()\n cfg.num_heads = len(self.selected_layers)\n\n for idx, layer_idx in enumerate(self.selected_layers):\n # If we're sharing prediction module weights, have every module's parent be the first one\n parent = None\n if cfg.share_prediction_module and idx > 0:\n parent = self.prediction_layers[0]\n\n pred = PredictionModule(src_channels[layer_idx], src_channels[layer_idx],\n aspect_ratios = cfg.backbone.pred_aspect_ratios[idx],\n scales = cfg.backbone.pred_scales[idx],\n parent = parent,\n index = idx)\n self.prediction_layers.append(pred)\n\n # Extra parameters for the extra losses\n if cfg.use_class_existence_loss:\n # This comes from the smallest layer selected\n # Also note that cfg.num_classes includes background\n self.class_existence_fc = nn.Linear(src_channels[-1], cfg.num_classes - 1)\n\n if cfg.use_semantic_segmentation_loss:\n self.semantic_seg_conv = nn.Conv2d(src_channels[0], cfg.num_classes-1, kernel_size=1)\n\n # For use in evaluation\n self.detect = Detect(cfg.num_classes, bkg_label=0, top_k=cfg.nms_top_k,\n conf_thresh=cfg.nms_conf_thresh, nms_thresh=cfg.nms_thresh)\n\n def save_weights(self, path):\n \"\"\" Saves the model's weights using compression because the file sizes were getting too big. \"\"\"\n torch.save(self.state_dict(), path)\n\n def load_weights(self, path):\n \"\"\" Loads weights from a compressed save file. \"\"\"\n state_dict = torch.load(path, map_location=\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # For backward compatability, remove these (the new variable is called layers)\n for key in list(state_dict.keys()):\n if key.startswith('backbone.layer') and not key.startswith('backbone.layers'):\n del state_dict[key]\n\n # Also for backward compatibility with v1.0 weights, do this check\n if key.startswith('fpn.downsample_layers.'):\n if cfg.fpn is not None and int(key.split('.')[2]) >= cfg.fpn.num_downsample:\n del state_dict[key]\n self.load_state_dict(state_dict)\n\n def init_weights(self, backbone_path):\n \"\"\" Initialize weights for training. \"\"\"\n # Initialize the backbone with the pretrained weights.\n self.backbone.init_backbone(backbone_path)\n\n conv_constants = getattr(nn.Conv2d(1, 1, 1), '__constants__')\n\n # Quick lambda to test if one list contains the other\n def all_in(x, y):\n for _x in x:\n if _x not in y:\n return False\n return True\n\n # Initialize the rest of the conv layers with xavier\n for name, module in self.named_modules():\n # See issue #127 for why we need such a complicated condition if the module is a WeakScriptModuleProxy\n # Broke in 1.3 (see issue #175), WeakScriptModuleProxy was turned into just ScriptModule.\n # Broke in 1.4 (see issue #292), where RecursiveScriptModule is the new star of the show.\n # Note that this might break with future pytorch updates, so let me know if it does\n is_script_conv = False\n if 'Script' in type(module).__name__:\n # 1.4 workaround: now there's an original_name member so just use that\n if hasattr(module, 'original_name'):\n is_script_conv = 'Conv' in module.original_name\n # 1.3 workaround: check if this has the same constants as a conv module\n else:\n is_script_conv = (\n all_in(module.__dict__['_constants_set'], conv_constants)\n and all_in(conv_constants, module.__dict__['_constants_set']))\n\n is_conv_layer = isinstance(module, nn.Conv2d) or is_script_conv\n\n if is_conv_layer and module not in self.backbone.backbone_modules:\n nn.init.xavier_uniform_(module.weight.data)\n\n if module.bias is not None:\n if cfg.use_focal_loss and 'conf_layer' in name:\n if not cfg.use_sigmoid_focal_loss:\n # Initialize the last layer as in the focal loss paper.\n # Because we use softmax and not sigmoid, I had to derive an alternate expression\n # on a notecard. Define pi to be the probability of outputting a foreground detection.\n # Then let z = sum(exp(x)) - exp(x_0). Finally let c be the number of foreground classes.\n # Chugging through the math, this gives us\n # x_0 = log(z * (1 - pi) / pi) where 0 is the background class\n # x_i = log(z / c) for all i > 0\n # For simplicity (and because we have a degree of freedom here), set z = 1. Then we have\n # x_0 = log((1 - pi) / pi) note: don't split up the log for numerical stability\n # x_i = -log(c) for all i > 0\n module.bias.data[0] = np.log((1 - cfg.focal_loss_init_pi) / cfg.focal_loss_init_pi)\n module.bias.data[1:] = -np.log(module.bias.size(0) - 1)\n else:\n module.bias.data[0] = -np.log(cfg.focal_loss_init_pi / (1 - cfg.focal_loss_init_pi))\n module.bias.data[1:] = -np.log((1 - cfg.focal_loss_init_pi) / cfg.focal_loss_init_pi)\n else:\n module.bias.data.zero_()\n\n def train(self, mode=True):\n super().train(mode)\n\n if cfg.freeze_bn:\n self.freeze_bn()\n\n def freeze_bn(self, enable=False):\n \"\"\" Adapted from https://discuss.pytorch.org/t/how-to-train-with-frozen-batchnorm/12106/8 \"\"\"\n for module in self.modules():\n if isinstance(module, nn.BatchNorm2d):\n module.train() if enable else module.eval()\n\n module.weight.requires_grad = enable\n module.bias.requires_grad = enable\n\n def forward(self, x):\n \"\"\" The input should be of size [batch_size, 3, img_h, img_w] \"\"\"\n _, _, img_h, img_w = x.size()\n cfg._tmp_img_h = img_h\n cfg._tmp_img_w = img_w\n\n with timer.env('backbone'):\n outs = self.backbone(x)\n\n if cfg.fpn is not None:\n with timer.env('fpn'):\n # Use backbone.selected_layers because we overwrote self.selected_layers\n outs = [outs[i] for i in cfg.backbone.selected_layers]\n outs = self.fpn(outs)\n\n proto_out = None\n if cfg.mask_type == mask_type.lincomb and cfg.eval_mask_branch:\n with timer.env('proto'):\n proto_x = x if self.proto_src is None else outs[self.proto_src]\n\n if self.num_grids > 0:\n grids = self.grid.repeat(proto_x.size(0), 1, 1, 1)\n proto_x = torch.cat([proto_x, grids], dim=1)\n\n proto_out = self.proto_net(proto_x)\n proto_out = cfg.mask_proto_prototype_activation(proto_out)\n\n if cfg.mask_proto_prototypes_as_features:\n # Clone here because we don't want to permute this, though idk if contiguous makes this unnecessary\n proto_downsampled = proto_out.clone()\n\n if cfg.mask_proto_prototypes_as_features_no_grad:\n proto_downsampled = proto_out.detach()\n\n # Move the features last so the multiplication is easy\n proto_out = proto_out.permute(0, 2, 3, 1).contiguous()\n\n if cfg.mask_proto_bias:\n bias_shape = [x for x in proto_out.size()]\n bias_shape[-1] = 1\n proto_out = torch.cat([proto_out, torch.ones(*bias_shape)], -1)\n\n\n with timer.env('pred_heads'):\n pred_outs = { 'loc': [], 'conf': [], 'mask': [], 'priors': [] }\n\n if cfg.use_mask_scoring:\n pred_outs['score'] = []\n\n if cfg.use_instance_coeff:\n pred_outs['inst'] = []\n\n for idx, pred_layer in zip(self.selected_layers, self.prediction_layers):\n pred_x = outs[idx]\n\n if cfg.mask_type == mask_type.lincomb and cfg.mask_proto_prototypes_as_features:\n # Scale the prototypes down to the current prediction layer's size and add it as inputs\n proto_downsampled = F.interpolate(proto_downsampled, size=outs[idx].size()[2:], mode='bilinear', align_corners=False)\n pred_x = torch.cat([pred_x, proto_downsampled], dim=1)\n\n # A hack for the way dataparallel works\n if cfg.share_prediction_module and pred_layer is not self.prediction_layers[0]:\n pred_layer.parent = [self.prediction_layers[0]]\n\n p = pred_layer(pred_x)\n\n for k, v in p.items():\n pred_outs[k].append(v)\n\n for k, v in pred_outs.items():\n pred_outs[k] = torch.cat(v, -2)\n\n if proto_out is not None:\n pred_outs['proto'] = proto_out\n\n if self.training:\n # For the extra loss functions\n if cfg.use_class_existence_loss:\n pred_outs['classes'] = self.class_existence_fc(outs[-1].mean(dim=(2, 3)))\n\n if cfg.use_semantic_segmentation_loss:\n pred_outs['segm'] = self.semantic_seg_conv(outs[0])\n\n return pred_outs\n else:\n if cfg.use_mask_scoring:\n pred_outs['score'] = torch.sigmoid(pred_outs['score'])\n\n if cfg.use_focal_loss:\n if cfg.use_sigmoid_focal_loss:\n # Note: even though conf[0] exists, this mode doesn't train it so don't use it\n pred_outs['conf'] = torch.sigmoid(pred_outs['conf'])\n if cfg.use_mask_scoring:\n pred_outs['conf'] *= pred_outs['score']\n elif cfg.use_objectness_score:\n # See focal_loss_sigmoid in multibox_loss.py for details\n objectness = torch.sigmoid(pred_outs['conf'][:, :, 0])\n pred_outs['conf'][:, :, 1:] = objectness[:, :, None] * F.softmax(pred_outs['conf'][:, :, 1:], -1)\n pred_outs['conf'][:, :, 0 ] = 1 - objectness\n else:\n pred_outs['conf'] = F.softmax(pred_outs['conf'], -1)\n else:\n\n if cfg.use_objectness_score:\n objectness = torch.sigmoid(pred_outs['conf'][:, :, 0])\n\n pred_outs['conf'][:, :, 1:] = (objectness > 0.10)[..., None] \\\n * F.softmax(pred_outs['conf'][:, :, 1:], dim=-1)\n\n else:\n pred_outs['conf'] = F.softmax(pred_outs['conf'], -1)\n\n return self.detect(pred_outs, self)\n\n\n\n\n# Some testing code\nif __name__ == '__main__':\n from utils.functions import init_console\n init_console()\n\n # Use the first argument to set the config if you want\n import sys\n if len(sys.argv) > 1:\n from data.config import set_cfg\n set_cfg(sys.argv[1])\n\n net = Yolact()\n net.train()\n net.init_weights(backbone_path='weights/' + cfg.backbone.path)\n\n # GPU\n net = net.to(device)\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n\n x = torch.zeros((1, 3, cfg.max_size, cfg.max_size))\n y = net(x)\n\n for p in net.prediction_layers:\n print(p.last_conv_size)\n\n print()\n for k, a in y.items():\n print(k + ': ', a.size(), torch.sum(a))\n exit()\n\n net(x)\n # timer.disable('pass2')\n avg = MovingAverage()\n try:\n while True:\n timer.reset()\n with timer.env('everything else'):\n net(x)\n avg.add(timer.total_time())\n print('\\033[2J') # Moves console cursor to 0,0\n timer.print_stats()\n print('Avg fps: %.2f\\tAvg ms: %.2f ' % (1/avg.get_avg(), avg.get_avg()*1000))\n except KeyboardInterrupt:\n pass\n" ]
[ [ "torch.set_default_tensor_type", "torch.nn.functional.softmax", "torch.zeros", "torch.cat", "torch.sum", "torch.cuda.is_available", "torch.nn.functional.interpolate", "torch.ones", "torch.nn.functional.relu", "numpy.load", "torch.nn.functional.max_pool2d", "torch.nn.functional.pad", "torch.sigmoid", "numpy.log", "torch.nn.ModuleList", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.BatchNorm2d", "torch.cuda.device_count", "torch.Tensor", "torch.nn.init.xavier_uniform_", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JulySinceAndrew/PP-Rec
[ "535272525326d8d1c5f57a2b27dfa48bfac69629" ]
[ "Code/NewsContent.py" ]
[ "import numpy as np\nfrom utils import *\nimport os\nimport json\n\nclass NewsContent():\n def __init__(self,config,):\n self.config = config\n self.read_news()\n self.get_doc_input()\n self.load_entitiy()\n self.load_ctr()\n self.load_publish_time()\n\n def fetch_news(self,docids,):\n title = None\n vert = None\n subvert = None\n body = None\n entity = None\n config = self.config\n if 'title' in config['attrs']: \n title = self.title[docids]\n if 'vert' in config['attrs']:\n vert = self.vert[docids]\n vert = vert.reshape(list(docids.shape)+[1])\n if 'subvert' in config['attrs']:\n subvert = self.subvert[docids]\n subvert = subvert.reshape(list(docids.shape)+[1])\n if 'body' in config['attrs']:\n body = self.body[docids]\n if 'entity' in config['attrs']:\n entity = self.news_entity_index[docids]\n \n FeatureTable = {'title':title,'vert':vert,'subvert':subvert,'body':body,'entity':entity}\n feature = [FeatureTable[v] for v in config['attrs']]\n feature = np.concatenate(feature, axis=-1)\n return feature\n\n def read_news(self,):\n config = self.config\n news={}\n category=[]\n subcategory=[]\n news_index={}\n index=1\n word_dict={}\n with open(self.config['data_root_path']+'/docs.tsv') as f:\n lines=f.readlines()\n for line in lines:\n splited = line.strip('\\n').split('\\t')\n doc_id,vert,subvert,title= splited[0:4]\n if len(splited)>4:\n body = splited[-1]\n else:\n body = ''\n\n if doc_id in news_index:\n continue\n news_index[doc_id]=index\n index+=1\n category.append(vert)\n subcategory.append(subvert)\n title = title.lower()\n title=word_tokenize(title)\n for word in title:\n if not(word in word_dict):\n word_dict[word]=0\n word_dict[word] += 1\n\n if 'body' in config['attrs']:\n body = body.lower()\n body = word_tokenize(body)\n for word in body:\n if not(word in word_dict):\n word_dict[word]=0\n word_dict[word] += 1\n news[doc_id]=[vert,subvert,title,body]\n else:\n news[doc_id]=[vert,subvert,title,None]\n\n category=list(set(category))\n subcategory=list(set(subcategory))\n category_dict={}\n index=0\n for c in category:\n category_dict[c]=index\n index+=1\n subcategory_dict={}\n index=0\n for c in subcategory:\n subcategory_dict[c]=index\n index+=1\n word_dict_true = {}\n word_index = 1\n for word in word_dict:\n if word_dict[word]<config['word_filter']:\n continue\n if not word in word_dict_true:\n word_dict_true[word] = word_index\n word_index +=1\n \n self.news = news\n self.news_index = news_index\n self.category_dict = category_dict\n self.subcategory_dict = subcategory_dict\n self.word_dict = word_dict_true\n\n def get_doc_input(self):\n config = self.config\n news = self.news\n news_index = self.news_index\n category = self.category_dict\n subcategory = self.subcategory_dict\n word_dict = self.word_dict\n\n title_length = config['title_length']\n body_length = config['body_length']\n\n news_num=len(news)+1\n news_title=np.zeros((news_num,title_length),dtype='int32')\n news_vert=np.zeros((news_num,),dtype='int32')\n news_subvert=np.zeros((news_num,),dtype='int32')\n if 'body' in config['attrs']:\n news_body=np.zeros((news_num,body_length),dtype='int32')\n else:\n news_body = None\n for key in news: \n vert,subvert,title,body=news[key]\n doc_index=news_index[key]\n news_vert[doc_index]=category[vert]\n news_subvert[doc_index]=subcategory[subvert]\n for word_id in range(min(title_length,len(title))):\n if title[word_id].lower() in word_dict:\n word_index = word_dict[title[word_id].lower()]\n else:\n word_index = 0\n news_title[doc_index,word_id]=word_index\n if 'body' in config['attrs']:\n for word_id in range(min(body_length,len(body))):\n word = body[word_id].lower()\n if word in word_dict:\n word_index = word_dict[word]\n else:\n word_index = 0\n news_body[doc_index,word_id]=word_index \n\n self.title = news_title\n self.vert = news_vert\n self.subvert = news_subvert\n self.body = news_body\n \n def load_entitiy(self,):\n config = self.config\n news_index = self.news_index\n max_entity_num = config['max_entity_num']\n KG_root_path = config['KG_root_path']\n\n with open(os.path.join(KG_root_path,'entity2id.txt')) as f:\n lines = f.readlines()\n\n EntityId2Index = {}\n EntityIndex2Id = {}\n for i in range(1,len(lines)):\n eid, eindex = lines[i].strip('\\n').split('\\t')\n EntityId2Index[eid] = int(eindex)\n EntityIndex2Id[int(eindex)] = eid\n\n with open(os.path.join(KG_root_path,'V21UrlDocs22_title_josn.tsv')) as f:\n lines = f.readlines()\n\n news_entity = {}\n retain_entities = {}\n index = 1\n g = []\n for i in range(len(lines)):\n d = json.loads(lines[i].strip('\\n'))\n docid = d['doc_id']\n if not docid in news_index:\n continue\n news_entity[docid] = []\n entities = d['entities']\n for j in range(len(entities)):\n e = entities[j]['Label']\n eid = entities[j]['WikidataId']\n if not eid in EntityId2Index:\n continue\n if not eid in retain_entities:\n retain_entities[eid] = index\n index += 1\n news_entity[docid].append([e,eid])\n\n entity_embedding = np.zeros((len(retain_entities)+1,100))\n\n temp_entity_embedding = np.load(os.path.join(KG_root_path,'entity_embedding.npy'))\n\n for eid in retain_entities:\n retain_index = retain_entities[eid]\n index = EntityId2Index[eid]\n entity_embedding[retain_index,:] = temp_entity_embedding[index,:]\n\n news_entity_index = np.zeros((len(news_index)+1,max_entity_num),dtype='int32')\n\n for newsid in news_index:\n index = news_index[newsid]\n entities = news_entity[newsid]\n ri = np.random.permutation(len(entities))\n for j in range(min(len(entities),max_entity_num)):\n eid = entities[ri[j]][-1]\n news_entity_index[index,j] = retain_entities[eid]\n\n self.entity_embedding = entity_embedding\n self.news_entity_index = news_entity_index\n self.news_entity = news_entity\n self.retain_entities = retain_entities\n \n def load_ctr(self,):\n news_index = self.news_index\n popularity_path = self.config['popularity_path']\n with open(os.path.join(popularity_path,'mergeimps.tsv')) as f:\n lines = f.readlines()\n\n num = 1100\n news_stat_imp = np.zeros((len(news_index)+1,num))\n news_stat_click = np.zeros((len(news_index)+1,num))\n mx = -1\n for i in range(len(lines)):\n newsid, bucket, click, imp = lines[i].strip('\\n').split('\\t')\n if not newsid in news_index:\n continue\n nindex = news_index[newsid]\n bucket = int(bucket)\n click = int(click)\n imp = int(imp)\n news_stat_imp[nindex,bucket] += imp\n news_stat_click[nindex,bucket] += click\n if bucket>mx:\n mx = bucket\n\n self.news_stat_imp = news_stat_imp\n self.news_stat_click = news_stat_click\n\n def load_publish_time(self,):\n news_index = self.news_index\n popularity_path = self.config['popularity_path']\n\n news_publish_bucket2 = np.zeros((len(news_index)+1,),dtype='int32')\n with open(os.path.join(popularity_path,'docs_pub_time.tsv')) as f:\n lines = f.readlines()\n\n for i in range(len(lines)):\n nid, tsp = lines[i].strip('\\n').split('\\t')\n if not nid in news_index:\n continue\n nindex = news_index[nid]\n if tsp=='':\n tsp = '10/10/2019 11:59:59 PM'\n #tsp = trans2tsp(tsp)\n bucket = parse_time_bucket(tsp)\n news_publish_bucket2[nindex,] = bucket\n\n index = news_publish_bucket2<0\n news_publish_bucket2[index] = 0\n self.news_publish_bucket2 = news_publish_bucket2\n\n news_publish_bucket = np.zeros((len(news_index)+1,),dtype='int32')\n news_stat_imp = self.news_stat_imp\n for i in range(1,news_stat_imp.shape[0]):\n start = (news_stat_imp[i]>0).argmax()\n news_publish_bucket[i,] = start\n self.news_publish_bucket = news_publish_bucket" ]
[ [ "numpy.concatenate", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Phhere/tiktorch
[ "82f109b4d82dda4b63a5d93e5527fc409a9fd4c1" ]
[ "tests/test_server/test_datasets.py" ]
[ "import math\nfrom collections import Counter\n\nimport numpy as np\nimport pytest\nimport torch\n\nfrom tiktorch import tiktypes as types\nfrom tiktorch.server import datasets\n\n\nclass TestDynamicDataset:\n @pytest.fixture\n def dataset(self):\n return datasets.DynamicDataset()\n\n @pytest.fixture\n def simple_dataset(self, dataset):\n labels = types.TikTensorBatch(\n [types.TikTensor(np.ones(shape=(3, 3)), id_=(0, 0)), types.TikTensor(np.ones(shape=(3, 3)), id_=(1, 0))]\n )\n data = types.TikTensorBatch(\n [types.TikTensor(np.ones(shape=(3, 3)), id_=(0, 0)), types.TikTensor(np.ones(shape=(3, 3)), id_=(1, 0))]\n )\n dataset.update(data, labels)\n return dataset\n\n def test_empty_dataset_has_lenght_of_0(self, dataset):\n assert 0 == len(dataset)\n\n def test_updating_dataset_increases_its_size(self, dataset):\n labels = types.TikTensorBatch([types.TikTensor(np.ones(shape=(3, 3)), id_=(0, 0))])\n data = types.TikTensorBatch([types.TikTensor(np.ones(shape=(3, 3)), id_=(0, 0))])\n\n dataset.update(data, labels)\n assert 1 == len(dataset)\n\n def test_removing_entries_from_dataset(self, dataset):\n labels = types.TikTensorBatch(\n [types.TikTensor(np.ones(shape=(3, 3)), id_=(0, 0)), types.TikTensor(np.ones(shape=(3, 3)), id_=(1, 0))]\n )\n data = types.TikTensorBatch(\n [types.TikTensor(np.ones(shape=(3, 3)), id_=(0, 0)), types.TikTensor(np.ones(shape=(3, 3)), id_=(1, 0))]\n )\n dataset.update(data, labels)\n\n assert 2 == len(dataset)\n\n dataset.remove((0, 0))\n\n assert 1 == len(dataset)\n\n def test_updating_removed_entries_recovers_them(self, dataset):\n labels = types.TikTensorBatch(\n [types.TikTensor(np.ones(shape=(3, 3)), id_=(0, 0)), types.TikTensor(np.ones(shape=(3, 3)), id_=(1, 0))]\n )\n data = types.TikTensorBatch(\n [types.TikTensor(np.ones(shape=(3, 3)), id_=(0, 0)), types.TikTensor(np.ones(shape=(3, 3)), id_=(1, 0))]\n )\n dataset.update(data, labels)\n\n assert 2 == len(dataset)\n\n dataset.remove((0, 0))\n dataset.update(data, labels)\n\n assert 2 == len(dataset)\n\n def test_access_by_index(self, dataset):\n first_label = torch.Tensor(np.arange(9).reshape(3, 3))\n first_data = torch.Tensor(np.arange(1, 10).reshape(3, 3))\n\n labels = types.TikTensorBatch(\n [types.TikTensor(first_label, id_=(0, 0)), types.TikTensor(np.ones(shape=(3, 3)), id_=(1, 0))]\n )\n data = types.TikTensorBatch(\n [types.TikTensor(first_data, id_=(0, 0)), types.TikTensor(np.ones(shape=(3, 3)), id_=(1, 0))]\n )\n dataset.update(data, labels)\n ret_data, ret_label = dataset[0]\n\n assert torch.equal(first_label, ret_label)\n assert torch.equal(first_data, ret_data)\n\n def test_access_by_index_to_deleted_element_is_allowed(self, dataset):\n labels = types.TikTensorBatch([types.TikTensor(np.ones(shape=(3, 3)), id_=(0, 0))])\n data = types.TikTensorBatch([types.TikTensor(np.ones(shape=(3, 3)), id_=(0, 0))])\n dataset.update(data, labels)\n\n dataset.remove((0, 0))\n\n assert dataset[0]\n\n def test_initial_get_weights(self, simple_dataset):\n expected = torch.DoubleTensor([1.0, 1.0])\n assert torch.equal(expected, simple_dataset.get_weights())\n\n def test_access_by_index_changes_weight(self, simple_dataset):\n _ = simple_dataset[0]\n\n weights = simple_dataset.get_weights().tolist()\n assert [0.9, 1.0] == weights\n\n _ = simple_dataset[0]\n\n weights = simple_dataset.get_weights().tolist()\n assert [0.81, 1.0] == weights\n\n\nclass TestDynamicWeightedRandomSampler:\n class DatasetStub:\n def __init__(self, weights):\n self.weights = weights\n\n def get_weights(self):\n return self.weights\n\n def __len__(self):\n return len(self.weights)\n\n def test_should_return(self):\n ds = self.DatasetStub(torch.Tensor([0.0, 0.0, 1.0]))\n\n sampler = datasets.DynamicWeightedRandomSampler(ds)\n sample_idx = next(iter(sampler))\n assert sample_idx == 2\n\n sample_idx = next(iter(sampler))\n assert sample_idx == 2\n\n def test_distribution(self):\n ds = self.DatasetStub(torch.Tensor([0.1, 0.2, 0.7]))\n num_samples = 10_000\n\n sampler = datasets.DynamicWeightedRandomSampler(ds)\n sampler_iter = iter(sampler)\n\n samples = Counter(next(sampler_iter) for _ in range(num_samples))\n norm_2 = samples[2] / num_samples\n norm_1 = samples[1] / num_samples\n norm_0 = samples[0] / num_samples\n\n assert math.isclose(0.7, norm_2, abs_tol=0.01)\n assert math.isclose(0.2, norm_1, abs_tol=0.01)\n assert math.isclose(0.1, norm_0, abs_tol=0.01)\n" ]
[ [ "torch.Tensor", "numpy.arange", "torch.equal", "numpy.ones", "torch.DoubleTensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
michal-hradis/torchSLAM
[ "23a23f27f66f4c8a7aa11283c87f1aaba0bb1475" ]
[ "src/incremental_slam.py" ]
[ "import logging\nlogging.basicConfig(level=logging.INFO)\n\nimport argparse\nimport torch\nimport numpy as np\nimport cv2\nimport time\nfrom collections import defaultdict\nfrom pytorch3d import transforms\nimport open3d as o3d\nimport laspy\nfrom slam_primitives import CalibratedCamera, CameraMotionSpeedConstraint, CameraPositionConstraint\n\n\ndef view(cam_trajectory, points, camera_point_assignment, resolution=1600, center=None, size=None, relations=False, errors=False, p_i=None, point_colors=None):\n if point_colors is not None:\n pass\n elif p_i is not None:\n max_count = 10\n counts = np.bincount(p_i, minlength=p_i.shape[0])\n counts = np.minimum(counts, max_count)\n colors = [(255 - 255 * i / max_count, 0, 255 * i / max_count) for i in range(max_count + 1)]\n point_colors = [colors[c] for c in counts]\n else:\n point_colors = [(0, 0, 255) for c in p_i]\n\n\n cam_trajectory = cam_trajectory.copy()[:, :2]\n points = points.copy()[:, :2]\n points[:, 1] *= -1\n cam_trajectory[:, 1] *= -1\n all = cam_trajectory[:, :2]\n\n if center is None:\n center = (np.max(all, axis=0, keepdims=True) + np.min(all, axis=0, keepdims=True)) / 2\n if size is None:\n size = np.max(np.linalg.norm(all - center, axis=1)) * 1.5\n\n img = np.zeros([resolution, resolution, 3], dtype=np.uint8)\n cam_trajectory = (cam_trajectory - center) / size / 2 + 0.5\n points = (points - center) / size / 2 + 0.5\n cam_trajectory *= resolution\n points *= resolution\n\n if relations:\n for start, camera_points in zip(cam_trajectory, camera_point_assignment):\n for end in points[camera_points > 0]:\n cv2.line(img, (int(start[0]), int(start[1])), (int(end[0]), int(end[1])), (128, 128, 128))\n\n else:\n for p, c in zip(points, point_colors):\n cv2.circle(img, (int(p[0]), int(p[1])), 1, c, -1)\n\n for p in cam_trajectory:\n cv2.circle(img, (int(p[0]), int(p[1])), 2, (0, 255, 0), -1)\n\n return img, center, size\n\n\ndef two_line_intersections(p1, u1, p2, u2, min_distance=5, max_distance=500):\n p = p1 - p2\n t2 = (p.dot(u1) * u1.dot(u2) / u1.dot(u1) - p.dot(u2)) / (u1.dot(u2)**2 / u1.dot(u1) - u2.dot(u2))\n t1 = (u2.dot(u1)*t2 - p.dot(u1)) / u1.dot(u1)\n t2 = max(t2, min_distance)\n t1 = max(t1, min_distance)\n t2 = min(t2, max_distance)\n t1 = min(t1, max_distance)\n P1 = p1 + u1 * t1\n P2 = p2 + u2 * t2\n PI = (P1 + P2) / 2.0\n if np.isnan(PI).any():\n PI = p1 + u1\n return PI\n\n\nclass IncrementalSLAM:\n def __init__(self):\n self.min_point_constraint_count = 3\n self.error_power = 1\n self.lr = 0.3\n self.cam_dist_weight = 0.25\n self.resolution = 600\n self.c_max = 1000\n self.p_max = 50000\n self.v_max = 500000\n\n self.out = cv2.VideoWriter('out.avi', cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), 30,\n (self.resolution, self.resolution))\n\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n self.camera = CalibratedCamera(self.device, error_power=self.error_power, c_max=self.c_max, v_max=self.v_max)\n self.camera_speed_constraint = CameraMotionSpeedConstraint(self.device, self.camera)\n self.camera_position_contsraint = CameraPositionConstraint(self.device, self.camera)\n\n self.p_count = 0\n self.p_pos = torch.zeros([self.p_max, 3], dtype=torch.float, device=self.device)\n\n self.rejected_points = torch.zeros([self.p_max], dtype=torch.bool, device=self.device)\n self.optimized_points = torch.zeros([self.p_max], dtype=torch.bool, device=self.device)\n\n self.new_cameras = []\n\n def save_laz(self, file_name):\n relevant_points = torch.logical_and(self.optimized_points, torch.logical_not(self.rejected_points)).cpu().numpy()\n header = laspy.LasHeader(version='1.4', point_format=3)\n las_data = laspy.LasData(header)\n\n all_positions = np.concatenate([self.p_pos[relevant_points].detach().cpu().numpy(),\n self.camera.all_positions().detach().cpu().numpy(),\n self.camera_position_contsraint.all_positions().cpu().numpy()], axis=0)\n\n las_data.x = all_positions[:, 0]\n las_data.y = all_positions[:, 1]\n las_data.z = all_positions[:, 2]\n las_data.classification = [1] * relevant_points.sum() + [2] * self.camera.c_count + [3] * self.camera.c_count\n las_data.write(file_name)\n\n def triangulate_new_points(self, point_ids):\n with torch.no_grad():\n view_mask = torch.isin(self.camera.views_p_id[:self.camera.p_count], point_ids)\n views, c_pos = self.camera.get_world_views(view_mask)\n views = views.cpu().numpy()\n c_pos = c_pos.cpu().numpy()\n p_ids = self.camera.views_p_id[:view_mask.shape[0]][view_mask].cpu().numpy()\n\n p_id_lists = defaultdict(list)\n for i in range(p_ids.shape[0]):\n p_id_lists[p_ids[i]].append(i)\n\n for p_id in p_id_lists:\n if len(p_id_lists[p_id]) > 1:\n i1 = sorted(p_id_lists[p_id])[0]\n i2 = sorted(p_id_lists[p_id])[-1]\n self.p_pos[p_id] = torch.from_numpy(two_line_intersections(c_pos[i1], views[i1], c_pos[i2], views[i2]))\n if torch.isnan(self.p_pos[p_id]).any():\n pass\n\n def add_camera(self, position, rotation, view_vectors, point_ids, c_dist, c_dist_weight,\n c_pos_gt=None, c_pos_weight=0):\n '''\n :param position: [3] Camera position vector.\n :param rotation: [3] Camera rotation vector in euler angles\n :param view_vectors: view_vectors: [n, 3] unit view direction vectors \n :param point_ids: point_ids: [n] ids of viewed points - new points should have ID None\n :param c_dist: distance from the last camera\n :param c_dist_weight: weight of the distance - use 0 to ignore the ground truth distance\n :param c_pos_gt: [3] Ground truth camera position.\n :param c_pos_weight: Weight of the ground truth position.\n :return: camera_id, [n] point id for all points\n '''\n\n\n for i in range(len(point_ids)):\n p_id = point_ids[i]\n if p_id is None:\n p_id = self.p_count\n self.p_count += 1\n point_ids[i] = p_id\n\n position = torch.from_numpy(position).float().to(self.device)\n rotation = torch.from_numpy(rotation).float().to(self.device)\n view_vectors = torch.from_numpy(view_vectors).float().to(self.device)\n if c_pos_gt is None:\n c_pos_gt = position\n else:\n c_pos_gt = torch.from_numpy(c_pos_gt).float().to(self.device)\n torch_point_ids = torch.from_numpy(np.asarray(point_ids)).long().to(self.device)\n\n cam_id = self.camera.add_camera(position, rotation, torch_point_ids, view_vectors)\n self.camera_position_contsraint.add_camera(cam_id, c_pos_gt, weight=c_pos_weight)\n self.camera_speed_constraint.add_camera(cam_id, c_dist, weight=c_dist_weight)\n\n self.new_cameras.append(cam_id)\n return cam_id, point_ids\n\n def problem_loss(self, c_pos, c_rot, c_i, p_pos, p_i, view_dir,\n c_dist, c_pos_gt, c_dist_weight):\n\n dist_cost = self.camera_speed_constraint.loss()\n pos_cost = self.camera_position_contsraint.loss()\n reprojection_loss = self.camera.loss(self.p_pos)\n\n opt = dist_cost + pos_cost + reprojection_loss\n return opt\n\n #def remove_underground_points(self, optimized_point_ids):\n # for p_id in set(optimized_point_ids) - self.rejected_points:\n # if self.p_pos[p_id, 2] < self.c_pos[list(self.point_cam_map[p_id]), 2].min() - 10:\n # self.rejected_points.add(p_id)\n\n #def remove_distant_points(self, optimized_point_ids, max_distance=100):\n # for p_id in set(optimized_point_ids) - self.rejected_points:\n # if np.linalg.norm(self.p_pos[p_id] - np.mean(self.c_pos[list(self.point_cam_map[p_id])], axis=0)) > max_distance:\n # self.rejected_points.add(p_id)\n\n def triangulate(self):\n with torch.no_grad():\n point_ids = torch.arange(0, self.p_count, device=self.device)\n view_mask = torch.isin(self.camera.views_p_id[:self.camera.p_count], point_ids)\n views, c_pos = self.camera.get_world_views(view_mask)\n p_ids = self.camera.views_p_id[:view_mask.shape[0]][view_mask].cpu().numpy()\n\n p_id_lists = defaultdict(list)\n for i in range(p_ids.shape[0]):\n p_id_lists[p_ids[i]].append(i)\n\n for p_id in p_id_lists:\n if len(p_id_lists[p_id]) > 1:\n i1 = sorted(p_id_lists[p_id])[len(p_id_lists[p_id]) // 2]\n self.p_pos[p_id] = c_pos[i1] + 10 * views[i1]\n #self.triangulate_new_points(torch.arange(0, self.p_count, device=self.device))\n pass\n\n def optimize_both(self, optimized_cam_ids, new_cams=True, iterations=150, episode_lr=1, show_interval=50):\n last_time = time.time()\n if new_cams:\n self.max_iter = iterations\n self.init_iter = 20\n lr_schedule = (np.linspace(0.001, 0.000001, self.init_iter) ** 0.5 * episode_lr).tolist() \\\n + ((np.linspace(0.0001, 1, self.init_iter) ** 0.5) * self.lr * episode_lr).tolist() \\\n + ((np.linspace(1, 0.0001, self.max_iter - 2 * self.init_iter) ** 0.4) * self.lr * episode_lr).tolist()\n else:\n self.max_iter = iterations\n self.init_iter = 0\n lr_schedule = ((np.linspace(0.0001, 1, self.init_iter) ** 0.5) * self.lr * episode_lr).tolist()\\\n + ((np.linspace(1, 0.0001, self.max_iter - self.init_iter) ** 0.4) * self.lr * episode_lr).tolist()\n\n with torch.no_grad():\n view_point_ids = self.camera.all_view_point_ids()\n point_counts = torch.bincount(view_point_ids, minlength=self.p_count)\n unwanted_points = torch.logical_or(point_counts < self.min_point_constraint_count, self.rejected_points[:self.p_count])\n new_points = torch.logical_and(torch.logical_not(unwanted_points), torch.logical_not(self.optimized_points[:self.p_count]))\n print('NEW points', new_points.sum())\n self.optimized_points[:self.p_count] = torch.logical_or(self.optimized_points[:self.p_count], new_points)\n\n if new_cams:\n new_cameras = np.asarray(self.new_cameras)\n new_cameras = torch.from_numpy(new_cameras).long().to(self.device)\n self.camera.prepare_optimization(new_cameras, None, unwanted_points.nonzero()[:, 0])\n else:\n optimized_cam_ids = np.asarray(optimized_cam_ids)\n optimized_cam_ids = torch.from_numpy(optimized_cam_ids).long().to(self.device)\n self.camera.prepare_optimization(optimized_cam_ids, None, unwanted_points.nonzero()[:, 0])\n\n if new_cams:\n params = [self.camera.c_pos, self.camera.c_rot]\n self.camera.c_pos.requires_grad = True\n self.camera.c_rot.requires_grad = True\n self.p_pos.requires_grad = False\n else:\n params = [self.camera.c_pos, self.camera.c_rot, self.p_pos]\n self.camera.c_pos.requires_grad = True\n self.camera.c_rot.requires_grad = True\n self.p_pos.requires_grad = True\n optimizer = torch.optim.Adam(params, lr=self.lr, betas=(0.90, 0.99))\n\n print(f'Init time: {time.time() - last_time:.3f}')\n last_time = time.time()\n\n for i in range(self.max_iter):\n for g in optimizer.param_groups:\n g['lr'] = lr_schedule[i]\n\n optimizer.zero_grad()\n loss = self.camera.loss(self.p_pos) + self.camera_position_contsraint.loss() + self.camera_speed_constraint.loss()\n loss.backward()\n self.camera.mask_gradients()\n optimizer.step()\n loss = loss.cpu().item()\n\n with torch.no_grad():\n if new_cams and i == self.init_iter:\n self.triangulate_new_points(new_points.nonzero()[:, 0])\n params = [self.camera.c_pos, self.camera.c_rot, self.p_pos]\n self.camera.c_pos.requires_grad = True\n self.camera.c_rot.requires_grad = True\n self.p_pos.requires_grad = True\n optimizer = torch.optim.Adam(params, lr=lr_schedule[i], betas=(0.90, 0.99))\n\n if i % show_interval == 0:\n print(f'{i}, {loss}, {show_interval / (time.time() - last_time):.1f}')\n\n #for c in c_rot.detach().cpu().numpy()[:self.c_count]:\n # print(c * self.rot_scale * 180 / np.pi)\n #print()\n #print('==============================')\n\n img, _, _ = view(\n self.camera.c_pos[optimized_cam_ids].detach().cpu().numpy(), self.p_pos[self.optimized_points][-4000:].detach().cpu().numpy(), None,\n resolution=self.resolution, p_i=self.camera.opt_p_id.detach().cpu().numpy())\n self.out.write(img)\n\n cv2.imshow('result', img)\n\n '''view_loss = view_loss.detach().cpu().numpy()\n p_i_cpu = p_i.detach().cpu().numpy()\n\n errors = 1 - np.asarray([np.median(view_loss[p_i_cpu == p_id]) ** 10 for p_id in optimized_points_new_id])\n print(errors.min(), errors.max())\n print(' '.join([f'{e}' for e in errors[:100]]))\n errors = np.arccos(errors) * 180 * np.pi\n print(errors.min(), errors.max())\n print(' '.join([f'{e}' for e in errors[:100]]))\n errors = np.minimum(errors, 20)\n errors /= 20\n point_colors = [(int(255 * (1-error)), 0, int(255 * error)) for error in errors]\n\n img2, _, _ = view(\n c_pos.detach().cpu().numpy()[-100:], p_pos.detach().cpu().numpy(), None,\n resolution=self.resolution, point_colors=point_colors)\n\n cv2.imshow('result2', img2)'''\n\n key = cv2.waitKey(5)\n if key == 27:\n break\n '''elif key == ord('s'):\n pcd = o3d.geometry.PointCloud()\n c = c_pos.detach().cpu().numpy()\n p = p_pos.detach().cpu().numpy()\n all_positions = np.concatenate([c, p], axis=0)\n cam_colors = c.copy()\n point_colors = p.copy()\n cam_colors[:, 0] = 1\n cam_colors[:, 1] = 0\n cam_colors[:, 2] = 0\n point_colors[:, 0] = 0\n point_colors[:, 1] = 0\n point_colors[:, 2] = 1\n all_colors = np.concatenate([cam_colors, point_colors], axis=0)\n\n pcd.points = o3d.utility.Vector3dVector(all_positions)\n pcd.colors = o3d.utility.Vector3dVector(all_colors)\n o3d.visualization.draw_geometries([pcd], width=1600, height=1200, point_show_normal=False)\n '''\n last_time = time.time()\n\n '''view_loss = view_loss.detach().cpu().numpy()\n p_i_cpu = p_i_t.detach().cpu().numpy()\n errors = np.asarray([np.median(view_loss[p_i_cpu == p_id]) ** (1.0/self.error_power) for p_id in optimized_points_new_id])\n if self.use_dot_product:\n errors = np.arccos(1 - errors) * 180 / np.pi\n else:\n errors = np.arcsin(errors) * 180 / np.pi\n #print(' '.join([f'{e}' for e in errors[-100:]]))\n rejected_points = errors > 1\n print(f'Rejected: {np.mean(rejected_points) * 100:.2f}% --- {np.sum(rejected_points)}/{rejected_points.shape[0]}')\n self.rejected_points |= set(np.asarray(optimized_point_ids)[rejected_points].tolist())\n self.c_pos[:self.c_count] = c_pos.detach().cpu().numpy()\n self.c_rot[:self.c_count] = c_rot.detach().cpu().numpy()\n self.p_pos[optimized_point_ids] = p_pos.detach().cpu().numpy()\n\n self.optimized_cams |= set(optimized_cam_ids)'''\n\n #cam_pos_error = np.linalg.norm(self.camera.c_pos[max(0, self.camera.c_count-20):self.camera.c_count] - self.camera_position_contsraint.positions[max(0, self.camera.c_count-20):self.c_count], axis=1)\n #cam_pos_error = np.mean(cam_pos_error)\n #self.new_cameras = []\n #print(f'Camera position error at camera {self.c_count}: {cam_pos_error}')\n #self.remove_underground_points(optimized_point_ids)\n #self.remove_distant_points(optimized_point_ids, max_distance=100)\n\n #for c in self.c_rot[:self.c_count]:\n # print(c * self.rot_scale * 180 / np.pi)\n\n def optimize_cameras(self, cam_id):\n pass\n\n def optimize_points(self, cam_id):\n pass\n\n\n" ]
[ [ "numpy.minimum", "numpy.linspace", "torch.zeros", "numpy.asarray", "numpy.max", "torch.no_grad", "torch.cuda.is_available", "torch.logical_not", "torch.isin", "torch.from_numpy", "torch.arange", "numpy.zeros", "torch.optim.Adam", "numpy.min", "numpy.isnan", "torch.logical_or", "torch.isnan", "numpy.linalg.norm", "numpy.bincount", "torch.bincount" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JeffMII/Questgen.ai
[ "6715eb1f54af44090e146fde157a8bf94de961a3" ]
[ "Questgen/mcq/mcq.py" ]
[ "# import numpy as np # linear algebra\n# import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n# import time\nimport torch\n# from transformers import T5ForConditionalGeneration,T5Tokenizer\nimport random\n# import spacy\n# import boto3\n# import zipfile\n# import os\n# import json\n# from sense2vec import Sense2Vec\n# import requests\nfrom collections import OrderedDict\nimport string\nimport importlib \npke = importlib.import_module(\"cogex-pke\")\nimport nltk\n# from nltk import FreqDist\n# nltk.download('brown')\nnltk.download('stopwords')\n# nltk.download('popular')\nfrom nltk.corpus import stopwords\n# from nltk.corpus import brown\n# from similarity.normalized_levenshtein import NormalizedLevenshtein\nfrom nltk.tokenize import sent_tokenize\nfrom flashtext import KeywordProcessor\n\ndef MCQs_available(word,s2v):\n word = word.replace(\" \", \"_\")\n sense = s2v.get_best_sense(word)\n if sense is not None:\n return True\n else:\n return False\n\n\ndef edits(word):\n \"All edits that are one edit away from `word`.\"\n letters = 'abcdefghijklmnopqrstuvwxyz '+string.punctuation\n splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]\n deletes = [L + R[1:] for L, R in splits if R]\n transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]\n replaces = [L + c + R[1:] for L, R in splits if R for c in letters]\n inserts = [L + c + R for L, R in splits for c in letters]\n return set(deletes + transposes + replaces + inserts)\n\n\ndef sense2vec_get_words(word,s2v):\n output = []\n\n word_preprocessed = word.translate(word.maketrans(\"\",\"\", string.punctuation))\n word_preprocessed = word_preprocessed.lower()\n\n word_edits = edits(word_preprocessed)\n\n word = word.replace(\" \", \"_\")\n\n sense = s2v.get_best_sense(word)\n most_similar = s2v.most_similar(sense, n=15)\n\n compare_list = [word_preprocessed]\n for each_word in most_similar:\n append_word = each_word[0].split(\"|\")[0].replace(\"_\", \" \")\n append_word = append_word.strip()\n append_word_processed = append_word.lower()\n append_word_processed = append_word_processed.translate(append_word_processed.maketrans(\"\",\"\", string.punctuation))\n if append_word_processed not in compare_list and word_preprocessed not in append_word_processed and append_word_processed not in word_edits:\n output.append(append_word.title())\n compare_list.append(append_word_processed)\n\n\n out = list(OrderedDict.fromkeys(output))\n\n return out\n\ndef get_options(answer,s2v):\n distractors =[]\n\n try:\n distractors = sense2vec_get_words(answer,s2v)\n if len(distractors) > 0:\n print(\" Sense2vec_distractors successful for word : \", answer)\n return distractors,\"sense2vec\"\n except:\n print (\" Sense2vec_distractors failed for word : \",answer)\n\n\n return distractors,\"None\"\n\ndef tokenize_sentences(text):\n sentences = [sent_tokenize(text)]\n sentences = [y for x in sentences for y in x]\n # Remove any short sentences less than 20 letters.\n sentences = [sentence.strip() for sentence in sentences if len(sentence) > 20]\n return sentences\n\n\ndef get_sentences_for_keyword(keywords, sentences):\n keyword_processor = KeywordProcessor()\n keyword_sentences = {}\n for word in keywords:\n word = word.strip()\n keyword_sentences[word] = []\n keyword_processor.add_keyword(word)\n for sentence in sentences:\n keywords_found = keyword_processor.extract_keywords(sentence)\n for key in keywords_found:\n keyword_sentences[key].append(sentence)\n\n for key in keyword_sentences.keys():\n values = keyword_sentences[key]\n values = sorted(values, key=len, reverse=True)\n keyword_sentences[key] = values\n\n delete_keys = []\n for k in keyword_sentences.keys():\n if len(keyword_sentences[k]) == 0:\n delete_keys.append(k)\n for del_key in delete_keys:\n del keyword_sentences[del_key]\n\n return keyword_sentences\n\n\ndef is_far(words_list,currentword,thresh,normalized_levenshtein):\n threshold = thresh\n score_list =[]\n for word in words_list:\n score_list.append(normalized_levenshtein.distance(word.lower(),currentword.lower()))\n if min(score_list)>=threshold:\n return True\n else:\n return False\n\ndef filter_phrases(phrase_keys,max,normalized_levenshtein ):\n filtered_phrases =[]\n if len(phrase_keys)>0:\n filtered_phrases.append(phrase_keys[0])\n for ph in phrase_keys[1:]:\n if is_far(filtered_phrases,ph,0.7,normalized_levenshtein ):\n filtered_phrases.append(ph)\n if len(filtered_phrases)>=max:\n break\n return filtered_phrases\n\n\ndef get_nouns_multipartite(text):\n out = []\n\n extractor = pke.unsupervised.MultipartiteRank()\n extractor.load_document(input=text, language='en')\n pos = {'PROPN', 'NOUN'}\n stoplist = list(string.punctuation)\n stoplist += stopwords.words('english')\n extractor.candidate_selection(pos=pos, stoplist=stoplist)\n # 4. build the Multipartite graph and rank candidates using random walk,\n # alpha controls the weight adjustment mechanism, see TopicRank for\n # threshold/method parameters.\n try:\n extractor.candidate_weighting(alpha=1.1,\n threshold=0.75,\n method='average')\n except:\n return out\n\n keyphrases = extractor.get_n_best(n=10)\n\n for key in keyphrases:\n out.append(key[0])\n\n return out\n\n\ndef get_phrases(doc):\n phrases={}\n for np in doc.noun_chunks:\n phrase =np.text\n len_phrase = len(phrase.split())\n if len_phrase > 1:\n if phrase not in phrases:\n phrases[phrase]=1\n else:\n phrases[phrase]=phrases[phrase]+1\n\n phrase_keys=list(phrases.keys())\n phrase_keys = sorted(phrase_keys, key= lambda x: len(x),reverse=True)\n phrase_keys=phrase_keys[:50]\n return phrase_keys\n\n\n\ndef get_keywords(nlp,text,max_keywords,s2v,fdist,normalized_levenshtein,no_of_sentences):\n doc = nlp(text)\n max_keywords = int(max_keywords)\n\n keywords = get_nouns_multipartite(text)\n keywords = sorted(keywords, key=lambda x: fdist[x])\n keywords = filter_phrases(keywords, max_keywords,normalized_levenshtein )\n\n phrase_keys = get_phrases(doc)\n filtered_phrases = filter_phrases(phrase_keys, max_keywords,normalized_levenshtein )\n\n total_phrases = keywords + filtered_phrases\n\n total_phrases_filtered = filter_phrases(total_phrases, min(max_keywords, 2*no_of_sentences),normalized_levenshtein )\n\n\n answers = []\n for answer in total_phrases_filtered:\n if answer not in answers and MCQs_available(answer,s2v):\n answers.append(answer)\n\n answers = answers[:max_keywords]\n return answers\n\n\ndef generate_questions_mcq(keyword_sent_mapping,device,tokenizer,model,sense2vec,normalized_levenshtein):\n batch_text = []\n answers = keyword_sent_mapping.keys()\n for answer in answers:\n txt = keyword_sent_mapping[answer]\n context = \"context: \" + txt\n text = context + \" \" + \"answer: \" + answer + \" </s>\"\n batch_text.append(text)\n\n encoding = tokenizer.batch_encode_plus(batch_text, pad_to_max_length=True, return_tensors=\"pt\")\n\n\n print (\"Running model for generation\")\n input_ids, attention_masks = encoding[\"input_ids\"].to(device), encoding[\"attention_mask\"].to(device)\n\n with torch.no_grad():\n outs = model.generate(input_ids=input_ids,\n attention_mask=attention_masks,\n max_length=150)\n\n output_array ={}\n output_array[\"questions\"] =[]\n# print(outs)\n for index, val in enumerate(answers):\n individual_question ={}\n out = outs[index, :]\n dec = tokenizer.decode(out, skip_special_tokens=True, clean_up_tokenization_spaces=True)\n\n Question = dec.replace(\"question:\", \"\")\n Question = Question.strip()\n individual_question[\"question_statement\"] = Question\n individual_question[\"question_type\"] = \"MCQ\"\n individual_question[\"answer\"] = val\n individual_question[\"id\"] = index+1\n individual_question[\"options\"], individual_question[\"options_algorithm\"] = get_options(val, sense2vec)\n\n individual_question[\"options\"] = filter_phrases(individual_question[\"options\"], 10,normalized_levenshtein)\n index = 3\n individual_question[\"extra_options\"]= individual_question[\"options\"][index:]\n individual_question[\"options\"] = individual_question[\"options\"][:index]\n individual_question[\"context\"] = keyword_sent_mapping[val]\n \n if len(individual_question[\"options\"])>0:\n output_array[\"questions\"].append(individual_question)\n\n return output_array\n\ndef generate_normal_questions(keyword_sent_mapping,device,tokenizer,model): #for normal one word questions\n batch_text = []\n answers = keyword_sent_mapping.keys()\n for answer in answers:\n txt = keyword_sent_mapping[answer]\n context = \"context: \" + txt\n text = context + \" \" + \"answer: \" + answer + \" </s>\"\n batch_text.append(text)\n\n encoding = tokenizer.batch_encode_plus(batch_text, pad_to_max_length=True, return_tensors=\"pt\")\n\n\n print (\"Running model for generation\")\n input_ids, attention_masks = encoding[\"input_ids\"].to(device), encoding[\"attention_mask\"].to(device)\n\n with torch.no_grad():\n outs = model.generate(input_ids=input_ids,\n attention_mask=attention_masks,\n max_length=150)\n\n output_array ={}\n output_array[\"questions\"] =[]\n \n for index, val in enumerate(answers):\n individual_quest= {}\n out = outs[index, :]\n dec = tokenizer.decode(out, skip_special_tokens=True, clean_up_tokenization_spaces=True)\n \n Question= dec.replace('question:', '')\n Question= Question.strip()\n\n individual_quest['Question']= Question\n individual_quest['Answer']= val\n individual_quest[\"id\"] = index+1\n individual_quest[\"context\"] = keyword_sent_mapping[val]\n \n output_array[\"questions\"].append(individual_quest)\n \n return output_array\n\ndef random_choice():\n a = random.choice([0,1])\n return bool(a)\n \n" ]
[ [ "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mghasemi/pyProximation
[ "2d19627aac33cc024c7f81b2a3f656794c9a5141" ]
[ "pyProximation/measure.py" ]
[ "from base import Foundation\n\n\nclass Measure(Foundation):\n \"\"\"\n An instance of this class is a measure on a given set `supp`. The support is either\n + a python variable of type `set`, or\n + a list of tuples which represents a box in euclidean space.\n Initializes a measure object according to the inputs:\n + *dom* must be either\n - a list of 2-tuples\n - a non-empty dictionary\n + *w* must be a\n - a function if `dom` defines a region\n - left blank (None) if `dom` is a dictionary\n \"\"\"\n\n def __init__(self, dom, w=None):\n \"\"\"\n Initializes a measure object according to the inputs:\n +`dom` must be either\n - a list of 2-tuples\n - a non-empty dictionary\n + `w` must be a\n - a function if `dom` defines a region\n - left blank (None) if `dom` is a dictionary\n \"\"\"\n self.ErrorMsg = \"\"\n self.dim = 0\n self.card = 0\n if not self.check(dom, w):\n raise Exception(self.ErrorMsg)\n\n def boxCheck(self, B):\n \"\"\"\n Checks the structure of the box *B*.\n Returns `True` id `B` is a list of 2-tuples, otherwise it\n returns `False`.\n \"\"\"\n flag = True\n for interval in B:\n flag = flag and (type(interval) == tuple) and (len(interval) == 2)\n return flag\n\n def check(self, dom, w):\n \"\"\"\n Checks the input types and their consistency, according to the\n *__init__* arguments.\n \"\"\"\n from types import FunctionType, IntType, LongType, FloatType\n if type(dom) == list:\n if not self.boxCheck(dom):\n self.ErrorMsg = \"Each member of the support's list must be a tuple of 2 elements\"\n return False\n self.DomType = \"box\"\n self.dim = len(dom)\n self.supp = dom\n if type(w) not in [FunctionType, IntType, LongType, FloatType]:\n self.ErrorMsg = \"Weight must be a `function` defined over the support or a number\"\n return False\n elif type(w) == FunctionType:\n self.weight = w\n else:\n self.weight = lambda *x: w\n elif type(dom) == dict:\n if len(dom) == 0:\n self.ErrorMsg = \"A measure can not have an empty support\"\n return False\n self.DomType = \"set\"\n self.card = len(dom)\n self.supp = dom.keys()\n self.weight = dom\n else:\n self.ErrorMsg = \"First parameter must be either a list of 2-tupels or a dictionary\"\n return False\n return True\n\n def measure(self, S):\n \"\"\"\n Returns the measure of the set `S`.\n `S` must be a list of 2-tuples.\n \"\"\"\n m = 0\n if self.DomType == \"set\":\n if type(S) not in [set, list, tuple]:\n raise Exception(\n \"The type of the given set must be either `set`, `list` or `tuple`\")\n for p in S:\n if p in self.supp:\n m += self.weight[p]\n else:\n if (type(S) != list) or (not self.boxCheck(S)):\n raise Exception(\"The given set must be a list of 2-tuples\")\n from scipy import integrate\n m = integrate.nquad(self.weight, S)[0]\n return m\n\n def integral(self, f):\n \"\"\"\n Returns the integral of `f` with respect to the currwnt measure\n over the support.\n \"\"\"\n from types import FunctionType\n m = 0\n if self.DomType == \"set\":\n if type(f) not in [dict, FunctionType]:\n raise Exception(\n \"The integrand must be a `function` or a `dict`\")\n if type(f) == dict:\n for p in self.supp:\n if p in f:\n m += self.weight[p] * f[p]\n else:\n for p in self.supp:\n try:\n m += self.weight[p] * f(p)\n except:\n pass\n else:\n if type(f) != FunctionType:\n raise Exception(\"The integrand must be a `function`\")\n from scipy import integrate\n fw = lambda *x: f(*x) * self.weight(*x)\n m = integrate.nquad(fw, self.supp)[0]\n return m\n\n def norm(self, p, f):\n \"\"\"\n Computes the norm-`p` of the `f` with respect to the current measure.\n \"\"\"\n from math import pow\n absfp = lambda *x: pow(abs(f(*x)), p)\n return pow(self.integral(absfp), 1. / p)\n\n def sample(self, num):\n \"\"\"\n Samples from the support according to the measure.\n\n \"\"\"\n assert num >= 1, \"Sample size must be a positive integer number.\"\n if self.DomType == 'box':\n from math import ceil, pow\n from itertools import product\n import random\n from random import uniform\n SubRegions = {}\n NumSample = {}\n points = []\n n = int(ceil(pow(num, (1. / self.dim))))\n delta = [(r[1] - r[0]) / float(n) for r in self.supp]\n for o in product(range(n), repeat=self.dim):\n SubRegions[o] = [(self.supp[i][0] + o[i] * delta[i], self.supp[i]\n [0] + (o[i] + 1) * delta[i]) for i in range(self.dim)]\n numpnts = max(num, len(SubRegions))\n muSupp = self.measure(self.supp)\n for o in SubRegions:\n NumSample[o] = ceil(numpnts * self.measure(SubRegions[o]))\n for o in NumSample:\n pnts = []\n while len(pnts) < NumSample[o]:\n v = []\n for rng in SubRegions[o]:\n v.append(uniform(rng[0], rng[1]))\n v = tuple(v)\n if v not in pnts:\n pnts.append(v)\n points += pnts\n return random.sample(set(points), num)\n else:\n from scipy import stats\n TotM = self.measure(self.supp)\n dist = [float(self.weight[p]) / TotM for p in self.supp]\n custm = stats.rv_discrete(name='custm', values=(self.supp, dist))\n return custm.rvs(size=num)\n" ]
[ [ "scipy.integrate.nquad", "scipy.stats.rv_discrete" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "1.10", "0.15", "1.4", "1.3", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "0.16", "1.8" ], "tensorflow": [] } ]
muyeby/AMR-Dialogue
[ "261535c407be6c166016e4759bc81176b1c99957" ]
[ "DialogRG/run.py" ]
[ "import os\nimport torch\nimport random\nfrom apex import amp\n\nrandom.seed(0)\ntorch.manual_seed(0)\ntorch.cuda.manual_seed(0)\nimport torch.nn as nn\nimport numpy as np\n\nnp.random.seed(0)\ntorch.backends.cudnn.deterministic = True\nimport tqdm\nimport argparse\nimport config_utils\nfrom dataset_utils import (\n load_vocab_new,\n tokenize,\n bpe_tokenize,\n)\n# from model import DualTransformer\n# from bert_model import DualTransformer\nfrom model_adapter import DualTransformer\nfrom torch.utils import data\nfrom torch import optim\nfrom bpemb import BPEmb\nimport math\nimport time\n\nos.environ[\"KMP_DUPLICATE_LIB_OK\"] = \"TRUE\"\n\n\ndef len_to_mask(len_seq, max_len=None):\n \"\"\"len to mask\"\"\"\n len_seq = len_seq.int()\n if max_len is None:\n max_len = torch.max(len_seq).item()\n mask = torch.zeros((len_seq.size(0), max_len))\n for i, l in enumerate(len_seq):\n mask[i, :l] = 1\n return mask\n\n\ndef train(model, data_loader, optimizer, n_gpu, FLAGS):\n model.train()\n train_loss = 0.0\n train_step = 0.0\n train_right, train_total = 0.0, 0.0\n # for i, _data in enumerate(data_loader):\n for i, _data in tqdm.tqdm(enumerate(data_loader)):\n sv, sv_len, cv, cv_len, rv, tv, tv_len, word_rel_mask, wr, tstr = _data\n batch = {}\n batch[\"tgt_str\"] = tstr\n\n batch[\"src\"] = sv\n batch[\"src_len\"] = sv_len\n batch[\"src_mask\"] = len_to_mask(sv_len)\n\n batch[\"con\"] = cv\n batch[\"con_len\"] = cv_len\n batch[\"con_mask\"] = len_to_mask(cv_len)\n\n batch[\"rel\"] = rv\n\n # batch[\"word_rel_mask\"] = word_rel_mask\n batch[\"wr\"] = wr\n\n batch[\"tgt_input\"] = tv[:, :-1] # remove eos\n batch[\"tgt_ref\"] = tv[:, 1:] # remove bos\n batch[\"tgt_len\"] = tv_len - 1\n batch[\"tgt_mask\"] = len_to_mask(tv_len - 1)\n\n outputs = model(batch)\n\n loss = outputs[\"loss\"]\n if n_gpu > 1:\n loss = loss.mean()\n if FLAGS.grad_accum_steps > 1:\n loss = loss / FLAGS.grad_accum_steps\n if FLAGS.fp16:\n with amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward() # just calculate gradient\n\n if i % FLAGS.grad_accum_steps == 0: # optimizer step\n optimizer.step()\n optimizer.zero_grad()\n\n train_loss += float(loss.cpu().item())\n train_step += 1.0\n train_right += outputs[\"counts\"][0].mean().cpu().item()\n train_total += outputs[\"counts\"][1].mean().cpu().item()\n torch.cuda.empty_cache()\n \n return train_loss / train_step, train_right / train_total\n\n\ndef validate(model, data_loader, n_gpu):\n model.eval()\n with torch.no_grad():\n dev_loss = 0.0\n dev_step = 0.0\n dev_right, dev_total = 0.0, 0.0\n for i, _data in tqdm.tqdm(enumerate(data_loader)):\n # sv, sv_len, cv, cv_len, rv, tv, tv_len, tstr = _data\n sv, sv_len, cv, cv_len, rv, tv, tv_len, word_rel_mask, wr, tstr = _data\n batch = {}\n batch[\"tgt_str\"] = tstr\n\n batch[\"src\"] = sv\n batch[\"src_len\"] = sv_len\n batch[\"src_mask\"] = len_to_mask(sv_len)\n\n batch[\"con\"] = cv\n batch[\"con_len\"] = cv_len\n batch[\"con_mask\"] = len_to_mask(cv_len)\n\n batch[\"rel\"] = rv\n\n # batch[\"word_rel_mask\"] = word_rel_mask\n batch[\"wr\"] = wr\n\n batch[\"tgt_input\"] = tv[:, :-1] # remove eos\n batch[\"tgt_ref\"] = tv[:, 1:] # remove bos\n batch[\"tgt_len\"] = (tv_len - 1)\n batch[\"tgt_mask\"] = len_to_mask(tv_len - 1)\n\n outputs = model(batch)\n loss = outputs[\"loss\"]\n if n_gpu > 1:\n loss = loss.mean()\n dev_loss += float(loss.cpu().item())\n dev_step += 1.0\n dev_right += outputs[\"counts\"][0].mean().cpu().item()\n dev_total += outputs[\"counts\"][1].mean().cpu().item()\n torch.cuda.empty_cache()\n \n return dev_loss / dev_step, dev_right / dev_total\n\n\nif __name__ == \"__main__\":\n argparser = argparse.ArgumentParser()\n argparser.add_argument(\"--config_path\", type=str, help=\"Configuration file.\")\n FLAGS, unparsed = argparser.parse_known_args()\n\n if FLAGS.config_path is not None:\n print(\"Loading hyperparameters from \" + FLAGS.config_path)\n FLAGS = config_utils.load_config(FLAGS.config_path)\n\n log_dir = FLAGS.log_dir\n continue_train = False\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n else:\n continue_train = True\n path_prefix = log_dir + \"/wiki.{}\".format(FLAGS.suffix)\n log_file = open(path_prefix + \".log\", \"w+\")\n if not continue_train:\n log_file.write(\"{}\\n\".format(str(FLAGS)))\n log_file.flush()\n print(\"Log file path: {}\".format(path_prefix + \".log\"))\n config_utils.save_config(FLAGS, path_prefix + \".config.json\")\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n n_gpu = torch.cuda.device_count()\n # n_gpu = 0\n print(\n \"device: {}, n_gpu: {}, grad_accum_steps: {}\".format(device, n_gpu, FLAGS.grad_accum_steps)\n )\n log_file.write(\n \"device: {}, n_gpu: {}, grad_accum_steps: {}\\n\".format(\n device, n_gpu, FLAGS.grad_accum_steps\n )\n if not continue_train\n else \"\"\n )\n # exit()\n s_time = time.time()\n words, word2id, concepts, concept2id, relations, relation2id, word_rels, word_rel2id = load_vocab_new(FLAGS.save_data)\n print(\"Loading vocab takes {:.3f}s\".format(time.time() - s_time))\n print(\"Vocabulary size: {}\".format(len(words)))\n if FLAGS.save_data != \"\":\n tokenize_fn = tokenize\n word_vocab, concept_vocab, relation_vocab, word_rel_vocab = word2id, concept2id, relation2id, word_rel2id\n else:\n print(\"Not support other vocabulary for now!!\")\n exit()\n\n checkpoint = None\n best_checkpoint_path = path_prefix + \"_best.checkpoint.bin\"\n last_checkpoint_path = path_prefix + \"_last.checkpoint.bin\"\n if os.path.exists(last_checkpoint_path):\n print(\"!!Existing checkpoint. Loading...\")\n log_file.write(\"!!Existing checkpoint. Loading...\\n\")\n checkpoint = torch.load(last_checkpoint_path)\n\n if FLAGS.use_bpe_pretrain:\n # word_emb = torch.load(FLAGS.save_data + \"/word_emb.pt\")\n word_emb = None\n con_emb = torch.load(FLAGS.save_data + \"/concept_emb.pt\")\n else:\n word_emb = None\n con_emb = None\n\n model = DualTransformer(FLAGS, word_emb, con_emb, word2id, concept2id, relation2id, word_rel2id)\n model.to(device)\n # model = DualTransformer(FLAGS, None, None, word2id, None, None)\n optimizer = optim.Adam(model.parameters(), lr=FLAGS.learning_rate)\n if FLAGS.fp16:\n model, optimizer = amp.initialize(model, optimizer, opt_level=\"O1\") # 这里是“欧一”,不是“零一”\n\n print(model)\n print(\n \"num. model params: {} (num. trained: {})\".format(\n sum(p.numel() for p in model.parameters()),\n sum(p.numel() for p in model.parameters() if p.requires_grad),\n )\n )\n if not continue_train:\n log_file.write(str(model))\n log_file.write(\n \"num. model params: {} (num. trained: {})\".format(\n sum(p.numel() for p in model.parameters()),\n sum(p.numel() for p in model.parameters() if p.requires_grad),\n )\n )\n if n_gpu > 1:\n model = nn.DataParallel(model)\n if checkpoint:\n if n_gpu <= 1:\n new_pre = {}\n for k, v in checkpoint[\"model_state_dict\"].items():\n name = k[7:] if k.startswith(\"module\") else k\n new_pre[name] = v\n model.load_state_dict(new_pre)\n else:\n model.load_state_dict(checkpoint[\"model_state_dict\"])\n\n best_accu = 0.0\n if checkpoint:\n assert \"best_accu\" in checkpoint\n best_accu = checkpoint[\"best_accu\"]\n print(\"Initial accuracy {:.4f}\".format(best_accu))\n log_file.write(\"Initial accuracy {:.4f}\\n\".format(best_accu))\n\n if checkpoint:\n optimizer.load_state_dict(checkpoint[\"optimizer\"])\n for state in optimizer.state.values():\n for k, v in state.items():\n if isinstance(v, torch.Tensor):\n state[k] = v.to(device)\n start_epoch = checkpoint[\"epoch\"]\n else:\n start_epoch = 0\n\n # for the usage of BertAdam\n # named_params = list(model.named_parameters())\n # no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n # grouped_params = [\n # {'params': [p for n, p in named_params if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},\n # {'params': [p for n, p in named_params if any(nd in n for nd in no_decay)], 'weight_decay': 0.01}\n # ]\n\n worker_init_fn = lambda worker_id: np.random.seed(np.random.get_state()[1][0] + worker_id)\n print(\"Loading train data and making batches\")\n log_file.write(\"Loading data and making batches\\n\")\n s_time = time.time()\n train_set = torch.load(FLAGS.save_data + \"/train_data.pt\")\n train_set.max_tok_len = 512\n print(\"Loading data takes {:.3f}s\".format(time.time() - s_time))\n s_time = time.time()\n train_loader = train_set.GetDataloader(\n batch_size=FLAGS.batch_size, shuffle=FLAGS.is_shuffle, num_workers=4\n )\n print(\"Loading dev data and making batches\")\n dev_set = torch.load(FLAGS.save_data + \"/dev_data.pt\")\n dev_loader = dev_set.GetDataloader(batch_size=FLAGS.batch_size, shuffle=False, num_workers=1)\n print(\"Loading dev data takes {:.3f}s\".format(time.time() - s_time))\n print(\"Num training examples = {}\".format(len(train_set.instance)))\n log_file.write(\"Num training examples = {}\\n\".format(len(train_set.instance)))\n\n max_patience = FLAGS.patience\n patience = 0\n optimizer.zero_grad()\n for iter in range(start_epoch, FLAGS.num_epochs):\n train_loss, train_accu = train(model, train_loader, optimizer, n_gpu, FLAGS)\n val_loss, val_accu = validate(model, dev_loader, n_gpu)\n\n print(\n \"iter: {}, lr:{:.5f} TRAIN loss: {:.4f} accu: {:.4f}; VAL loss: {:.4f} accu: {:.4f}\".format(\n iter, optimizer.param_groups[0][\"lr\"], train_loss, train_accu, val_loss, val_accu\n )\n )\n log_file.write(\n \"iter: {}, lr:{:.5f} TRAIN loss: {:.4f} accu: {:.4f}; VAL loss: {:.4f} accu: {:.4f}\\n\".format(\n iter, optimizer.param_groups[0][\"lr\"], train_loss, train_accu, val_loss, val_accu\n )\n )\n state = {\n \"epoch\": iter,\n \"model_state_dict\": model.state_dict(),\n \"optimizer\": optimizer.state_dict(),\n \"best_accu\": best_accu,\n }\n # print(\"saving last model ...\")\n torch.save(state, last_checkpoint_path)\n if best_accu < val_accu:\n best_accu = val_accu\n patience = 0\n # save model\n print(\"saving best model ...\")\n log_file.write(\"saving best model ...\\n\")\n config_utils.save_config(FLAGS, path_prefix + \".config.json\")\n state = {\n \"epoch\": iter,\n \"model_state_dict\": model.state_dict(),\n \"optimizer\": optimizer.state_dict(),\n \"best_accu\": best_accu,\n }\n torch.save(state, best_checkpoint_path)\n os.system(\"cp {} {}\".format(best_checkpoint_path, last_checkpoint_path))\n else:\n patience += 1\n if patience >= max_patience:\n print(\"Reaching max patience! exit...\")\n exit()\n if iter % 10 == 0 and iter > 0:\n # state = {\n # \"epoch\": iter,\n # \"model_state_dict\": model.state_dict(),\n # \"optimizer\": optimizer.state_dict(),\n # \"best_accu\": best_accu,\n # }\n # print(\"saving last model ...\")\n tmp_checkpoint_path = path_prefix + \"_epoch_{}.checkpoint.bin\".format(iter)\n # os.system(\"cp {} {}\".format(last_checkpoint_path, tmp_checkpoint_path))\n os.system(\"cp {} {}.{}\".format(best_checkpoint_path, best_checkpoint_path, iter))\n # torch.cuda.empty_cache()" ]
[ [ "numpy.random.get_state", "torch.max", "numpy.random.seed", "torch.cuda.manual_seed", "torch.load", "torch.manual_seed", "torch.cuda.empty_cache", "torch.nn.DataParallel", "torch.no_grad", "torch.cuda.is_available", "torch.cuda.device_count", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tiendzung-le/weather4cast-stage1
[ "56bedfa01351e5bea02bfb3a608a68ade329242e" ]
[ "weather4cast/blocks.py" ]
[ "import numpy as np\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Add, Conv2D, Layer\nfrom tensorflow.keras.layers import ELU, LeakyReLU, ReLU, Activation\nfrom tensorflow.keras.layers import AveragePooling2D\nfrom tensorflow.keras.layers import BatchNormalization, TimeDistributed\nfrom tensorflow.keras.regularizers import l2\nfrom layers import ReflectionPadding2D\n\n\ndef conv_block(channels, conv_size=(3,3), time_dist=False,\n norm='batch', stride=1, activation='relu', padding='reflect'):\n\n TD = TimeDistributed if time_dist else (lambda x: x)\n\n def block(x):\n if padding == 'reflect':\n pad = tuple((s-1)//2 for s in conv_size)\n x = TD(ReflectionPadding2D(padding=pad))(x)\n x = TD(Conv2D(channels, conv_size, \n padding='valid' if padding=='reflect' else padding,\n strides=(stride,stride), \n #kernel_regularizer=(l2(1e-4) if norm!=\"spectral\" else None)\n ))(x)\n if activation == 'leakyrelu':\n x = LeakyReLU(0.2)(x)\n elif activation == 'relu':\n x = ReLU()(x)\n elif activation == 'elu':\n x = ELU()(x)\n if norm==\"batch\":\n scale = (activation not in ['leakyrelu', 'relu'])\n x = BatchNormalization(momentum=0.95, scale=scale)(x)\n return x\n\n return block\n\n\ndef res_block(channels, conv_size=(3,3), stride=1, norm='batch',\n time_dist=False, activation='leakyrelu'):\n\n TD = TimeDistributed if time_dist else (lambda x: x)\n\n def block(x):\n in_channels = int(x.shape[-1])\n x_in = x\n if (stride > 1):\n x_in = TD(AveragePooling2D(pool_size=(stride,stride)))(x_in)\n if (channels != in_channels):\n x_in = conv_block(channels, conv_size=(1,1), stride=1, \n activation=False, time_dist=time_dist)(x_in)\n\n x = conv_block(channels, conv_size=conv_size, stride=stride,\n padding='reflect', norm=norm, time_dist=time_dist,\n activation=activation)(x)\n x = conv_block(channels, conv_size=conv_size, stride=1,\n padding='reflect', norm=norm, time_dist=time_dist,\n activation=activation)(x)\n\n x = Add()([x,x_in])\n\n return x\n\n return block\n\n\n\nclass ConvBlock(Layer):\n def __init__(self, channels, conv_size=(3,3), time_dist=False,\n norm='none', stride=1, activation='relu', padding='same',\n order=(\"conv\", \"act\", \"norm\"), scale_norm=False):\n\n super().__init__()\n TD = TimeDistributed if time_dist else (lambda x: x)\n \n if padding == 'reflect':\n pad = tuple((s-1)//2 for s in conv_size)\n self.padding = TD(ReflectionPadding2D(padding=pad))\n else:\n self.padding = lambda x: x\n \n self.conv = TD(Conv2D(\n channels, conv_size, \n padding='valid' if padding=='reflect' else padding,\n strides=(stride,stride), \n ))\n\n if activation == 'leakyrelu':\n self.act = LeakyReLU(0.2)\n elif activation == 'relu':\n self.act = ReLU()\n elif activation == 'elu':\n self.act = ELU()\n else:\n self.act = Activation(activation)\n\n if norm == \"batch\":\n self.norm = BatchNormalization(momentum=0.95, scale=scale_norm)\n elif norm == \"layer\":\n self.norm = LayerNormalization(scale=scale_norm)\n else:\n self.norm = lambda x: x\n\n self.order = order\n\n def call(self, x):\n for layer in self.order:\n if layer == \"conv\":\n x = self.conv(self.padding(x))\n elif layer == \"act\":\n x = self.act(x)\n elif layer == \"norm\":\n x = self.norm(x)\n else:\n raise ValueError(\"Unknown layer {}\".format(layer))\n return x\n\n\nclass ResBlock(Layer):\n def __init__(self, channels, **kwargs):\n super().__init__()\n self.channels = channels\n self.stride = kwargs.pop(\"stride\", 1)\n time_dist = kwargs.get(\"time_dist\", False)\n\n TD = TimeDistributed if time_dist else (lambda x: x)\n\n if self.stride > 1:\n self.pool = TD(AveragePooling2D(\n pool_size=(self.stride,self.stride)))\n else:\n self.pool = lambda x: x\n self.proj = TD(Conv2D(self.channels, kernel_size=(1,1)))\n \n self.conv_block_1 = ConvBlock(channels, stride=self.stride, **kwargs)\n self.conv_block_2 = ConvBlock(channels, activation='leakyrelu', **kwargs)\n self.add = Add()\n\n def call(self, x):\n x_in = self.pool(x)\n in_channels = int(x.shape[-1]) \n if in_channels != self.channels: \n x_in = self.proj(x_in)\n\n x = self.conv_block_1(x)\n x = self.conv_block_2(x)\n\n return self.add([x,x_in])\n\n\nclass GRUResBlock(ResBlock):\n def __init__(self, channels, final_activation='sigmoid', **kwargs):\n super().__init__(channels, **kwargs)\n self.final_act = Activation(final_activation)\n\n def call(self, x):\n x = super().call(x)\n return self.final_act(x)\n" ]
[ [ "tensorflow.keras.layers.AveragePooling2D", "tensorflow.keras.layers.Activation", "tensorflow.keras.layers.LeakyReLU", "tensorflow.keras.layers.ReLU", "tensorflow.keras.layers.ELU", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.layers.Add" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
aleczoeller/SQLServer_Loan_Data_Reporting
[ "229463a652ce54073f0565a74e20f828f8a1d21b" ]
[ "Generate_Report.py" ]
[ "# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n******************************************\r\n* Generate_Report.py *\r\n* ------------------ *\r\n* Connect to SQL Database, retrieve *\r\n* weekly loan data and email to *\r\n* specified recipients as cleaned *\r\n* Excel attachment. Also summarizes *\r\n* loan data in other worksheets. *\r\n* *\r\n* Author: Alec Zoeller, 2020 *\r\n* *\r\n* *\r\n******************************************\r\n\"\"\"\r\n\r\nimport os\r\nimport base64\r\nimport pyodbc\r\nimport pandas as pd\r\nfrom pandas.io.json import json_normalize\r\nimport json\r\nfrom datetime import datetime, timedelta\r\nfrom getpass import getpass, getuser\r\n\r\nimport smtplib\r\nimport mimetypes\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.base import MIMEBase\r\nfrom email import encoders\r\nfrom dotenv import load_dotenv\r\nload_dotenv(verbose=True)\r\n\r\n\r\n__author__ = 'Alec Zoeller'\r\n__version__ = '1.0.1'\r\n\r\n\r\nclass DataSupport(object):\r\n \"\"\"\r\n Support methods for data prep class.\r\n \"\"\"\r\n @staticmethod\r\n def format_excel(writer, num_rows, df, sheetname, letters):\r\n \"\"\"\r\n Format worksheet in Excel table for pandas export\r\n \"\"\"\r\n print(sheetname)\r\n workbook = writer.book\r\n wsheet = writer.sheets[sheetname]\r\n #wsheet.set_column('A:Z', 16.0)\r\n headname = []\r\n for i in df.columns:\r\n headname.append(dict([('header', i)]))\r\n wsheet.add_table('A1:{0}{1}'.format(letters, str(num_rows)), \r\n {'style': 'Table Style Medium 20',\r\n 'header_row':True, 'columns':headname})\r\n\r\nclass Send_Email(object):\r\n '''\r\n Support methods for Email object. \r\n '''\r\n @staticmethod \r\n def send_email(address, attachment, date):\r\n '''\r\n Method to send individual emails.\r\n '''\r\n #Connect to server. Specifically configured to Office365 login without token.\r\n #For advanced/tokenized O365 login, see shareplum library \r\n s = smtplib.SMTP('smtp.office365.com', 587)\r\n s.ehlo()\r\n s.starttls()\r\n pwd = os.getenv('EMAIL')\r\n pwd = base64.b64decode(pwd).decode('ascii')\r\n from_address = base64.b64decode(os.getenv('FROM_EMAIL')).decode('ascii')\r\n s.login(from_address, pwd)\r\n #Prepare message\r\n from_email = from_address\r\n from_display = 'Weekly Reporting'\r\n date_display = datetime.strftime(date, '%m/%d/%Y')\r\n subject = 'Weekly Reporting - Week of {}'.format(date_display)\r\n mssg = f'<p>Hello,</p><p>This is an automatically generated weekly summary for loan '\\\r\n f'volume and statistics. The data itemized in the attached table lists all pertinent '\\\r\n f'information regarding loan, partner, channel and borrower. See additional worksheets '\\\r\n f'in the Excel document for summary information on all close loans, as well as breakdowns for partners and '\\\r\n f'channels.</p><p>To request that anyone else be added to this message, or to be removed'\\\r\n f' from the mailing list feel free to reply to this message or email <a href=\"mailto'\\\r\n f':{from_address}\">{from_address}</a>. Thank you an have a great day.</p>'\r\n msg = MIMEMultipart()\r\n #Add Excel table attachment\r\n ctype, encoding = mimetypes.guess_type(attachment)\r\n if ctype is None or encoding is not None:\r\n ctype = 'application/octet-stream'\r\n maintype, subtype = ctype.split('/', 1)\r\n with open(attachment, 'rb') as fp:\r\n attach = MIMEBase(maintype, subtype)\r\n attach.set_payload(fp.read())\r\n encoders.encode_base64(attach)\r\n attach.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment))\r\n msg.attach(attach)\r\n #Add subject and body to message, then send and quit SMTP object\r\n msg['Subject'] = subject\r\n msg['From'] = from_display\r\n msg['To'] = address\r\n body = MIMEText(mssg, 'html')\r\n msg.attach(body)\r\n s.sendmail(from_email, address, msg.as_string())\r\n s.quit() \r\n \r\n\r\n\r\nclass Email(Send_Email):\r\n '''\r\n Class to set up and implement email alerts. \r\n '''\r\n def __init__(self, email_list, daten, attachment):\r\n self.email_list = email_list\r\n self.daten = daten\r\n self.attachment = attachment\r\n \r\n def distribute_emails(self):\r\n '''\r\n Method to automatically email all recipients.\r\n '''\r\n for email in self.email_list:\r\n Send_Email.send_email(email, self.attachment, self.daten)\r\n\r\nclass DataGenerator(DataSupport):\r\n \"\"\"\r\n Contains functionality for extracting data from database and \r\n returning dataframe.\r\n \"\"\"\r\n def __init__(self, query, conn, daten):\r\n self.query = query\r\n self.conn = conn\r\n self.daten = daten\r\n \r\n def generateTheD(self):\r\n \"\"\"\r\n Ping database and pull weekly data, summarize and return\r\n full dataframe and all individual ones.\r\n \"\"\"\r\n conn = self.conn\r\n query = self.query\r\n fulldf = pd.read_sql(con=conn, sql=query, parse_dates=True)\r\n #Extract json values from table/dataframe\r\n fulldf['json'] = fulldf.apply(lambda x: json.loads(x['jsondata']), axis=1)\r\n fulldf = json_normalize(fulldf['json'])\r\n fulldf.columns = [i.upper() for i in fulldf.columns]\r\n fulldf['CHANNEL'] = fulldf['CHANNEL'].fillna('no channel')\r\n fulldf.FINALIZED = pd.to_datetime(fulldf.FINALIZED)\r\n fulldf.sort_values(by='FINALIZED', inplace=True, ascending=True)\r\n outputdf = fulldf.copy()\r\n #Clean columns of master dataframe\r\n outputdf.drop(labels=['CORE_ID', 'PATH'], axis=1, inplace=True)\r\n ordered_cols = []\r\n for col in outputdf.columns:\r\n if col in ['EMP_YEARS', 'RATE', 'AGE', 'FICO', 'STATE', 'SCHOOL', 'OCCUPATION',\r\n 'DEGREE']:\r\n ordered_cols.append(1)\r\n elif col in ['STATUS', 'FINALIZED', 'VOLUME']:\r\n ordered_cols.append(0)\r\n else:\r\n ordered_cols.append(2)\r\n outputdf_columns = [x for _, x in sorted(zip(ordered_cols, outputdf.columns.tolist()))]\r\n outputdf = outputdf[outputdf_columns]\r\n #Prepare summary data columns and those for use in calculating mean, count and sum\r\n list_summ = ['CHANNEL', ['PROGRAM', 'TIER'], 'SCHOOL', 'STATE', 'OCCUPATION']\r\n summ_sheets = ['CHANNEL', 'PROGRAM&TIER', 'SCHOOL', 'STATE', 'OCCUPATION']\r\n stat_fields = ['VOLUME', 'EMP_YEARS', 'RATE', 'INCOME', 'AGE', 'FICO', 'LOAN_PAYMENT',\r\n 'TERM']\r\n fulldf['VOLUME_SUM'] = fulldf['VOLUME'].astype(float)\r\n for fld in stat_fields:\r\n fulldf[fld] = fulldf[fld].fillna(0.0)\r\n try:\r\n fulldf[fld] = fulldf.apply(lambda x: x[fld].replace('$', '').replace(',',''), axis=1)\r\n except:\r\n pass\r\n try:\r\n fulldf[fld] = fulldf[fld].astype(float)\r\n except:\r\n fulldf[fld] = fulldf.apply(lambda x: 0.0 if x[fld]=='' else x[fld], axis=1)\r\n fulldf[fld] = fulldf[fld].astype(float)\r\n #Create dictionary for applying statistics to summary tables\r\n dict_summ = {'APP_ID':'count','VOLUME_SUM':'sum'}\r\n for field in stat_fields:\r\n dict_summ[field] = 'mean'\r\n #Summarize data into supplemental dataframes\r\n channeldf = fulldf.loc[fulldf.STATUS=='Closed', :].groupby('CHANNEL').agg(dict_summ).reset_index()\r\n programdf = fulldf.loc[fulldf.STATUS=='Closed', :].groupby(['PROGRAM', 'TIER']).agg(dict_summ).reset_index()\r\n schooldf = fulldf.loc[fulldf.STATUS=='Closed', :].groupby('SCHOOL').agg(dict_summ).reset_index()\r\n statedf = fulldf.loc[fulldf.STATUS=='Closed', :].groupby('STATE').agg(dict_summ).reset_index()\r\n occupationdf = fulldf.loc[fulldf.STATUS=='Closed', :].groupby('OCCUPATION').agg(dict_summ).reset_index()\r\n fulldf.drop(labels='VOLUME_SUM', axis=1, inplace=True)\r\n #Get column lettes for Excel formatting\r\n first_letter = chr(int(len(fulldf.columns.tolist())/26)+64)\r\n second_letter = chr((int(len(fulldf.columns.tolist()))%26)+64) if \\\r\n int(len(fulldf.columns.tolist()))%26 > 0 else 'A'\r\n letters = first_letter + second_letter\r\n #Write full data to main excel table\r\n daten = datetime.strftime(self.daten, '%m%d%Y')\r\n report_path = os.path.join(os.path.dirname(__file__), 'Reports', 'Loan_Report_Week_of_{}.xlsx'.format(daten))\r\n writer = pd.ExcelWriter(report_path, engine='xlsxwriter')\r\n outputdf.to_excel(writer, 'WEEKLY_LOANS', index=False, header=outputdf.columns)\r\n DataSupport.format_excel(writer, len(outputdf) + 1, outputdf, 'WEEKLY_LOANS', letters)\r\n #Add worksheets for all the summay statistics\r\n letters = chr(len(channeldf.columns.tolist())%26 + 64)\r\n summ_dfs = [channeldf, programdf, schooldf, statedf, occupationdf]\r\n col_rename = {'APP_ID':'COUNT', 'VOLUME':'AVG_VOLUME', 'EMP_YEARS':'AVG_EMP',\r\n 'RATE':'AVG_RATE', 'INCOME':'AVG_INCOME', 'AGE':'AVG_AGE', \r\n 'FICO':'AVG_FICO', 'LOAN_PAYMENT':'AVG_PAYMENT',\r\n 'TERM':'AVG_TERM'\r\n }\r\n for i in range(len(summ_dfs)):\r\n summ_dfs[i].rename(col_rename, axis=1, inplace=True)\r\n summ_dfs[i]['AVG_VOLUME'] = summ_dfs[i].apply(lambda x: '${:,}'.format(round(float(x['AVG_VOLUME']),\r\n 2)), axis=1)\r\n summ_dfs[i]['VOLUME_SUM'] = summ_dfs[i].apply(lambda x: '${:,}'.format(round(float(x['VOLUME_SUM']),\r\n 2)), axis=1)\r\n summ_dfs[i]['AVG_INCOME'] = summ_dfs[i].apply(lambda x: '${:,}'.format(round(float(x['AVG_INCOME']),\r\n 2)), axis=1) \r\n if summ_sheets[i] == 'PROGRAM&TIER':\r\n summ_dfs[i].to_excel(writer, summ_sheets[i], index=False, header=summ_dfs[i].columns)\r\n DataSupport.format_excel(writer, len(summ_dfs[i])+1, summ_dfs[i], \r\n summ_sheets[i], chr(len(summ_dfs[i].columns.tolist())%26 + 64))\r\n summ_dfs[i].to_excel(writer, summ_sheets[i], index=False, header=summ_dfs[i].columns)\r\n DataSupport.format_excel(writer, len(summ_dfs[i])+1, summ_dfs[i], summ_sheets[i], letters)\r\n #Save and close Excel table \r\n writer.save()\r\n writer.close() \r\n return report_path\r\n \r\n \r\n \r\ndef main(): \r\n \"\"\"\"\r\n Main method - create objects for pulling data and sending emails.\r\n \"\"\"\r\n #Create SQL connection object and define query \r\n pwd = os.getenv('DBUSER')\r\n pwd = base64.b64decode(pwd).decode('ascii')\r\n server = base64.b64decode(os.getenv('SERVER')).decode('ascii')\r\n database = base64.b64decode(os.getenv('DATABASE')).decode('ascii')\r\n user = base64.b64decode(os.getenv('USERNAME')).decode('ascii')\r\n conn = pyodbc.connect(user=user, password=pwd, \r\n driver='{SQL Server}', #Choose correct, installed driver for server\r\n server=server, database=database)\r\n query = '''\r\n select jsondata as jsondata,\r\n modified as modified\r\n from dbo.loan loan\r\n where loan.finalized >= '{}'\r\n '''.format(datetime.strftime(datetime.now() - timedelta(days=7), '%m-%d-%Y'))\r\n datenow = datetime.now()\r\n\r\n #Generate dataframes and Excel table with SQL pull\r\n datagen = DataGenerator(query, conn, datenow)\r\n report_path = datagen.generateTheD()\r\n #Assume email list is in textfile in same repository, named emails.txt\r\n with open('emails.txt', 'r') as f:\r\n email_list = f.read().splitlines()\r\n #Email each recipient the Excel table\r\n email = Email(email_list, datenow, report_path)\r\n email.distribute_emails()\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n" ]
[ [ "pandas.io.json.json_normalize", "pandas.to_datetime", "pandas.read_sql", "pandas.ExcelWriter" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "0.19", "0.24", "0.20", "0.25" ], "scipy": [], "tensorflow": [] } ]
ashwindcruz/dgm
[ "b8bfdf2485afe8ff6619ae0bf59705159728e76d" ]
[ "sdgm_mnist/model.py" ]
[ "import pdb\n\nimport numpy as np\nimport math\nimport time\n\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer import cuda\n\nfrom util import gaussian_kl_divergence_standard\nfrom util import gaussian_logp\nfrom util import gaussian_logp0\nfrom util import bernoulli_logp\n\nclass VAE(chainer.Chain):\n def __init__(self, dim_in, dim_hidden, dim_latent, num_layers, temperature, num_zsamples=1):\n \n super(VAE, self).__init__()\n # initialise first encoder and decoder hidden layer separately because \n # the input and output dims differ from the other hidden layers\n\n # auxiliary variable\n self.qlina0 = L.Linear(dim_in, dim_hidden)\n self.plina0 = L.Linear(dim_latent, dim_hidden)\n self._children.append('qlina0')\n self._children.append('plina0')\n\n # z and x variable\n self.qlinz0 = L.Linear(dim_in+dim_latent, dim_hidden)\n self.plinx0 = L.Linear(dim_latent+dim_latent, dim_hidden)\n self._children.append('qlinz0')\n self._children.append('plinx0')\n\n\n # Set up the auxiliary inference model q(a|x) and the latent inference model q(z|a,x)\n for i in range(num_layers-1):\n # encoder for a\n layer_name = 'qlina' + str(i+1)\n setattr(self, layer_name, L.Linear(2*dim_hidden, dim_hidden))\n self._children.append(layer_name) \n\n # decoder for a\n layer_name = 'plina' + str(i+1)\n setattr(self, layer_name, L.Linear(2*dim_hidden, dim_hidden))\n self._children.append(layer_name)\n\n # encoder for z\n layer_name = 'qlinz' + str(i+1)\n setattr(self, layer_name, L.Linear(2*dim_hidden, dim_hidden))\n self._children.append(layer_name)\n\n # decoder for z\n layer_name = 'plinx' + str(i+1)\n setattr(self, layer_name, L.Linear(2*dim_hidden, dim_hidden))\n self._children.append(layer_name)\n\n # initialise the encoder and decoder output layer separately because\n # the input and output dims differ from the other hidden layers\n self.qlina_mu = L.Linear(2*dim_hidden, dim_latent)\n self.qlina_ln_var = L.Linear(2*dim_hidden, dim_latent)\n self.qlinz_mu = L.Linear(2*dim_hidden, dim_latent)\n self.qlinz_ln_var = L.Linear(2*dim_hidden, dim_latent)\n self.plina_mu = L.Linear(2*dim_hidden, dim_latent)\n self.plina_ln_var = L.Linear(2*dim_hidden, dim_latent)\n self.plinx_ber_prob = L.Linear(2*dim_hidden, dim_in)\n \n self._children.append('qlina_mu')\n self._children.append('qlina_ln_var')\n self._children.append('qlinz_mu')\n self._children.append('qlinz_ln_var')\n self._children.append('plina_mu')\n self._children.append('plina_ln_var')\n self._children.append('plinx_ber_prob')\n\n self.num_layers = num_layers\n self.temperature = temperature\n self.num_zsamples = num_zsamples\n self.epochs_seen = 0\n\n def encode_a(self, x):\n a_params = F.crelu(self.qlina0(x))\n\n for i in range(self.num_layers-1):\n layer_name = 'qlina' + str(i+1)\n a_params = F.crelu(self[layer_name](a_params))\n\n self.qmu_a = self.qlina_mu(a_params)\n self.qln_var_a = self.qlina_ln_var(a_params)\n\n return self.qmu_a, self.qln_var_a\n\n def encode_z(self, x, a):\n # a = F.gaussian(self.qmu_a, self.qln_var_a) # This should be outside the encoding function. Pass the function a. \n net_input = F.concat((x,a), axis=1)\n\n h = F.crelu(self.qlinz0(net_input))\n for i in range(self.num_layers-1):\n layer_name = 'qlinz' + str(i+1)\n h = F.crelu(self[layer_name](h))\n\n self.qmu_z = self.qlinz_mu(h)\n self.qln_var_z = self.qlinz_ln_var(h)\n\n return self.qmu_z, self.qln_var_z\n\n def decode_a(self, z):\n # net_input = F.concat((x,z), axis=1)\n \n h = F.crelu(self.plina0(z))\n\n for i in range(self.num_layers-1):\n layer_name = 'plina' + str(i+1)\n h = F.crelu(self[layer_name](h)) \n\n self.pmu_a = self.plina_mu(h)\n self.pln_var_a = self.plina_ln_var(h)\n\n return self.pmu_a, self.pln_var_a\n\n def decode(self,z):\n # pdb.set_trace()\n a = self.a_enc\n\n # If this function is coming from the sampling call, the batch size of z and a won't match. Manually handle that here.\n if (a.shape[0]!=z.shape[0]):\n a.volatile = 'ON'\n batch_size = z.shape[0]\n a.data = a.data[0:batch_size,:]\n\n net_input = F.concat((z,a), axis=1)\n\n h = F.crelu(self.plinx0(net_input))\n\n for i in range(self.num_layers-1):\n layer_name = 'plinx' + str(i+1)\n h = F.crelu(self[layer_name](h))\n\n self.p_ber_prob_logit = self.plinx_ber_prob(h)\n \n return self.p_ber_prob_logit\n\n def __call__(self, x):\n # Compute parameters for q(z|x, a)\n encoding_time_1 = time.time()\n qmu_a, qln_var_a = self.encode_a(x)\n encoding_time_1 = float(time.time() - encoding_time_1)\n\n a_enc = F.gaussian(qmu_a, qln_var_a)\n self.a_enc = a_enc \n \n encoding_time_2 = time.time()\n qmu_z, qln_var_z = self.encode_z(x, a_enc)\n encoding_time_2 = float(time.time() - encoding_time_2)\n\n encoding_time = encoding_time_1 + encoding_time_2\n\n decoding_time_average = 0.\n\n self.kl = 0\n self.logp = 0\n\n logp_a_z = 0\n logp_x_az = 0\n logp_z = 0\n logq_a_x = 0\n logq_z_ax = 0\n\n current_temperature = min(self.temperature['value'],1.0)\n self.temperature['value'] += self.temperature['increment']\n\n for j in xrange(self.num_zsamples):\n # z ~ q(z|x, a)\n z = F.gaussian(self.qmu_z, self.qln_var_z)\n\n # Compute p(x|z)\n decoding_time = time.time()\n pmu_a, pln_var_a = self.decode_a(z)\n p_ber_prob_logit = self.decode(z)\n decoding_time = time.time() - decoding_time\n decoding_time_average += decoding_time\n\n logp_a_z += gaussian_logp(a_enc, pmu_a, pln_var_a)\n logp_x_az += bernoulli_logp(x, p_ber_prob_logit)\n logp_z += current_temperature*gaussian_logp0(z)\n logq_a_x += gaussian_logp(a_enc, qmu_a, qln_var_a)\n logq_z_ax += current_temperature*gaussian_logp(z, qmu_z, qln_var_z)\n\n logp_a_z /= self.num_zsamples\n logp_x_az /= self.num_zsamples\n logp_z /= self.num_zsamples\n logq_a_x /= self.num_zsamples\n logq_z_ax /= self.num_zsamples\n\n\n decoding_time_average /= self.num_zsamples\n self.logp /= self.num_zsamples\n\n self.obj_batch = logp_a_z + logp_x_az + logp_z - logq_a_x - logq_z_ax\n self.kl = logq_z_ax - logp_z\n self.logp = logp_x_az\n \n self.timing_info = np.array([encoding_time,decoding_time_average])\n\n batch_size = self.obj_batch.shape[0]\n \n self.obj = -F.sum(self.obj_batch)/batch_size\n \n return self.obj" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
1001871302/CSE_6392_Term_Project
[ "899b9bbb15aac1aee5274b14fa69f3a96b0a9714" ]
[ "OnPC_Pipelines/Project DataCode1/VisualizeData.py" ]
[ "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom numpy.core.fromnumeric import mean\r\nfrom scipy.fftpack import fft, fftshift\r\nimport math\r\n\r\ndef string2array(input_str):\r\n line = ( input_str.strip('\\n,],[').split(',') ) \r\n line = np.array([ eval(num) for num in line])\r\n return line\r\n\r\n\r\ndata = open('./walking_dataset.txt')\r\nlines = data.readlines()\r\n\r\n\r\nfor line in lines:\r\n line = string2array(line)\r\n fig = plt.figure()\r\n ax1 = fig.add_subplot(211)\r\n ax1.plot(line)\r\n ax1.set_title('time domain signal')\r\n ax1_mean = np.mean(line)\r\n ax1_std = np.std(line)\r\n print('ax1_mean {}, ax1_std {}'.format(ax1_mean,ax1_std))\r\n\r\n #fft \r\n line = line- mean( np.array(line) )\r\n fft_all = fft(line)\r\n abs_all= fftshift( np.abs(fft_all) / len(fft_all) )\r\n abs_all_len = len(abs_all) \r\n x = np.arange((-int(abs_all_len/2)),math.ceil(abs_all_len/2),1)\r\n ax2 = fig.add_subplot(212)\r\n ax2.plot( x,abs_all) \r\n ax2.set_title('FFT')\r\n\r\n plt.show()" ]
[ [ "numpy.abs", "scipy.fftpack.fft", "numpy.std", "numpy.mean", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
sonercandas/fledge
[ "ac107df1236d898ea31f62a60a568cf00a9bda08" ]
[ "examples/run_electric_grid_optimal_power_flow_trust_region.py" ]
[ "\"\"\"Example script for setting up and solving an optimal power flow problem with trust-region algorithm.\"\"\"\n\nimport numpy as np\nimport os\nimport pandas as pd\nimport pyomo.environ as pyo\n\nimport fledge.config\nimport fledge.database_interface\nimport fledge.linear_electric_grid_models\nimport fledge.electric_grid_models\nimport fledge.power_flow_solvers\n\n\ndef main():\n\n # Settings.\n scenario_name = 'singapore_6node'\n\n results_path = (\n os.path.join(\n fledge.config.results_path,\n f'run_electric_grid_optimal_power_flow_trust_region_{fledge.config.timestamp}'\n )\n )\n\n # Instantiate results directory.\n os.mkdir(results_path)\n\n # Recreate / overwrite database, to incorporate changes in the CSV files.\n fledge.database_interface.recreate_database()\n\n # Obtain models.\n electric_grid_model = (\n fledge.electric_grid_models.ElectricGridModel(scenario_name)\n )\n der_power_vector_reference_candidate = electric_grid_model.der_power_vector_nominal\n power_flow_solution_candidate = (\n fledge.power_flow_solvers.PowerFlowSolutionFixedPoint(\n electric_grid_model,\n der_power_vector_reference_candidate\n )\n )\n\n # Instantiate iteration variables.\n sigma = 0.0\n der_power_vector_change_max = np.inf\n trust_region_iteration_count = 0\n power_flow_solutions = []\n linear_electric_grid_models = []\n objective_power_flows = []\n optimization_problems = []\n\n # Define trust-region parameters.\n delta = 0.1 # 3.0 / 0.5 / range: (0, delta_max] / If too big, no power flow solution.\n delta_max = 0.2 # 4.0 / 1.0\n gamma = 0.5 # 0.5 / range: (0, 1)\n eta = 0.1 # 0.1 / range: (0, 0.5]\n tau = 0.1 # 0.1 / range: [0, 0.25)\n epsilon = 1.0e-3 # 1e-3 / 1e-4\n trust_region_iteration_limit = 100\n\n while (\n (der_power_vector_change_max > epsilon)\n and (trust_region_iteration_count < trust_region_iteration_limit)\n ):\n\n # Print progress.\n print(f\"Starting trust-region iteration #{trust_region_iteration_count}\")\n\n # Check trust-region solution acceptance conditions.\n if (trust_region_iteration_count == 0) or (sigma > tau):\n\n # Accept der power vector and power flow solution candidate.\n der_power_vector_reference = der_power_vector_reference_candidate\n power_flow_solution = power_flow_solution_candidate\n power_flow_solutions.append(power_flow_solution)\n\n # Obtain new\n linear_electric_grid_model = (\n fledge.linear_electric_grid_models.LinearElectricGridModelGlobal(\n electric_grid_model,\n power_flow_solution\n )\n )\n linear_electric_grid_models.append(linear_electric_grid_model)\n\n # Store objective value.\n objective_power_flow = (\n - np.sum(np.real(der_power_vector_reference_candidate).ravel())\n + np.sum(np.real(power_flow_solution_candidate.loss.ravel()))\n )\n objective_power_flows.append(objective_power_flow)\n\n # Instantiate / reset optimization problem.\n optimization_problem = pyo.ConcreteModel()\n\n # Define linear electric grid model variables.\n linear_electric_grid_model.define_optimization_variables(optimization_problem)\n\n # Define linear electric grid model constraints.\n linear_electric_grid_model.define_optimization_constraints(optimization_problem)\n\n # Define DER constraints.\n # TODO: DERs are currently assumed to be only loads, hence negative values.\n optimization_problem.der_constraints = pyo.ConstraintList()\n for der_index, der in enumerate(electric_grid_model.ders):\n optimization_problem.der_constraints.add(\n optimization_problem.der_active_power_vector_change[0, der]\n <=\n 0.5 * np.real(electric_grid_model.der_power_vector_nominal[der_index])\n - np.real(der_power_vector_reference[der_index])\n )\n optimization_problem.der_constraints.add(\n optimization_problem.der_active_power_vector_change[0, der]\n >=\n 1.5 * np.real(electric_grid_model.der_power_vector_nominal[der_index])\n - np.real(der_power_vector_reference[der_index])\n )\n # Fixed power factor for reactive power based on nominal power factor.\n optimization_problem.der_constraints.add(\n optimization_problem.der_reactive_power_vector_change[0, der]\n ==\n optimization_problem.der_active_power_vector_change[0, der]\n * np.imag(electric_grid_model.der_power_vector_nominal[der_index])\n / np.real(electric_grid_model.der_power_vector_nominal[der_index])\n )\n\n # Define trust region constraints.\n optimization_problem.trust_region_constraints = pyo.ConstraintList()\n\n # DER.\n # TODO: DERs are currently assumed to be only loads, hence negative values.\n for der_index, der in enumerate(electric_grid_model.ders):\n optimization_problem.trust_region_constraints.add(\n optimization_problem.der_active_power_vector_change[0, der]\n <=\n -delta * np.real(electric_grid_model.der_power_vector_nominal.ravel()[der_index])\n )\n optimization_problem.trust_region_constraints.add(\n optimization_problem.der_active_power_vector_change[0, der]\n >=\n delta * np.real(electric_grid_model.der_power_vector_nominal.ravel()[der_index])\n )\n\n # Voltage.\n for node_index, node in enumerate(electric_grid_model.nodes):\n optimization_problem.trust_region_constraints.add(\n optimization_problem.voltage_magnitude_vector_change[0, node]\n >=\n -delta * np.abs(electric_grid_model.node_voltage_vector_no_load.ravel()[node_index])\n )\n optimization_problem.trust_region_constraints.add(\n optimization_problem.voltage_magnitude_vector_change[0, node]\n <=\n delta * np.abs(electric_grid_model.node_voltage_vector_no_load.ravel()[node_index])\n )\n\n # Branch flows.\n for branch_index, branch in enumerate(electric_grid_model.branches):\n optimization_problem.trust_region_constraints.add(\n optimization_problem.branch_power_vector_1_squared_change[0, branch]\n >=\n -delta * np.abs(power_flow_solutions[0].branch_power_vector_1.ravel()[branch_index] ** 2)\n )\n optimization_problem.trust_region_constraints.add(\n optimization_problem.branch_power_vector_1_squared_change[0, branch]\n <=\n delta * np.abs(power_flow_solutions[0].branch_power_vector_1.ravel()[branch_index] ** 2)\n )\n optimization_problem.trust_region_constraints.add(\n optimization_problem.branch_power_vector_2_squared_change[0, branch]\n >=\n -delta * np.abs(power_flow_solutions[0].branch_power_vector_2.ravel()[branch_index] ** 2)\n )\n optimization_problem.trust_region_constraints.add(\n optimization_problem.branch_power_vector_2_squared_change[0, branch]\n <=\n delta * np.abs(power_flow_solutions[0].branch_power_vector_2.ravel()[branch_index] ** 2)\n )\n\n # Loss.\n optimization_problem.trust_region_constraints.add(\n optimization_problem.loss_active_change[0]\n >=\n -delta * np.sum(np.real(power_flow_solutions[0].loss))\n )\n optimization_problem.trust_region_constraints.add(\n optimization_problem.loss_active_change[0]\n <=\n delta * np.sum(np.real(power_flow_solutions[0].loss))\n )\n optimization_problem.trust_region_constraints.add(\n optimization_problem.loss_reactive_change[0]\n >=\n -delta * np.sum(np.imag(power_flow_solutions[0].loss))\n )\n optimization_problem.trust_region_constraints.add(\n optimization_problem.loss_reactive_change[0]\n <=\n delta * np.sum(np.imag(power_flow_solutions[0].loss))\n )\n\n # Define objective.\n optimization_problem.objective = (\n pyo.Objective(\n expr=0.0,\n sense=pyo.minimize\n )\n )\n optimization_problem.objective.expr += (\n # DER active power.\n # TODO: DERs are currently assumed to be only loads, hence negative values.\n -1.0 * sum(\n optimization_problem.der_active_power_vector_change[0, der]\n + np.real(der_power_vector_reference[der_index])\n for der_index, der in enumerate(electric_grid_model.ders)\n )\n )\n optimization_problem.objective.expr += (\n # Active loss.\n optimization_problem.loss_active_change[0]\n + np.sum(np.real(power_flow_solution.loss))\n )\n\n # Solve optimization problem.\n optimization_solver = pyo.SolverFactory(fledge.config.solver_name)\n optimization_result = optimization_solver.solve(optimization_problem, tee=fledge.config.solver_output)\n optimization_problems.append(optimization_problem)\n try:\n assert optimization_result.solver.termination_condition is pyo.TerminationCondition.optimal\n except AssertionError:\n raise AssertionError(f\"Solver termination condition: {optimization_result.solver.termination_condition}\")\n # optimization_problem.display()\n\n # Obtain der power change value.\n der_active_power_vector_change = (\n np.zeros((len(electric_grid_model.ders), 1), dtype=np.float)\n )\n der_reactive_power_vector_change = (\n np.zeros((len(electric_grid_model.ders), 1), dtype=np.float)\n )\n for der_index, der in enumerate(electric_grid_model.ders):\n der_active_power_vector_change[der_index] = (\n optimization_problem.der_active_power_vector_change[0, der].value\n )\n der_reactive_power_vector_change[der_index] = (\n optimization_problem.der_reactive_power_vector_change[0, der].value\n )\n der_power_vector_change_max = (\n max(\n np.max(abs(der_active_power_vector_change).ravel()),\n np.max(abs(der_reactive_power_vector_change).ravel())\n )\n )\n\n # Print change variables.\n print(f\"der_active_power_vector_change = {der_active_power_vector_change.ravel()}\")\n print(f\"der_reactive_power_vector_change = {der_reactive_power_vector_change.ravel()}\")\n print(f\"der_power_vector_change_max = {der_power_vector_change_max}\")\n\n # Check trust-region conditions and obtain DER power vector / power flow solution candidates for next iteration.\n # - Only if termination condition is not met, otherwise risk of division by zero.\n if der_power_vector_change_max > epsilon:\n # Get new der vector and power flow solution candidate.\n der_power_vector_reference_candidate = (\n der_power_vector_reference\n + der_active_power_vector_change.ravel()\n + 1.0j * der_reactive_power_vector_change.ravel()\n )\n power_flow_solution_candidate = (\n fledge.power_flow_solvers.PowerFlowSolutionFixedPoint(\n electric_grid_model,\n der_power_vector_reference_candidate\n )\n )\n\n # Obtain objective values.\n objective_power_flow = (\n - np.sum(np.real(der_power_vector_reference_candidate).ravel())\n + np.sum(np.real(power_flow_solution_candidate.loss.ravel()))\n )\n objective_linear_model = (\n pyo.value(optimization_problem.objective)\n )\n\n # Check trust-region range conditions.\n sigma = (\n (objective_power_flows[-1] - objective_power_flow)\n / (objective_power_flows[-1] - objective_linear_model)\n )\n if sigma <= eta:\n delta *= gamma\n elif sigma > (1.0 - eta):\n delta = min(2 * delta, delta_max)\n\n # Print trust-region parameters.\n print(f\"objective_power_flow = {objective_power_flow}\")\n print(f\"objective_linear_model = {objective_linear_model}\")\n print(f\"objective_power_flows[-1] = {objective_power_flows[-1]}\")\n print(f\"sigma = {sigma}\")\n print(f\"delta = {delta}\")\n\n # Iterate counter.\n trust_region_iteration_count += 1\n\n # Obtain results.\n (\n der_active_power_vector,\n der_reactive_power_vector,\n voltage_magnitude_vector,\n branch_power_vector_1_squared,\n branch_power_vector_2_squared,\n loss_active,\n loss_reactive\n ) = linear_electric_grid_model.get_optimization_results(\n optimization_problem,\n power_flow_solutions[0],\n in_per_unit=True,\n with_mean=True\n )\n\n # Print results.\n print(f\"der_active_power_vector = \\n{der_active_power_vector.to_string()}\")\n print(f\"der_reactive_power_vector = \\n{der_reactive_power_vector.to_string()}\")\n print(f\"voltage_magnitude_vector = \\n{voltage_magnitude_vector.to_string()}\")\n print(f\"branch_power_vector_1_squared = \\n{branch_power_vector_1_squared.to_string()}\")\n print(f\"branch_power_vector_2_squared = \\n{branch_power_vector_2_squared.to_string()}\")\n print(f\"loss_active = \\n{loss_active.to_string()}\")\n print(f\"loss_reactive = \\n{loss_reactive.to_string()}\")\n\n # Store results as CSV.\n der_active_power_vector.to_csv(os.path.join(results_path, 'der_active_power_vector.csv'))\n der_reactive_power_vector.to_csv(os.path.join(results_path, 'der_reactive_power_vector.csv'))\n voltage_magnitude_vector.to_csv(os.path.join(results_path, 'voltage_magnitude_vector.csv'))\n branch_power_vector_1_squared.to_csv(os.path.join(results_path, 'branch_power_vector_1_squared.csv'))\n branch_power_vector_2_squared.to_csv(os.path.join(results_path, 'branch_power_vector_2_squared.csv'))\n loss_active.to_csv(os.path.join(results_path, 'loss_active.csv'))\n loss_reactive.to_csv(os.path.join(results_path, 'loss_reactive.csv'))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.real", "numpy.imag" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Siddhant-Ray/relatio
[ "30ad7a6bb143384db2f1b6cf51477bbed20e7b52" ]
[ "relatio/semantic_role_labeling.py" ]
[ "# MIT License\n\n# Copyright (c) 2020-2021 ETH Zurich, Andrei V. Plamada\n# Copyright (c) 2020-2021 ETH Zurich, Elliott Ash\n# Copyright (c) 2020-2021 University of St.Gallen, Philine Widmer\n# Copyright (c) 2020-2021 Ecole Polytechnique, Germain Gauthier\n\n# Semantic Role Labeling\n# ..................................................................................................................\n# ..................................................................................................................\n\n# link to choose the SRL model\n# https://storage.googleapis.com/allennlp-public-models/YOUR-PREFERRED-MODEL\n\nimport time\nimport warnings\nfrom copy import deepcopy\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nfrom allennlp_models.structured_prediction.predictors import (\n SemanticRoleLabelerPredictor as Predictor,\n)\nfrom tqdm import tqdm\n\nfrom .utils import clean_text, group_sentences_in_batches, replace_sentences\n\n\nclass SRL:\n def __init__(\n self,\n path: str,\n cuda_device: int = -1,\n max_batch_char_length: Optional[int] = None,\n batch_size: Optional[int] = None,\n max_sentence_length: Optional[int] = None,\n max_number_words: Optional[int] = None,\n cuda_empty_cache: bool = True,\n cuda_sleep: float = 0.0,\n ):\n self._predictor = Predictor.from_path(path, cuda_device=cuda_device)\n self._max_batch_char_length = max_batch_char_length\n self._batch_size = batch_size\n self._max_sentence_length = max_sentence_length\n self._max_number_words = max_number_words\n self._cuda_empty_cache = cuda_empty_cache\n self._cuda_device = cuda_device\n self._cuda_sleep = cuda_sleep\n\n def _clean_cache(self, cuda_sleep, cuda_empty_cache):\n if self._cuda_device > -1 and cuda_empty_cache:\n with torch.cuda.device(self._cuda_device):\n torch.cuda.empty_cache()\n time.sleep(cuda_sleep)\n\n def __call__(\n self,\n sentences: List[str],\n max_batch_char_length: Optional[int] = None,\n batch_size: Optional[int] = None,\n max_sentence_length: Optional[int] = None,\n max_number_words: Optional[int] = None,\n cuda_empty_cache: bool = None,\n cuda_sleep: float = None,\n progress_bar: bool = False,\n ):\n max_batch_char_length = (\n max_batch_char_length\n if max_batch_char_length is not None\n else self._max_batch_char_length\n )\n\n batch_size = batch_size if batch_size is not None else self._batch_size\n\n max_sentence_length = (\n max_sentence_length\n if max_sentence_length is not None\n else self._max_sentence_length\n )\n\n max_number_words = (\n max_number_words if max_number_words is not None else self._max_number_words\n )\n\n cuda_empty_cache = (\n cuda_empty_cache if cuda_empty_cache is not None else self._cuda_empty_cache\n )\n\n cuda_sleep = cuda_sleep if cuda_sleep is not None else self._cuda_sleep\n\n sentences = replace_sentences(\n sentences,\n max_sentence_length=max_sentence_length,\n max_number_words=max_number_words,\n )\n\n batches = group_sentences_in_batches(\n sentences,\n max_batch_char_length=max_batch_char_length,\n batch_size=batch_size,\n )\n\n res: List[Dict[str, List]] = []\n\n if progress_bar:\n print(\"Running SRL...\")\n time.sleep(1)\n batches = tqdm(batches)\n\n for batch in batches:\n sentences_json = [{\"sentence\": sent} for sent in batch]\n try:\n res_batch = self._predictor.predict_batch_json(sentences_json)\n except RuntimeError as err:\n warnings.warn(f\"empty result {err}\", RuntimeWarning)\n res = [{\"words\": [], \"verbs\": []}] * len(batch)\n break\n except:\n raise\n finally:\n self._clean_cache(cuda_sleep, cuda_empty_cache)\n\n res.extend(res_batch)\n return res\n\n\ndef extract_roles(\n srl: List[Dict[str, Any]], used_roles: List[str], progress_bar: bool = False\n) -> Tuple[List[Dict[str, Union[str, bool]]], List[int]]:\n\n \"\"\"\n\n A function that extracts semantic roles from the SRL output.\n\n Args:\n srl: srl output\n used_roles: list of semantic roles to extract\n progress_bar: print a progress bar (default is False)\n\n Returns:\n List of statements and numpy array of sentence indices (to keep track of sentences)\n\n \"\"\"\n\n statements_role_list: List[Dict[str, Union[str, bool]]] = []\n sentence_index: List[int] = []\n\n if progress_bar:\n print(\"Processing SRL...\")\n time.sleep(1)\n srl = tqdm(srl)\n\n for i, sentence_dict in enumerate(srl):\n role_per_sentence = extract_role_per_sentence(sentence_dict, used_roles)\n sentence_index.extend([i] * len(role_per_sentence))\n statements_role_list.extend(role_per_sentence)\n\n return statements_role_list, np.asarray(sentence_index, dtype=np.uint32)\n\n\ndef extract_role_per_sentence(\n sentence_dict: dict, used_roles: List[str]\n) -> List[Dict[str, Union[str, bool]]]:\n\n \"\"\"\n\n A function that extracts the semantic roles for a given sentence.\n\n Args:\n srl: srl output\n used_roles: list of semantic roles to extract\n\n Returns:\n List of statements with their associated roles for a given sentence\n\n \"\"\"\n\n word_list = sentence_dict[\"words\"]\n sentence_role_list = []\n\n for statement_dict in sentence_dict[\"verbs\"]:\n tag_list = statement_dict[\"tags\"]\n\n statement_role_dict: Dict[str, Union[str, bool]] = {}\n for role in [\"ARG0\", \"ARG1\", \"ARG2\", \"B-V\", \"B-ARGM-MOD\"]:\n if role in used_roles:\n indices_role = [i for i, tok in enumerate(tag_list) if role in tok]\n toks_role = [\n tok for i, tok in enumerate(word_list) if i in indices_role\n ]\n statement_role_dict[role] = \" \".join(toks_role)\n\n if \"B-ARGM-NEG\" in used_roles:\n role_negation_value = any(\"B-ARGM-NEG\" in tag for tag in tag_list)\n statement_role_dict[\"B-ARGM-NEG\"] = role_negation_value\n\n key_to_delete = []\n for key, value in statement_role_dict.items():\n if not value:\n key_to_delete.append(key)\n for key in key_to_delete:\n del statement_role_dict[key]\n sentence_role_list.append(statement_role_dict)\n\n if not sentence_role_list:\n sentence_role_list = [{}]\n\n return sentence_role_list\n\n\ndef process_roles(\n statements: List[Dict[str, List]],\n max_length: Optional[int] = None,\n remove_punctuation: bool = True,\n remove_digits: bool = True,\n remove_chars: str = \"\",\n stop_words: Optional[List[str]] = None,\n lowercase: bool = True,\n strip: bool = True,\n remove_whitespaces: bool = True,\n lemmatize: bool = False,\n stem: bool = False,\n tags_to_keep: Optional[List[str]] = None,\n remove_n_letter_words: Optional[int] = None,\n progress_bar: bool = False,\n) -> List[Dict[str, List]]:\n\n \"\"\"\n\n Takes a list of raw extracted semantic roles and cleans the text.\n\n Args:\n max_length = remove roles of more than n characters (NB: very long roles tend to be uninformative)\n progress_bar: print a progress bar (default is False)\n For other arguments see utils.clean_text.\n\n Returns:\n List of processed statements\n\n \"\"\"\n\n roles_copy = deepcopy(statements)\n\n if progress_bar:\n print(\"Cleaning SRL...\")\n time.sleep(1)\n statements = tqdm(statements)\n\n for i, statement in enumerate(statements):\n for role, role_content in roles_copy[i].items():\n if isinstance(role_content, str):\n res = clean_text(\n [role_content],\n remove_punctuation=remove_punctuation,\n remove_digits=remove_digits,\n remove_chars=remove_chars,\n stop_words=stop_words,\n lowercase=lowercase,\n strip=strip,\n remove_whitespaces=remove_whitespaces,\n lemmatize=lemmatize,\n stem=stem,\n tags_to_keep=tags_to_keep,\n remove_n_letter_words=remove_n_letter_words,\n )[0]\n if max_length is not None:\n if len(res) <= max_length:\n roles_copy[i][role] = res\n else:\n roles_copy[i][role] = \"\"\n else:\n roles_copy[i][role] = res\n elif isinstance(role_content, bool):\n pass\n else:\n raise ValueError(f\"{role_content}\")\n\n return roles_copy\n\n\ndef rename_arguments(\n statements: List[dict], progress_bar: bool = False, suffix: str = \"_highdim\"\n):\n\n \"\"\"\n\n Takes a list of dictionaries and renames the keys of the dictionary with an extra user-specified suffix.\n\n Args:\n statements: list of statements\n progress_bar: print a progress bar (default is False)\n suffix: extra suffix to add to the keys of the dictionaries\n\n Returns:\n List of dictionaries with renamed keys.\n\n \"\"\"\n\n roles_copy = deepcopy(statements)\n\n if progress_bar:\n print(\"Processing raw arguments...\")\n time.sleep(1)\n statements = tqdm(statements)\n\n for i, statement in enumerate(statements):\n for role, role_content in statement.items():\n name = role + suffix\n roles_copy[i][name] = roles_copy[i].pop(role)\n roles_copy[i][name] = role_content\n\n return roles_copy\n" ]
[ [ "numpy.asarray", "torch.cuda.device", "torch.cuda.empty_cache" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Javim24/project-based-learning
[ "d13320f28eb74ddf8587c88e2ab9a337b0c77ff2" ]
[ "python/data_science/intro.py" ]
[ "from sklearn import tree, svm\n\n# [height, weight, shoe_size]\nX = [[181, 80, 44], [177, 70, 43], [160, 60, 38], [154, 54, 37], [166, 65, 40],\n [190, 90, 47], [175, 64, 39],\n [177, 70, 40], [159, 55, 37], [171, 75, 42], [181, 85, 43]]\n\nY = ['male', 'male', 'female', 'female', 'male', 'male', 'female', 'female',\n 'female', 'male', 'male']\n\nclf = tree.DecisionTreeClassifier()\n\nclf = clf.fit(X,Y)\n\nX_test = [[155,40,37]]\nprediction = clf.predict(X_test)\nprint(prediction)\n\n#usando svc\nclf_svc = svm.SVC()\nclf_svc = clf_svc.fit(X,Y)\nprint(clf_svc.predict(X_test))" ]
[ [ "sklearn.tree.DecisionTreeClassifier", "sklearn.svm.SVC" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
baoy-nlp/TextVAE-pytorch
[ "65e53eef4f0c8b6ddd1355c857eff028421c0b4e" ]
[ "encoder/attentive_encoder.py" ]
[ "# MIT License\n\n# Copyright (c) 2018 the NJUNMT-pytorch authors.\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.\n\nimport torch.nn as nn\n\nfrom nn_self.embeddings import Embeddings\nfrom nn_self.sublayers import PositionwiseFeedForward, MultiHeadedAttention\n\n\nclass EncoderBlock(nn.Module):\n\n def __init__(self, d_model, d_inner_hid, n_head, dim_per_head, dropout=0.1):\n super(EncoderBlock, self).__init__()\n\n self.layer_norm = nn.LayerNorm(d_model)\n\n self.slf_attn = MultiHeadedAttention(head_count=n_head, model_dim=d_model, dropout=dropout,\n dim_per_head=dim_per_head)\n\n self.pos_ffn = PositionwiseFeedForward(size=d_model, hidden_size=d_inner_hid, dropout=dropout)\n\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, enc_input, slf_attn_mask=None):\n input_norm = self.layer_norm(enc_input)\n context, _, _ = self.slf_attn(input_norm, input_norm, input_norm, slf_attn_mask)\n out = self.dropout(context) + enc_input\n\n return self.pos_ffn(out)\n\n\nclass SelfATTEncoder(nn.Module):\n def __init__(self, n_layers, hidden_size, inner_hidden, n_head, block_dropout, dim_per_head=None):\n super().__init__()\n self.num_layers = n_layers\n self.block_stack = nn.ModuleList(\n [EncoderBlock(d_model=hidden_size, d_inner_hid=inner_hidden, n_head=n_head, dropout=block_dropout,\n dim_per_head=dim_per_head)\n for _ in range(n_layers)])\n\n self.layer_norm = nn.LayerNorm(hidden_size)\n\n def forward(self, out, enc_slf_attn_mask=None):\n for i in range(self.num_layers):\n out = self.block_stack[i](out, enc_slf_attn_mask)\n\n out = self.layer_norm(out)\n\n return out\n\n\nclass TransformerEncoder(nn.Module):\n\n def __init__(self,\n vocab_size,\n n_layers=6,\n n_head=8,\n input_size=512,\n hidden_size=512,\n inner_hidden=1024,\n embed_dropout=0.1,\n block_dropout=0.1,\n dim_per_head=None,\n pad=0,\n **kwargs\n ):\n super().__init__()\n self.pad_id = pad\n self.embeddings = Embeddings(num_embeddings=vocab_size,\n embedding_dim=input_size,\n dropout=embed_dropout,\n add_position_embedding=True,\n padding_idx=self.pad_id\n )\n\n self.self_att_encoder = SelfATTEncoder(\n n_layers,\n hidden_size,\n inner_hidden,\n n_head,\n block_dropout,\n dim_per_head\n )\n self.hiddne_size = hidden_size\n\n def reset_embed(self, share_embed):\n self.embeddings = share_embed\n\n @property\n def out_dim(self):\n return self.hiddne_size\n\n def forward(self, src_seq):\n # Word embedding look up\n batch_size, src_len = src_seq.size()\n\n emb = self.embeddings(src_seq)\n\n enc_mask = src_seq.detach().eq(self.pad_id)\n enc_slf_attn_mask = enc_mask.unsqueeze(1).expand(batch_size, src_len, src_len)\n\n out = self.self_att_encoder(emb, enc_slf_attn_mask)\n\n # return out, enc_mask\n return {\n \"out\": out,\n \"mask\": enc_mask,\n }\n" ]
[ [ "torch.nn.Dropout", "torch.nn.LayerNorm" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
GSS-Cogs/sdg-build
[ "16aae08407d920478224648694ab2ab2e2572712" ]
[ "sdg/outputs/OutputGeoJson.py" ]
[ "import os\nimport json\nimport copy\nfrom urllib.request import urlopen\nimport sdg\nimport pandas as pd\nfrom sdg.outputs import OutputBase\n\nclass OutputGeoJson(OutputBase):\n \"\"\"Output SDG data/metadata in GeoJson disaggregated by region.\"\"\"\n\n\n def __init__(self, inputs, schema, output_folder='_site', translations=None,\n geojson_file='regions.geojson', name_property='name', id_property='id',\n id_column='GeoCode', output_subfolder='regions', filename_prefix='indicator_',\n exclude_columns=None, id_replacements=None, indicator_options=None,\n logging=None):\n \"\"\"Constructor for OutputGeoJson.\n\n Parameters\n ----------\n\n Inherits all the parameters from OutputBase, plus the following optional\n arguments (see above for the default values):\n\n geojson_file : string\n A path to a GeoJSON file (remote or local) which contains all of the\n \"geometries\" for the regions to include. Each region should have an\n id and a name, in properties (see name_property and id_property).\n name_property : string\n The property in the geometry file which contains the region's name.\n id_property : string\n The property in the geometry file which contains the region's id.\n id_column : string\n The name of a column in the indicator data which corresponds to the\n id that is in the \"id_property\" of the geometry file. This serves to\n \"join\" the indicator data with the geometry file.\n output_subfolder : string\n A folder beneath 'geojson' to put the files. The full path will be:\n [output_folder]/geojson/[output_subfolder]/[indicator_id].geojson\n filename_prefix : string\n A prefix added before the indicator id to construct a filename for\n each geojson file.\n exclude_columns : list\n A list of strings, each a column name in the indicator data that\n should not be included in the disaggregation. This is typically\n for any columns that mirror the region referenced by the id column.\n id_replacements : dict\n An optional for with replacements to apply to the values in\n the id_column. This is typically used if another column exists which\n \"mirrors\" what would be in an id column, to avoid duplicate work.\n For example, maybe a \"Region\" column exists with the names of the\n regions as values. This can be used to \"map\" those region names to\n geocodes, and save you the work of maintaining a separate id column.\n \"\"\"\n if translations is None:\n translations = []\n if exclude_columns is None:\n exclude_columns = []\n if id_replacements is None:\n id_replacements = {}\n\n OutputBase.__init__(self, inputs, schema, output_folder, translations,\n indicator_options, logging=logging)\n self.geojson_file = geojson_file\n self.name_property = name_property\n self.id_property = id_property\n self.id_column = id_column\n self.output_subfolder = output_subfolder\n self.filename_prefix = filename_prefix\n self.exclude_columns = exclude_columns\n self.id_replacements = id_replacements\n self.geometry_data = self.fetch_geometry_data()\n\n\n def fetch_geometry_data(self):\n \"\"\"Grab the data referenced by the \"geojson_file\" parameter.\n\n Returns\n -------\n dict\n Parsed JSON as a Python dict.\n \"\"\"\n file = None\n data = None\n if self.geojson_file.startswith('http'):\n file = urlopen(self.geojson_file)\n data = file.read().decode('utf-8')\n else:\n file = open(self.geojson_file)\n data = file.read()\n file.close()\n\n data = json.loads(data)\n return data\n\n\n def indicator_has_geocodes(self, indicator):\n \"\"\"Determine if an indicator has geographical data.\n\n Parameters\n ----------\n indicator : Indicator object\n An Indicator object to examine.\n\n Returns\n -------\n boolean\n True if the indicator has geographical data, False otherwise.\n \"\"\"\n # Make sure the indicator has data at all.\n if not indicator.has_data():\n return False\n # Make sure the indicator has a geocode column.\n cols = indicator.data.columns\n if self.id_column not in cols:\n return False\n # Make sure that column has data in it.\n return indicator.data[self.id_column].any()\n\n\n def build(self, language=None):\n \"\"\"Write the GeoJSON output. Overrides parent.\"\"\"\n status = True\n\n target_folder = os.path.join(self.output_folder, 'geojson', self.output_subfolder)\n if not os.path.exists(target_folder):\n os.makedirs(target_folder, exist_ok=True)\n\n for indicator_id in self.get_indicator_ids():\n indicator = self.get_indicator_by_id(indicator_id)\n\n if not self.indicator_has_geocodes(indicator):\n continue\n\n series_by_geocodes = self.get_series_by_geocodes(indicator, language=language)\n geometry_data = copy.deepcopy(self.geometry_data)\n\n # Loop through the features.\n for index, feature in enumerate(geometry_data['features']):\n geocode = feature['properties'][self.id_property]\n # If there are no series for this geocode, skip it.\n if geocode not in series_by_geocodes:\n continue\n disaggregations = [series.get_disaggregations() for series in series_by_geocodes[geocode]]\n values = [series.get_values() for series in series_by_geocodes[geocode]]\n # Do some cleanup of the disaggregations.\n disaggregations = [self.clean_disaggregations(disaggregation) for disaggregation in disaggregations]\n # Figure out a \"headline\" so we can move it to the front of the list.\n headline_index = self.get_headline_index(disaggregations)\n disaggregations.insert(0, disaggregations.pop(headline_index))\n values.insert(0, values.pop(headline_index))\n # Set these lists on the GeoJSON data structure.\n geometry_data['features'][index]['properties']['disaggregations'] = disaggregations\n geometry_data['features'][index]['properties']['values'] = values\n # Translate the name, if necessary using a 'data' group.\n feature_name = feature['properties'][self.name_property]\n feature_name = self.translation_helper.translate(feature_name, language, default_group='data')\n # Normalize the id and name properties.\n geometry_data['features'][index]['properties']['name'] = feature_name\n geometry_data['features'][index]['properties']['geocode'] = feature['properties'][self.id_property]\n if self.name_property != 'name':\n del geometry_data['features'][index]['properties'][self.name_property]\n if self.id_property != 'geocode':\n del geometry_data['features'][index]['properties'][self.id_property]\n # Finally write the updated GeoJSON file.\n filename = self.filename_prefix + indicator_id + '.geojson'\n filepath = os.path.join(target_folder, filename)\n with open(filepath, 'w') as f:\n json.dump(geometry_data, f)\n\n return status\n\n\n def get_series_by_geocodes(self, indicator, language=None):\n \"\"\"Get a dict of lists of Series objects, keyed by geocode ids.\n\n Parameters\n ----------\n indicator : Indicator\n An instance of the Indicator class.\n language : language\n A specified language since each language is cached\n\n Returns\n -------\n dict\n Lists of instances of the Series class, keyed by geocode id.\n \"\"\"\n series_by_geocodes = {}\n for series in indicator.get_all_series(language=language):\n if series.has_disaggregation(self.id_column):\n geocode = series.get_disaggregation(self.id_column)\n geocode = self.replace_geocode(geocode)\n if geocode not in series_by_geocodes:\n series_by_geocodes[geocode] = []\n series_by_geocodes[geocode].append(series)\n return series_by_geocodes\n\n\n def clean_disaggregations(self, disaggregations):\n \"\"\"Apply any modifications to disaggregations before saving them into\n the GeoJSON file.\n\n Parameters\n ----------\n disaggregations : dict\n A dict of disaggregations, with category keyed to subcategory.\n\n Returns\n -------\n dict\n A modified version of the disaggregations dict.\n \"\"\"\n # We don't need the actual geocode column.\n del disaggregations[self.id_column]\n # Remove any others necessary.\n for column in self.exclude_columns:\n if column in disaggregations:\n del disaggregations[column]\n # Convert null/nan/etc into just null.\n for key in disaggregations:\n if pd.isna(disaggregations[key]):\n disaggregations[key] = None\n return disaggregations\n\n\n def get_headline_index(self, disaggregations):\n \"\"\"Figure out a \"headline\" from a list of disaggregations.\n\n Parameters\n ----------\n disaggregations : list\n A list of disaggregations dicts (categories keyed to subcategory).\n\n Returns\n -------\n int\n The index of the disaggregation chosen to be the headline.\n \"\"\"\n # We need to figure out which series to mark as the \"headline\". Try\n # to find one with the smallest amount of disaggregation.\n headline_scores = {}\n for disagg_index, disaggregation in enumerate(disaggregations):\n num_disaggregations = 0\n for key in disaggregation:\n if not pd.isna(disaggregation[key]):\n num_disaggregations += 1\n headline_scores[disagg_index] = num_disaggregations\n return min(headline_scores, key=headline_scores.get)\n\n\n def replace_geocode(self, geocode):\n \"\"\"Make any replaces of geocodes, according to the id_replacements.\n\n Parameters\n ----------\n geocode : string\n A geocode to look for a replacement for.\n\n Returns\n -------\n string\n The replaced geocode, or the original, if no replacement was found.\n \"\"\"\n if geocode in self.id_replacements:\n return self.id_replacements[geocode]\n return geocode\n\n\n def validate(self):\n \"\"\"Validate geojson-related source data. Overrides parent.\n\n This output does not currently test general data and metadata, as it is\n assumed that this is a supplemental output, and that another output will\n validate all of that.\n \"\"\"\n\n status = True\n\n # Make sure the geojson_file has the required properties on each feature.\n for index, feature in enumerate(self.geometry_data['features']):\n feature_is_bad = False\n if self.name_property not in feature['properties']:\n print('Name property \"' + self.name_property + '\" not found in feature:')\n feature_is_bad = True\n if self.id_property not in feature['properties']:\n print('ID property \"' + self.id_property + '\" not found in feature:')\n feature_is_bad = True\n if feature_is_bad:\n print(feature['properties'])\n status = False\n\n # Make sure at least one indicator has geocodes.\n if not self.geocodes_exist():\n print('No indicators have data under \"' + self.id_column + '\".')\n status = False\n\n return status\n\n\n def geocodes_exist(self):\n \"\"\"Check to see if at least one indicator in this output contains geocodes.\"\"\"\n no_indicators_have_geocodes = True\n for indicator_id in self.get_indicator_ids():\n if self.indicator_has_geocodes(self.get_indicator_by_id(indicator_id)):\n no_indicators_have_geocodes = False\n break\n\n return False if no_indicators_have_geocodes else True\n\n\n def get_documentation_title(self):\n return 'GeoJSON output - ' + self.output_subfolder\n\n\n def get_documentation_content(self, languages=None, baseurl=''):\n if languages is None:\n languages = ['']\n\n indicator_ids = self.get_documentation_indicator_ids()\n\n endpoint = '{language}/geojson/{folder}/indicator_{indicator_id}.geojson'\n output = '<p>' + self.get_documentation_description() + ' Examples are below:<p>'\n output += '<ul>'\n for language in languages:\n for indicator_id in indicator_ids:\n path = endpoint.format(language=language, indicator_id=indicator_id, folder=self.output_subfolder)\n output += '<li><a href=\"' + baseurl + path + '\">' + path + '</a></li>'\n output += '<li>etc...</li>'\n output += '</ul>'\n\n return output\n\n\n def get_documentation_indicator_ids(self):\n indicator_ids = []\n for indicator_id in self.get_indicator_ids():\n if len(indicator_ids) > 2:\n break\n indicator = self.get_indicator_by_id(indicator_id)\n if not self.indicator_has_geocodes(indicator):\n continue\n indicator_ids.append(indicator_id)\n return indicator_ids\n\n\n def get_documentation_description(self):\n return 'This output contains GeoJSON for those indicators that have geocoded data.'\n" ]
[ [ "pandas.isna" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.1", "1.5", "1.2", "0.24", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
shawdm/experiments-tensorflow-models
[ "eb4b62fd5cb20dcd8e768f122957a1a1c11ba31b" ]
[ "official/resnet/imagenet_main.py" ]
[ "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Runs a ResNet model on the ImageNet dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport tensorflow as tf\n\nimport resnet_model\nimport resnet_shared\nimport vgg_preprocessing\n\n_DEFAULT_IMAGE_SIZE = 224\n_NUM_CHANNELS = 3\n_NUM_CLASSES = 1001\n\n_NUM_IMAGES = {\n 'train': 1281167,\n 'validation': 50000,\n}\n\n_FILE_SHUFFLE_BUFFER = 1024\n_SHUFFLE_BUFFER = 1500\n\n\n###############################################################################\n# Data processing\n###############################################################################\ndef filenames(is_training, data_dir):\n \"\"\"Return filenames for dataset.\"\"\"\n if is_training:\n return [\n os.path.join(data_dir, 'train-%05d-of-01024' % i)\n for i in range(1024)]\n else:\n return [\n os.path.join(data_dir, 'validation-%05d-of-00128' % i)\n for i in range(128)]\n\n\ndef parse_record(raw_record, is_training):\n \"\"\"Parse an ImageNet record from `value`.\"\"\"\n keys_to_features = {\n 'image/encoded':\n tf.FixedLenFeature((), tf.string, default_value=''),\n 'image/format':\n tf.FixedLenFeature((), tf.string, default_value='jpeg'),\n 'image/class/label':\n tf.FixedLenFeature([], dtype=tf.int64, default_value=-1),\n 'image/class/text':\n tf.FixedLenFeature([], dtype=tf.string, default_value=''),\n 'image/object/bbox/xmin':\n tf.VarLenFeature(dtype=tf.float32),\n 'image/object/bbox/ymin':\n tf.VarLenFeature(dtype=tf.float32),\n 'image/object/bbox/xmax':\n tf.VarLenFeature(dtype=tf.float32),\n 'image/object/bbox/ymax':\n tf.VarLenFeature(dtype=tf.float32),\n 'image/object/class/label':\n tf.VarLenFeature(dtype=tf.int64),\n }\n\n parsed = tf.parse_single_example(raw_record, keys_to_features)\n\n image = tf.image.decode_image(\n tf.reshape(parsed['image/encoded'], shape=[]),\n _NUM_CHANNELS)\n image = tf.image.convert_image_dtype(image, dtype=tf.float32)\n\n image = vgg_preprocessing.preprocess_image(\n image=image,\n output_height=_DEFAULT_IMAGE_SIZE,\n output_width=_DEFAULT_IMAGE_SIZE,\n is_training=is_training)\n\n label = tf.cast(\n tf.reshape(parsed['image/class/label'], shape=[]),\n dtype=tf.int32)\n\n return image, tf.one_hot(label, _NUM_CLASSES)\n\n\ndef input_fn(is_training, data_dir, batch_size, num_epochs=1):\n \"\"\"Input function which provides batches for train or eval.\"\"\"\n dataset = tf.data.Dataset.from_tensor_slices(\n filenames(is_training, data_dir))\n\n if is_training:\n dataset = dataset.shuffle(buffer_size=_FILE_SHUFFLE_BUFFER)\n\n dataset = dataset.flat_map(tf.data.TFRecordDataset)\n dataset = dataset.map(lambda value: parse_record(value, is_training),\n num_parallel_calls=5)\n dataset = dataset.prefetch(batch_size)\n\n if is_training:\n # When choosing shuffle buffer sizes, larger sizes result in better\n # randomness, while smaller sizes have better performance.\n dataset = dataset.shuffle(buffer_size=_SHUFFLE_BUFFER)\n\n # We call repeat after shuffling, rather than before, to prevent separate\n # epochs from blending together.\n dataset = dataset.repeat(num_epochs)\n dataset = dataset.batch(batch_size)\n\n iterator = dataset.make_one_shot_iterator()\n images, labels = iterator.get_next()\n return images, labels\n\n\n###############################################################################\n# Running the model\n###############################################################################\nclass ImagenetModel(resnet_model.Model):\n def __init__(self, resnet_size, data_format=None):\n \"\"\"These are the parameters that work for Imagenet data.\n \"\"\"\n\n # For bigger models, we want to use \"bottleneck\" layers\n if resnet_size < 50:\n block_fn = resnet_model.building_block\n final_size = 512\n else:\n block_fn = resnet_model.bottleneck_block\n final_size = 2048\n\n super(ImagenetModel, self).__init__(\n resnet_size=resnet_size,\n num_classes=_NUM_CLASSES,\n num_filters=64,\n kernel_size=7,\n conv_stride=2,\n first_pool_size=3,\n first_pool_stride=2,\n second_pool_size=7,\n second_pool_stride=1,\n block_fn=block_fn,\n block_sizes=_get_block_sizes(resnet_size),\n block_strides=[1, 2, 2, 2],\n final_size=final_size,\n data_format=data_format)\n\n\ndef _get_block_sizes(resnet_size):\n \"\"\"The number of block layers used for the Resnet model varies according\n to the size of the model. This helper grabs the layer set we want, throwing\n an error if a non-standard size has been selected.\n \"\"\"\n choices = {\n 18: [2, 2, 2, 2],\n 34: [3, 4, 6, 3],\n 50: [3, 4, 6, 3],\n 101: [3, 4, 23, 3],\n 152: [3, 8, 36, 3],\n 200: [3, 24, 36, 3]\n }\n\n try:\n return choices[resnet_size]\n except KeyError:\n err = ('Could not find layers for selected Resnet size.\\n'\n 'Size received: {}; sizes allowed: {}.'.format(\n resnet_size, choices.keys()))\n raise ValueError(err)\n\n\ndef imagenet_model_fn(features, labels, mode, params):\n \"\"\"Our model_fn for ResNet to be used with our Estimator.\"\"\"\n learning_rate_fn = resnet_shared.learning_rate_with_decay(\n batch_size=params['batch_size'], batch_denom=256,\n num_images=_NUM_IMAGES['train'], boundary_epochs=[30, 60, 80, 90],\n decay_rates=[1, 0.1, 0.01, 0.001, 1e-4])\n\n return resnet_shared.resnet_model_fn(features, labels, mode, ImagenetModel,\n resnet_size=params['resnet_size'],\n weight_decay=1e-4,\n learning_rate_fn=learning_rate_fn,\n momentum=0.9,\n data_format=params['data_format'],\n loss_filter_fn=None)\n\n\ndef main(unused_argv):\n resnet_shared.resnet_main(FLAGS, imagenet_model_fn, input_fn)\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n\n parser = resnet_shared.ResnetArgParser(\n resnet_size_choices=[18, 34, 50, 101, 152, 200])\n FLAGS, unparsed = parser.parse_known_args()\n tf.app.run(argv=[sys.argv[0]] + unparsed)\n" ]
[ [ "tensorflow.FixedLenFeature", "tensorflow.reshape", "tensorflow.logging.set_verbosity", "tensorflow.image.convert_image_dtype", "tensorflow.VarLenFeature", "tensorflow.one_hot", "tensorflow.parse_single_example", "tensorflow.app.run" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
jmoraga-mines/SparseConvNet
[ "735600176a05259eea5a93a47f320b008f463eaa" ]
[ "setup.py" ]
[ "# Copyright 2016-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport torch, os\nfrom torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension\nfrom setuptools import setup, find_packages\n\nthis_dir = os.path.dirname(os.path.realpath(__file__))\ntorch_dir = os.path.dirname(torch.__file__)\nconda_include_dir = '/'.join(torch_dir.split('/')[:-4]) + '/include'\n\nextra = {'cxx': ['-std=c++11', '-fopenmp'], 'nvcc': ['-std=c++11', '-Xcompiler', '-fopenmp']}\n\nsetup(\n name='sparseconvnet',\n version='0.2',\n description='Submanifold (Spatially) Sparse Convolutional Networks https://arxiv.org/abs/1706.01307',\n author='Facebook AI Research',\n author_email='[email protected]',\n url='https://github.com/facebookresearch/SparseConvNet',\n packages=['sparseconvnet','sparseconvnet.SCN'],\n ext_modules=[\n CUDAExtension('sparseconvnet.SCN',\n [\n 'sparseconvnet/SCN/cuda.cu', 'sparseconvnet/SCN/sparseconvnet_cuda.cpp', 'sparseconvnet/SCN/pybind.cpp'],\n include_dirs=[conda_include_dir, this_dir+'/sparseconvnet/SCN/'],\n extra_compile_args=extra)\n # if torch.cuda.is_available() else\n # CppExtension('sparseconvnet.SCN',\n # ['sparseconvnet/SCN/pybind.cpp', 'sparseconvnet/SCN/sparseconvnet_cpu.cpp'],\n # include_dirs=[conda_include_dir, this_dir+'/sparseconvnet/SCN/'],\n # extra_compile_args=extra['cxx'])],\n ],\n cmdclass={'build_ext': BuildExtension},\n zip_safe=False,\n)\n" ]
[ [ "torch.utils.cpp_extension.CUDAExtension" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pixel-ports/PPA_Traffic_Prediction
[ "5a4f3e7746bea024a8c05307328548bef934a733" ]
[ "Scripts/WeatherData.py" ]
[ "import pandas as pd\r\nimport ast\r\n\r\n\r\n\r\ndef aggregation_functionWeather(a):\r\n\r\n df = pd.DataFrame()\r\n df = pd.read_csv(r'C:\\Users\\sergi\\Desktop\\Environment\\Raw Data\\WeatherRawData.csv')\r\n weather_data = pd.DataFrame()\r\n\r\n for index, row in df.iterrows():\r\n darkSky = row['darkSkyPireaus']\r\n dict_darkSky = ast.literal_eval(darkSky)\r\n currently = dict_darkSky['currently']\r\n \r\n weather_data = weather_data.append(currently, ignore_index = True)\r\n weather_data['time'] = weather_data['time'].apply(lambda x: pd.Timestamp(x, unit = 's'))\r\n weather_data = weather_data.drop_duplicates()\r\n \r\n weather_data['time'] = pd.to_datetime(weather_data['time'], format='%Y-%m-%d %H:%M:%S')\r\n weather_data['time'] = weather_data['time'].map(lambda x: x.replace(second=0))\r\n a = str(a) + 'Min'\r\n weather_data.set_index('time', inplace = True)\r\n weather_data = weather_data.groupby(pd.Grouper(freq=a)).mean()\r\n\r\n return weather_data" ]
[ [ "pandas.read_csv", "pandas.to_datetime", "pandas.Grouper", "pandas.DataFrame", "pandas.Timestamp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DongxuGuo1997/TransNet
[ "a720c0b1ac18db19796409b51e1cab96b744a4f0" ]
[ "src/model/baselines.py" ]
[ "import torch\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.ops import RoIAlign\nfrom .basenet import *\n\n\nclass Res18Crop(torch.nn.Module):\n \"\"\"\n CNN for single frame model with cropped image.\n \"\"\"\n\n def __init__(self, backbone, drop_p=0.5):\n super(Res18Crop, self).__init__()\n self.backbone = backbone\n self.conv1 = nn.Conv2d(512, 64, kernel_size=3, stride=2, padding=1)\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout(p=drop_p)\n self.act = nn.Sigmoid()\n self.linear = nn.Linear(1024, 1)\n\n def forward(self, x):\n x = self.backbone(x)\n x = self.conv1(x)\n x = self.relu(x)\n x = self.dropout(x)\n x = x.view(-1, 1024)\n x = self.linear(x)\n x = self.act(x)\n\n return x\n\n\nclass Res18RoI(torch.nn.Module):\n \"\"\"\n CNN for single frame model. ResNet-18 bacbone and RoI for adding context.\n \"\"\"\n\n def __init__(self, resnet, last_block, drop_p=0.5):\n super(Res18RoI, self).__init__()\n self.resnet = resnet\n self.last_block = last_block.apply(set_conv2d_stride1)\n self.conv_last = torch.nn.Conv2d(512, 64, kernel_size=3, stride=2, padding=1)\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout(p=drop_p)\n self.FC = torch.nn.Linear(1024, 1)\n self.act = torch.nn.Sigmoid()\n\n def forward(self, imgs, bboxes):\n feature_maps = self.resnet(imgs)\n fa = RoIAlign(output_size=(7, 7), spatial_scale=1 / 8,\n sampling_ratio=2, aligned=True)\n ya = fa(feature_maps, bboxes)\n y = self.last_block(ya)\n y = self.conv_last(y)\n y = self.relu(y)\n y = self.dropout(y)\n y = y.view(1, -1)\n y = self.FC(y)\n y = self.act(y)\n\n return y\n\n\nclass Res18CropEncoder(nn.Module):\n def __init__(self, resnet):\n super(Res18CropEncoder, self).__init__()\n\n self.resnet = resnet\n # self.fc = nn.Linear(1024, CNN_embed_dim)\n\n def forward(self, x_5d, x_lengths):\n x_seq = []\n for i in range(x_5d.size(0)):\n cnn_embed_seq = []\n for t in range(x_lengths[i]):\n with torch.no_grad():\n img = x_5d[i, t, :, :, :]\n x = self.resnet(torch.unsqueeze(img, dim=0)) # ResNet\n x = x.view(x.size(0), -1) # flatten output of conv\n cnn_embed_seq.append(x)\n # swap time and sample dim such that (sample dim=1, time dim, CNN latent dim)\n embed_seq = torch.stack(cnn_embed_seq, dim=0).transpose_(0, 1)\n embed_seq = torch.squeeze(embed_seq)\n fea_dim = embed_seq.shape[-1]\n embed_seq = embed_seq.view(-1, fea_dim)\n x_seq.append(embed_seq)\n # pad feature vector sequences\n x_padded = nn.utils.rnn.pad_sequence(x_seq, batch_first=True, padding_value=0)\n\n return x_padded\n\n\nclass Res18RoIEncoder(nn.Module):\n \"\"\"\n Image feature encoder based on ResNet-18 backbone with RoI align\n \"\"\"\n\n def __init__(self, encoder):\n super(Res18RoIEncoder, self).__init__()\n\n self.encoder = encoder\n # self.fc = nn.Linear(1024, CNN_embed_dim)\n\n def forward(self, x_5d, bbox_list, x_lengths):\n x_seq = []\n for i in range(x_5d.size(0)):\n cnn_embed_seq = []\n for t in range(x_lengths[i]):\n with torch.no_grad():\n img = x_5d[i, t, :, :, :]\n bbox = [bbox_list[t][i]]\n x = self.encoder(torch.unsqueeze(img, dim=0), bbox) # ResNet\n cnn_embed_seq.append(x)\n # swap time and sample dim such that (sample dim=1, time dim, CNN latent dim)\n embed_seq = torch.stack(cnn_embed_seq, dim=0).transpose_(0, 1)\n embed_seq = torch.squeeze(embed_seq)\n fea_dim = embed_seq.shape[-1]\n embed_seq = embed_seq.view(-1, fea_dim)\n x_seq.append(embed_seq)\n # pad feature vector sequences\n x_padded = nn.utils.rnn.pad_sequence(x_seq, batch_first=True, padding_value=0)\n\n return x_padded\n\n\nclass DecoderRNN(nn.Module):\n \"\"\"\n RNN decoder for transition prediction (classification task)\n \"\"\"\n\n def __init__(self, RNN_type='LSTM', embed_dim=1024, h_RNN_layers=1, h_RNN=256, h_FC_dim=128, drop_p=0.2):\n super(DecoderRNN, self).__init__()\n\n assert RNN_type in ['LSTM', 'GRU'], 'Invalid RNN type'\n self.RNN_input_size = embed_dim\n self.h_RNN_layers = h_RNN_layers # RNN hidden layers\n self.h_RNN = h_RNN # RNN hidden nodes\n self.h_FC_dim = h_FC_dim\n self.dropout = nn.Dropout(p=drop_p)\n if RNN_type == 'LSTM':\n self.RNN = nn.LSTM(\n input_size=self.RNN_input_size,\n hidden_size=self.h_RNN,\n num_layers=h_RNN_layers,\n batch_first=True # input & output have batch size as 1s dimension. e.g. (batch, time_step, input_size)\n )\n else:\n self.RNN = nn.GRU(\n input_size=self.RNN_input_size,\n hidden_size=self.h_RNN,\n num_layers=h_RNN_layers,\n batch_first=True\n )\n # dense layers for classification\n self.fc1 = nn.Linear(self.h_RNN, self.h_FC_dim)\n self.fc2 = nn.Linear(self.h_FC_dim, 1)\n self.act = nn.Sigmoid()\n\n def forward(self, x_3d, x_lengths):\n packed_x_RNN = torch.nn.utils.rnn.pack_padded_sequence(x_3d, x_lengths, batch_first=True, enforce_sorted=False)\n self.RNN.flatten_parameters()\n packed_RNN_out, _ = self.RNN(packed_x_RNN, None)\n \"\"\" h_n shape (n_layers, batch, hidden_size), h_c shape (n_layers, batch, hidden_size) \"\"\"\n \"\"\" None represents zero initial hidden state. RNN_out has shape=(batch, time_step, output_size) \"\"\"\n\n RNN_out, _ = torch.nn.utils.rnn.pad_packed_sequence(packed_RNN_out, batch_first=True)\n RNN_out = RNN_out.contiguous()\n # RNN_out = RNN_out.view(-1, RNN_out.size(2))\n\n # FC layers\n x = self.fc1(RNN_out[:, -1, :]) # choose RNN_out at the last time step\n x = F.relu(x)\n x = self.dropout(x)\n x = self.fc2(x)\n x = self.act(x)\n\n return x\n" ]
[ [ "torch.nn.Dropout", "torch.nn.LSTM", "torch.nn.Conv2d", "torch.nn.utils.rnn.pad_sequence", "torch.nn.GRU", "torch.nn.utils.rnn.pack_padded_sequence", "torch.nn.Sigmoid", "torch.unsqueeze", "torch.nn.Linear", "torch.nn.utils.rnn.pad_packed_sequence", "torch.nn.functional.relu", "torch.no_grad", "torch.stack", "torch.nn.ReLU", "torch.squeeze" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
svenkilian/Deep-Reinforcement-Learning-Hands-On
[ "b9ab995722bd692828ce3e6f50026fa87e5f924b" ]
[ "Chapter06/02_dqn_pong.py" ]
[ "#!/usr/bin/env python3\nfrom lib import wrappers\nfrom lib import dqn_model\n\nimport argparse\nimport time\nimport numpy as np\nimport collections\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom tensorboardX import SummaryWriter\n\n\nDEFAULT_ENV_NAME = \"PongNoFrameskip-v4\"\nMEAN_REWARD_BOUND = 19.5\n\nGAMMA = 0.99\nBATCH_SIZE = 32\nREPLAY_SIZE = 10000\nLEARNING_RATE = 1e-4\nSYNC_TARGET_FRAMES = 1000\nREPLAY_START_SIZE = 10000\n\nEPSILON_DECAY_LAST_FRAME = 10**5\nEPSILON_START = 1.0\nEPSILON_FINAL = 0.02\n\n\nExperience = collections.namedtuple('Experience', field_names=[\n 'state', 'action', 'reward', 'done', 'new_state'])\n\n\nclass ExperienceBuffer:\n def __init__(self, capacity):\n self.buffer = collections.deque(maxlen=capacity)\n\n def __len__(self):\n return len(self.buffer)\n\n def append(self, experience):\n self.buffer.append(experience)\n\n def sample(self, batch_size):\n indices = np.random.choice(len(self.buffer), batch_size, replace=False)\n states, actions, rewards, dones, next_states = zip(\n *[self.buffer[idx] for idx in indices])\n return np.array(states), np.array(actions), np.array(rewards, dtype=np.float32), \\\n np.array(dones, dtype=np.uint8), np.array(next_states)\n\n\nclass Agent:\n def __init__(self, env, exp_buffer):\n self.env = env\n self.exp_buffer = exp_buffer\n self._reset()\n\n def _reset(self):\n self.state = env.reset()\n self.total_reward = 0.0\n\n def play_step(self, net, epsilon=0.0, device=\"cpu\"):\n done_reward = None\n\n if np.random.random() < epsilon:\n action = env.action_space.sample()\n else:\n state_a = np.array([self.state], copy=False)\n state_v = torch.tensor(state_a).to(device)\n q_vals_v = net(state_v)\n _, act_v = torch.max(q_vals_v, dim=1)\n action = int(act_v.item())\n\n # do step in the environment\n new_state, reward, is_done, _ = self.env.step(action)\n self.total_reward += reward\n\n exp = Experience(self.state, action, reward, is_done, new_state)\n self.exp_buffer.append(exp)\n self.state = new_state\n if is_done:\n done_reward = self.total_reward\n self._reset()\n return done_reward\n\n\ndef calc_loss(batch, net, tgt_net, device=\"cpu\"):\n states, actions, rewards, dones, next_states = batch\n\n states_v = torch.tensor(states).to(device)\n next_states_v = torch.tensor(next_states).to(device)\n actions_v = torch.tensor(actions).to(device)\n rewards_v = torch.tensor(rewards).to(device)\n done_mask = torch.ByteTensor(dones).to(device)\n\n state_action_values = net(states_v).gather(\n 1, actions_v.unsqueeze(-1)).squeeze(-1)\n next_state_values = tgt_net(next_states_v).max(1)[0]\n next_state_values[done_mask] = 0.0\n next_state_values = next_state_values.detach()\n\n expected_state_action_values = next_state_values * GAMMA + rewards_v\n return nn.MSELoss()(state_action_values, expected_state_action_values)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--cuda\", default=False,\n action=\"store_true\", help=\"Enable cuda\")\n parser.add_argument(\"--env\", default=DEFAULT_ENV_NAME,\n help=\"Name of the environment, default=\" + DEFAULT_ENV_NAME)\n parser.add_argument(\"--reward\", type=float, default=MEAN_REWARD_BOUND,\n help=\"Mean reward boundary for stop of training, default=%.2f\" % MEAN_REWARD_BOUND)\n args = parser.parse_args()\n device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n\n env = wrappers.make_env(args.env)\n\n net = dqn_model.DQN(env.observation_space.shape,\n env.action_space.n).to(device)\n tgt_net = dqn_model.DQN(env.observation_space.shape,\n env.action_space.n).to(device)\n writer = SummaryWriter(comment=\"-\" + args.env)\n print(net)\n\n buffer = ExperienceBuffer(REPLAY_SIZE)\n agent = Agent(env, buffer)\n epsilon = EPSILON_START\n\n optimizer = optim.Adam(net.parameters(), lr=LEARNING_RATE)\n total_rewards = []\n frame_idx = 0\n ts_frame = 0\n ts = time.time()\n best_mean_reward = None\n\n while True:\n frame_idx += 1\n epsilon = max(EPSILON_FINAL, EPSILON_START -\n frame_idx / EPSILON_DECAY_LAST_FRAME)\n\n reward = agent.play_step(net, epsilon, device=device)\n if reward is not None:\n total_rewards.append(reward)\n speed = (frame_idx - ts_frame) / (time.time() - ts)\n ts_frame = frame_idx\n ts = time.time()\n mean_reward = np.mean(total_rewards[-100:])\n print(\"%d: done %d games, mean reward %.3f, eps %.2f, speed %.2f f/s\" % (\n frame_idx, len(total_rewards), mean_reward, epsilon,\n speed\n ))\n writer.add_scalar(\"epsilon\", epsilon, frame_idx)\n writer.add_scalar(\"speed\", speed, frame_idx)\n writer.add_scalar(\"reward_100\", mean_reward, frame_idx)\n writer.add_scalar(\"reward\", reward, frame_idx)\n if best_mean_reward is None or best_mean_reward < mean_reward:\n torch.save(net.state_dict(), args.env + \"-best.dat\")\n if best_mean_reward is not None:\n print(\"Best mean reward updated %.3f -> %.3f, model saved\" %\n (best_mean_reward, mean_reward))\n best_mean_reward = mean_reward\n if mean_reward > args.reward:\n print(\"Solved in %d frames!\" % frame_idx)\n break\n\n if len(buffer) < REPLAY_START_SIZE:\n continue\n\n if frame_idx % SYNC_TARGET_FRAMES == 0:\n tgt_net.load_state_dict(net.state_dict())\n\n optimizer.zero_grad()\n batch = buffer.sample(BATCH_SIZE)\n loss_t = calc_loss(batch, net, tgt_net, device=device)\n loss_t.backward()\n optimizer.step()\n writer.close()\n" ]
[ [ "torch.ByteTensor", "numpy.random.random", "torch.max", "torch.tensor", "numpy.mean", "torch.device", "numpy.array", "torch.nn.MSELoss" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
QuantLaw/legal-data-preprocessing
[ "c5462ba946e858d5e33a4698e9da350402903bca" ]
[ "utils/common.py" ]
[ "import argparse\nimport os\nimport pickle\nimport shutil\nfrom collections import Counter\n\nimport pandas as pd\nfrom quantlaw.utils.files import ensure_exists\nfrom quantlaw.utils.pipeline import PipelineStep\nfrom regex import regex\n\nfrom statics import (\n DATA_PATH,\n DE_LAW_NAMES_COMPILED_PATH,\n DE_LAW_NAMES_PATH,\n DE_REG_LAW_NAMES_COMPILED_PATH,\n DE_REG_LAW_NAMES_PATH,\n)\n\n##########\n# Pipeline\n##########\n\n\nclass RegulationsPipelineStep(PipelineStep):\n def __init__(self, regulations, *args, **kwargs):\n self.regulations = regulations\n super().__init__(*args, **kwargs)\n\n\ndef str_to_bool(v):\n if isinstance(v, bool):\n return v\n if v.lower() in (\"yes\", \"true\", \"t\", \"y\", \"1\"):\n return True\n elif v.lower() in (\"no\", \"false\", \"f\", \"n\", \"0\"):\n return False\n else:\n raise argparse.ArgumentTypeError(\"Boolean value expected.\")\n\n\n########################\n# Generic Data Wrangling\n########################\n\n\ndef invert_dict_mapping_all(mapping_dictionary):\n \"\"\"\n Args:\n mapping_dictionary: mapping from keys to values which is not necessarily\n injective, e.g., node_id to community_id mapping\n\n Returns: inverted mapping with unique values as keys and lists of former keys as\n values, e.g., community_id to node_id mapping\n\n \"\"\"\n inverted = {v: [] for v in mapping_dictionary.values()}\n for k, v in mapping_dictionary.items():\n inverted[v].append(k)\n return inverted\n\n\ndef invert_dict_mapping_unique(source_dict):\n \"\"\"\n Inverts keys and values of a dict. Only entries with unique values are inverted.\n \"\"\"\n counter = Counter(source_dict.values())\n unique = set([text for text, cnt in counter.most_common() if cnt == 1])\n return {v: k for k, v in source_dict.items() if v in unique}\n\n\n####################\n# DE Crossreferences\n####################\n\n\ndef load_law_names(regulations):\n df = pd.read_csv(DE_REG_LAW_NAMES_PATH if regulations else DE_LAW_NAMES_PATH)\n data = [\n dict(\n citename=row.citename,\n citekey=row.citekey,\n start=row.filename.split(\"_\")[2],\n end=os.path.splitext(row.filename)[0].split(\"_\")[3],\n filename=row.filename,\n )\n for i, row in df.iterrows()\n ]\n return data\n\n\ndef load_law_names_compiled(regulations):\n with open(\n DE_REG_LAW_NAMES_COMPILED_PATH if regulations else DE_LAW_NAMES_COMPILED_PATH,\n \"rb\",\n ) as f:\n return pickle.load(f)\n\n\ndef get_stemmed_law_names_for_filename(filename, law_names):\n date = os.path.splitext(filename)[0].split(\"_\")[2]\n return get_stemmed_law_names(date, law_names)\n\n\ndef get_stemmed_law_names(date, law_names):\n laws_lookup = law_names[date]\n\n # Custom law names, stemmed as key.\n laws_lookup[\"grundgesetz\"] = \"GG\"\n\n # Add law names without year number if key already used\n shortened_keys = {}\n for key, value in laws_lookup.items():\n match = regex.fullmatch(r\"(.+)\\s\\d{4}[\\-\\d]*\", key)\n if match:\n if match[1] not in shortened_keys:\n shortened_keys[match[1]] = set()\n shortened_keys[match[1]].update([value])\n\n for key, values in shortened_keys.items():\n if len(values) == 1 and key not in laws_lookup.keys():\n laws_lookup[key] = list(values)[0]\n\n return laws_lookup\n\n\ndef get_snapshot_law_list(date, law_names_data):\n date = date.replace(\"-\", \"\")\n law_names_list = {\n d[\"filename\"] for d in law_names_data if d[\"start\"] <= date and d[\"end\"] >= date\n }\n assert len(law_names_list) == len({x.split(\"_\")[0] for x in law_names_list})\n return law_names_list\n\n\ndef copy_xml_schema_to_data_folder():\n ensure_exists(DATA_PATH)\n shutil.copyfile(\"xml-schema.xsd\", os.path.join(DATA_PATH, \"xml-schema.xsd\"))\n shutil.copyfile(\"xml-styles.css\", os.path.join(DATA_PATH, \"xml-styles.css\"))\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
Guymer/flffc
[ "635f863c3f45158fdf5ea9afa091c1de8439bdf0" ]
[ "run.py" ]
[ "def run(dirOut = \"FLFFCoutput\", country = \"United Kingdom\", steps = 50):\n # Import standard modules ...\n import os\n\n # Import special modules ...\n try:\n import cartopy\n import cartopy.crs\n import cartopy.io\n import cartopy.io.shapereader\n except:\n raise Exception(\"\\\"cartopy\\\" is not installed; run \\\"pip install --user Cartopy\\\"\") from None\n try:\n import matplotlib\n matplotlib.use(\"Agg\") # NOTE: See https://matplotlib.org/stable/gallery/user_interfaces/canvasagg.html\n import matplotlib.pyplot\n except:\n raise Exception(\"\\\"matplotlib\\\" is not installed; run \\\"pip install --user matplotlib\\\"\") from None\n try:\n import numpy\n except:\n raise Exception(\"\\\"numpy\\\" is not installed; run \\\"pip install --user numpy\\\"\") from None\n try:\n import shapely\n import shapely.geometry\n except:\n raise Exception(\"\\\"shapely\\\" is not installed; run \\\"pip install --user Shapely\\\"\") from None\n\n # Import my modules ...\n try:\n import pyguymer3\n import pyguymer3.geo\n import pyguymer3.image\n except:\n raise Exception(\"\\\"pyguymer3\\\" is not installed; you need to have the Python module from https://github.com/Guymer/PyGuymer3 located somewhere in your $PYTHONPATH\") from None\n\n # Make output directory ...\n if not os.path.exists(dirOut):\n os.makedirs(dirOut)\n\n # Find file containing all the country shapes ...\n shape_file = cartopy.io.shapereader.natural_earth(\n resolution = \"10m\",\n category = \"cultural\",\n name = \"admin_0_countries\"\n )\n\n # Loop over records ...\n for record in cartopy.io.shapereader.Reader(shape_file).records():\n # Skip this record if it is not the one we are looking for ...\n if record.attributes[\"NAME\"] != country:\n continue\n\n # Find extent of the country ...\n lon_min, lat_min, lon_max, lat_max = record.bounds # [°], [°], [°], [°]\n print(\"The bounding box of {:s} is from ({:.2f},{:.2f}) to ({:.2f},{:.2f}).\".format(record.attributes[\"NAME\"], lon_min, lat_min, lon_max, lat_max))\n\n # Create plot and make it pretty ...\n fg = matplotlib.pyplot.figure(figsize = (9, 6), dpi = 300)\n ax = matplotlib.pyplot.axes(projection = cartopy.crs.PlateCarree())\n ax.set_extent(\n [\n lon_min - 0.1,\n lon_max + 0.1,\n lat_min - 0.1,\n lat_max + 0.1\n ]\n )\n pyguymer3.geo.add_map_background(ax, resolution = \"large4096px\")\n ax.coastlines(resolution = \"10m\", color = \"black\", linewidth = 0.1)\n\n # Make longitude and latitude grid ...\n xcoords = numpy.linspace(lon_min, lon_max, num = steps) # [°]\n ycoords = numpy.linspace(lat_min, lat_max, num = steps) # [°]\n\n # Make empty lists of points ...\n xpoints = [] # [°]\n ypoints = [] # [°]\n zpoints = [] # [m]\n\n # Loop over longitudes ...\n for ix in range(xcoords.size):\n print(\"Calculating slice {:d} of {:d} ...\".format(ix + 1, xcoords.size))\n\n # Loop over latitudes ...\n for iy in range(ycoords.size):\n # Skip this point if it is not within the geometry ...\n if not record.geometry.contains(shapely.geometry.Point(xcoords[ix], ycoords[iy])):\n continue\n\n # Set a silly initial minimum ...\n # NOTE: Earth's mean radius is 6,371,009 m.\n # NOTE: Therefore, Earth's mean circumference is 40,030,230 m.\n zpoint1 = 5.0e7 # [m]\n\n # Loop over boundaries ...\n for boundary in record.geometry.boundary:\n # Loop over coordinates ...\n for coord in boundary.coords:\n # Find distance between points ...\n zpoint2, alpha1, alpha2 = pyguymer3.geo.calc_dist_between_two_locs(\n lon1_deg = xcoords[ix],\n lat1_deg = ycoords[iy],\n lon2_deg = coord[0],\n lat2_deg = coord[1]\n ) # [m], [°], [°]\n\n # Replace current minimum if required ...\n if zpoint2 < zpoint1:\n zpoint1 = zpoint2 # [m]\n\n # Add values to lists (converting from m to km) ...\n xpoints.append(xcoords[ix]) # [°]\n ypoints.append(ycoords[iy]) # [°]\n zpoints.append(zpoint1 / 1000.0) # [km]\n\n print(\"The furthest you can get from the coast is ~{:.1f} km.\".format(max(zpoints)))\n\n # Plot points ...\n # NOTE: Default value of the optional keyword argument \"s\" (as of\n # November 2016) is \"20 points ^ 2\". Therefore, the nominal width/\n # height is approximately \"4.5 points\" (assuming that the circles\n # are actually sized like squares). I want to scale the width/\n # height so that the circles do not overlap. The following tweak\n # should do that as different users request different numbers of\n # steps. With the default value of \"steps = 50\" the size will be\n # \"16 points ^ 2\" - a slightly smaller area than default.\n sc = matplotlib.pyplot.scatter(\n xpoints,\n ypoints,\n s = (200 / steps) ** 2,\n c = zpoints,\n alpha = 0.5,\n linewidth = 0.5,\n cmap = matplotlib.pyplot.cm.rainbow,\n vmin = 0.0,\n transform = cartopy.crs.Geodetic()\n )\n\n # Add colour bar ...\n cb = matplotlib.pyplot.colorbar(sc)\n cb.set_label(\"Distance [km]\")\n\n # Save map as PNG ...\n ax.set_title(\"Location Furthest From Coast\")\n fg.savefig(\n os.path.join(dirOut, \"{:s}.png\".format(country)),\n bbox_inches = \"tight\",\n dpi = 300,\n pad_inches = 0.1\n )\n pyguymer3.image.optimize_image(os.path.join(dirOut, \"{:s}.png\".format(country)), strip = True)\n matplotlib.pyplot.close(fg)\n" ]
[ [ "numpy.linspace", "matplotlib.use", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.close", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kfollette/QuaRCS
[ "9ca0d997d6b20caeac45f1322f82de15f0450b65" ]
[ "tutorials/scoring tutorial/score.py" ]
[ "from factor_analyzer import FactorAnalyzer, Rotator, calculate_bartlett_sphericity, calculate_kmo\nfrom sklearn.utils import check_array\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nimport numpy as np\n\ndef score(database, semester, year, season, answer_key, savedname):\n '''\n Modified so that it uses numerical values of question/answer rather than string values.\n By:\n Ilija Nikolov, 5 March 2018\n '''\n\n '''\n The score function reads in a QuaRCS dataset and answer key file to create a series of columns\n to add to the dataset. The function creates columns for:\n - score on a binary scale (1 for correct, 0 for incorrect)\n - total score\n - totals and means by category\n - number of questions answered\n - total and mean confidence\n Args:\n database: pre or post QuaRCS dataset for a semester\n answer_key: QuaRCS Assessment Answer Key\n semester: 'PRE' or 'PST'\n Output:\n name of file + '_scored' as .csv file\n Example:\n score('QuaRCS_Summer_2017_Pre.csv', 'PRE', QuaRCS Assessment Answer Key.csv', QuaRCS_Summer_2017_Pre )\n New File saved under QuaRCS_Summer_2017_Pre_scored.csv\n Check folder for files\n By:\n Abdoulaye Sanogo, 08/11/2017\n Future Improvements:\n add columns for confidence means and totals by category\n add extra colums after insert so the deletion of columns will not be necessary\n '''\n\n question = semester + \"_Q\" # question = 'PRE_Q' or 'PST_Q'\n\n data = pd.read_csv(database, encoding = 'utf-8', skiprows = [1,2], header = 0)\n df = pd.read_csv(answer_key, encoding = 'utf-8')\n\n\n cols = list(data.columns.values)\n c = len(cols)\n e = 0\n h = len(data)\n\n # Adds the Q#_SCORE column right next to each question\n questions = np.unique(df['Question #'])\n\n for item in questions:\n if(question+str(item) in data.columns):\n data.insert(data.columns.get_loc(question+str(item))+1,question+str(item)+'_SCORE', 0)\n\n # e >= 50 --> Full, e < 50 --> Lite\n for d in range(c):\n column = cols[d]\n column = column[0:5]\n\n if question == column:\n e = e + 1\n\n data.insert(6 , 'VERSION', \" \")\n\n if e == 50:\n if(year == \"16\" and season == \"Fa\"):\n data['VERSION'] = \"Fl_2.0\"\n # If the value \"progress bar\" is in comments, change the version to 2.1\n for v in range(h):\n if 'COMMENTS' in data.columns:\n if (data.loc[v, 'COMMENTS'] == \"progress bar\"):\n data.loc[v, 'VERSION'] = \"Fl_2.1\"\n else:\n data['VERSION'] = \"Fl_1.1\"\n elif e == 54:\n data['VERSION'] = \"Fl_1.0\"\n data = data.drop([semester + '_Q18'], axis=1)\n data = data.drop([semester + '_Q18CF'], axis=1)\n data = data.drop([semester + '_Q25'], axis=1)\n data = data.drop([semester + '_Q25CF'], axis=1)\n e = 50\n elif e == 22:\n data['VERSION'] = \"Lt_1.0\"\n elif e == 30:\n intyr = int(year)\n if (intyr >= 19 or (year == \"18\" and season == \"Fa\")):\n data['VERSION'] = \"Lt_2.1\"\n else:\n data['VERSION'] = \"Lt_2.0\"\n elif e == 28:\n data['VERSION'] = \"SM_1.0\"\n\n # New columns for the totals\n data[semester + '_TOTAL'] = np.nan\n data[semester + '_PCT_TOTAL'] = np.nan\n data[semester + '_GR_TOTAL'] = np.nan\n data[semester + '_GR_MEAN'] = np.nan\n data[semester + '_AR_TOTAL'] = np.nan\n data[semester + '_AR_MEAN'] = np.nan\n data[semester + '_PR_TOTAL'] = np.nan\n data[semester + '_PR_MEAN'] = np.nan\n data[semester + '_PC_TOTAL'] = np.nan\n data[semester + '_PC_MEAN'] = np.nan\n data[semester + '_SP_TOTAL'] = np.nan\n data[semester + '_SP_MEAN'] = np.nan\n data[semester + '_TR_TOTAL'] = np.nan\n data[semester + '_TR_MEAN'] = np.nan\n data[semester + '_AV_TOTAL'] = np.nan\n data[semester + '_AV_MEAN'] = np.nan\n #data[semester + '_ER_MEAN'] = np.nan\n data[semester + '_UD_TOTAL'] = np.nan\n data[semester + '_UD_MEAN'] = np.nan\n data[semester + '_ES_TOTAL'] = np.nan\n data[semester + '_ES_MEAN'] = np.nan\n\n # Composite Variables\n data[semester + '_SELFEFF'] = np.nan\n data[semester + '_MATHANX'] = np.nan\n data[semester + '_MATHREL'] = np.nan\n data[semester + '_ACADMAT'] = np.nan\n data[semester + '_SCHMATH'] = np.nan\n\n corr_ans = {15: 0, 12:0, 14:0, 26:0, 27:0, 23:0, 28:0, 19:0, 3:0, 16:0, 13:0, 31:0,\n 32:0, 29:0, 30:0, 5:0, 6:0, 7:0, 10:0, 11:0, 20:0, 21:0, 33:0, 34:0, 35:0}\n for item in corr_ans:\n corr_ans[item] = int(list(df.loc[df['Question #']==item]['Correct Answer'])[0])\n\n # Adds totals and means to total and means columns\n for nn in range(h):\n qn = {15: 0, 12:0, 14:0, 26:0, 27:0, 23:0, 28:0, 19:0, 3:0, 16:0, 13:0, 31:0, 32:0, 29:0, 30:0, 5:0, 6:0, 7:0, 10:0, 11:0, 20:0, 21:0, 33:0, 34:0, 35:0}\n\n for q_num in qn:\n try:\n\n if(int(data.loc[nn, question + str(q_num)]) == corr_ans[q_num]):\n\n qn[q_num] = 1\n data.loc[nn, question+str(q_num)+'_SCORE'] = 1\n except:\n pass\n\n\n GR = int(np.nansum([qn[15], qn[14], qn[12], qn[29], qn[30], qn[13]]))\n AR = int(np.nansum([qn[15], qn[14], qn[26], qn[27], qn[23], qn[28], qn[19], qn[3], qn[16], qn[31], qn[32], qn[5], qn[6], qn[7], qn[29], qn[30], qn[10], qn[11], qn[20], qn[21], qn[33], qn[34], qn[35]]))\n PR = int(np.nansum([qn[15], qn[12], qn[14], qn[23], qn[28], qn[3], qn[16], qn[7], qn[10], qn[11], qn[20], qn[21], qn[33], qn[35], qn[13]]))\n PC = int(np.nansum([qn[27], qn[3], qn[32], qn[20], qn[21]]))\n SP = int(np.nansum([qn[27], qn[23], qn[28], qn[29], qn[30], qn[20], qn[21]]))\n TR = int(np.nansum([qn[26], qn[27], qn[23]]))\n AV = int(np.nansum([qn[31], qn[10], qn[11], qn[33], qn[34]]))\n UD = int(np.nansum([qn[31], qn[6], qn[7], qn[35], qn[16]]))\n ES = int(np.nansum([qn[15], qn[12], qn[14], qn[16], qn[13]]))\n data.loc[nn, semester + '_GR_TOTAL'] = GR\n data.loc[nn, semester + '_AR_TOTAL'] = AR\n data.loc[nn, semester + '_PR_TOTAL'] = PR\n data.loc[nn, semester + '_PC_TOTAL'] = PC\n data.loc[nn, semester + '_SP_TOTAL'] = SP\n data.loc[nn, semester + '_TR_TOTAL'] = TR\n data.loc[nn, semester + '_AV_TOTAL'] = AV\n data.loc[nn, semester + '_UD_TOTAL'] = UD\n data.loc[nn, semester + '_ES_TOTAL'] = ES\n total_full = 0\n\n for q_num in qn:\n total_full += qn[q_num]\n if e == 50:\n data.loc[nn, semester + '_TOTAL'] = total_full\n data.loc[nn, semester + '_PCT_TOTAL'] = total_full/(25)\n data.loc[nn, semester + '_GR_MEAN'] = GR/6\n data.loc[nn, semester + '_AR_MEAN'] = AR/23\n data.loc[nn, semester + '_PR_MEAN'] = PR/15\n data.loc[nn, semester + '_PC_MEAN'] = PC/5\n data.loc[nn, semester + '_SP_MEAN'] = SP/7\n data.loc[nn, semester + '_TR_MEAN'] = TR/3\n data.loc[nn, semester + '_AV_MEAN'] = AV/5\n data.loc[nn, semester + '_UD_MEAN'] = UD/5\n data.loc[nn, semester + '_ES_MEAN'] = ES/5\n\n elif e == 22:\n data.loc[nn, semester + '_TOTAL'] = total_full\n data.loc[nn, semester + '_PCT_TOTAL'] = total_full/(11)\n data.loc[nn, semester + '_GR_MEAN'] = GR/4\n data.loc[nn, semester + '_AR_MEAN'] = AR/9\n data.loc[nn, semester + '_PR_MEAN'] = PR/8\n data.loc[nn, semester + '_SP_MEAN'] = SP/3\n data.loc[nn, semester + '_TR_MEAN'] = TR/3\n data.loc[nn, semester + '_ES_MEAN'] = ES/5\n\n #lacks number of questions for meaningful subscore\n #1 q\n data.loc[nn, semester + '_UD_MEAN'] = np.nan\n data.loc[nn, semester + '_UD_TOTAL'] = np.nan\n #2 qs\n data.loc[nn, semester + '_PC_MEAN'] = np.nan\n data.loc[nn, semester + '_PC_TOTAL'] = np.nan\n #1 q\n data.loc[nn, semester + '_AV_MEAN'] = np.nan\n data.loc[nn, semester + '_AV_TOTAL'] = np.nan\n\n elif e == 30:\n data.loc[nn, semester + '_TOTAL'] = total_full\n data.loc[nn, semester + '_PCT_TOTAL'] = total_full/(15)\n data.loc[nn, semester + '_GR_MEAN'] = GR/4\n data.loc[nn, semester + '_AR_MEAN'] = AR/13\n data.loc[nn, semester + '_PR_MEAN'] = PR/11\n data.loc[nn, semester + '_SP_MEAN'] = SP/3\n data.loc[nn, semester + '_TR_MEAN'] = TR/3\n data.loc[nn, semester + '_AV_MEAN'] = AV/4\n data.loc[nn, semester + '_ES_MEAN'] = ES/5\n #lacks number of questions for meaningful subscore\n #1 q\n data.loc[nn, semester + '_UD_MEAN'] = np.nan\n data.loc[nn, semester + '_UD_TOTAL'] = np.nan\n #2 qs\n data.loc[nn, semester + '_PC_MEAN'] = np.nan\n data.loc[nn, semester + '_PC_TOTAL'] = np.nan\n\n elif e == 28:\n data.loc[nn, semester + '_TOTAL'] = total_full\n data.loc[nn, semester + '_PCT_TOTAL'] = total_full/(14)\n data.loc[nn, semester + '_GR_MEAN'] = GR/4\n data.loc[nn, semester + '_AR_MEAN'] = AR/13\n data.loc[nn, semester + '_PR_MEAN'] = PR/9\n data.loc[nn, semester + '_PC_MEAN'] = PC/3\n data.loc[nn, semester + '_SP_MEAN'] = SP/7\n data.loc[nn, semester + '_UD_MEAN'] = UD/5\n data.loc[nn, semester + '_ES_MEAN'] = ES/3\n\n #lacks number of questions for meaningful subscore\n #2 q\n data.loc[nn, semester + '_TR_MEAN'] = np.nan\n data.loc[nn, semester + '_TR_TOTAL'] = np.nan\n #1 q\n data.loc[nn, semester + '_AV_MEAN'] = np.nan\n data.loc[nn, semester + '_AV_TOTAL'] = np.nan\n\n\n\n data[semester + '_CF_TOTAL'] = np.nan\n data[semester + '_CF_TOTAL_CORR'] = np.nan\n data[semester + '_CF_TOTAL_INCORR'] = np.nan\n data[semester + '_CF_MEAN'] = np.nan\n data[semester + '_CF_MEAN_CORR'] = np.nan\n data[semester + '_CF_MEAN_INCORR'] = np.nan\n\n\n # Calculates confidence totals and means; adds to respective columns\n for u in range(h):\n qcf = {'15': 0, '12':0, '14':0, '26':0, '27':0, '23':0, '28':0, '19':0, '3':0, '16':0, '13':0, '31':0, '32':0, '29':0, '30':0, '5':0, '6':0, '7':0, '10':0, '11':0,'20':0, '21':0, '33':0, '34':0, '35':0}\n qc = {'15': 0, '12':0, '14':0, '26':0, '27':0, '23':0, '28':0, '19':0, '3':0, '16':0, '13':0, '31':0, '32':0, '29':0, '30':0, '5':0, '6':0, '7':0, '10':0, '11':0,'20':0, '21':0, '33':0, '34':0, '35':0}\n\n for q_num in qcf:\n try:\n qcf[q_num] = int(data.loc[u, question + str(q_num) + \"CF\"])\n\n qc[q_num] = int(data.loc[u, question + str(q_num) + '_SCORE'])\n except:\n pass\n\n medscore = 0\n corrscore = 0\n incorrscore = 0\n confcount = 0\n for item in qcf:\n medscore += qcf[item]\n\n if qcf[item] > 0:\n confcount +=1\n\n if qc[item] == 1:\n corrscore += qcf[item]\n else:\n incorrscore += qcf[item]\n #print(confcount)\n if (confcount == 0):\n confcount = 1\n # Student's score\n numcorr = data.loc[u, semester + '_TOTAL']\n\n # Calculate confidence scores\n if e == 30:\n data.loc[u, semester + '_CF_TOTAL'] = medscore\n data.loc[u, semester + '_CF_TOTAL_CORR'] = corrscore\n data.loc[u, semester + '_CF_TOTAL_INCORR'] = incorrscore\n data.loc[u, semester + '_CF_MEAN'] = medscore/confcount\n\n if numcorr != 0:\n data.loc[u, semester + '_CF_MEAN_CORR'] = corrscore/numcorr\n else:\n data.loc[u, semester + '_CF_MEAN_CORR'] = 0\n if numcorr != confcount:\n data.loc[u, semester + '_CF_MEAN_INCORR'] = incorrscore/(confcount-numcorr)\n else:\n data.loc[u, semester + '_CF_MEAN_INCORR'] = 0\n\n elif e == 22:\n data.loc[u, semester + '_CF_TOTAL'] = medscore\n data.loc[u, semester + '_CF_TOTAL_CORR'] = np.nan\n data.loc[u, semester + '_CF_TOTAL_INCORR'] = incorrscore\n data.loc[u, semester + '_CF_MEAN'] = medscore/confcount\n if numcorr != 0:\n data.loc[u, semester + '_CF_MEAN_CORR'] = corrscore/numcorr\n else:\n data.loc[u, semester + '_CF_MEAN_CORR'] = 0\n if numcorr != confcount:\n data.loc[u, semester + '_CF_MEAN_INCORR'] = incorrscore/(confcount-numcorr)\n else:\n data.loc[u, semester + '_CF_MEAN_INCORR'] = 0\n elif e == 28:\n data.loc[u, semester + '_CF_TOTAL'] = medscore\n data.loc[u, semester + '_CF_TOTAL_CORR'] = np.nan\n data.loc[u, semester + '_CF_TOTAL_INCORR'] = incorrscore\n data.loc[u, semester + '_CF_MEAN'] = medscore/confcount\n if numcorr != 0:\n data.loc[u, semester + '_CF_MEAN_CORR'] = corrscore/numcorr\n else:\n data.loc[u, semester + '_CF_MEAN_CORR'] = 0\n if numcorr != confcount:\n data.loc[u, semester + '_CF_MEAN_INCORR'] = incorrscore/(confcount-numcorr)\n else:\n data.loc[u, semester + '_CF_MEAN_INCORR'] = 0\n\n elif e == 50:\n data.loc[u, semester + '_CF_TOTAL'] = medscore\n data.loc[u, semester + '_CF_TOTAL_CORR'] = corrscore\n data.loc[u, semester + '_CF_TOTAL_INCORR'] = incorrscore\n data.loc[u, semester + '_CF_MEAN'] = medscore/confcount\n\n if numcorr != 0:\n data.loc[u, semester + '_CF_MEAN_CORR'] = corrscore/numcorr\n else:\n data.loc[u, semester + '_CF_MEAN_CORR'] = 0\n if numcorr != confcount:\n data.loc[u, semester + '_CF_MEAN_INCORR'] = incorrscore/(confcount-numcorr)\n else:\n data.loc[u, semester + '_CF_MEAN_INCORR'] = 0\n\n data[semester + '_QCOMPLETE'] = 0\n data[semester + '_COMPFLAG'] = 0\n data[semester +'_EFFFLAG'] = 0\n\n # Counts number of completed columns\n try:\n if e == 50:\n q = [15, 12, 14, 26, 27, 23, 28, 19, 3, 16, 13, 31, 32, 29, 30, 5, 6, 7, 10, 11, 20, 21, 33, 34, 35]\n elif e == 22:\n q = [15, 12, 13, 14, 26, 27, 23, 28, 19, 3, 16]\n elif e == 30:\n q = [15, 12, 13, 14, 26, 27, 23, 28, 19, 3, 16, 10, 11, 33, 34]\n elif e == 28:\n q = [6, 7, 13, 14, 16, 20, 21, 23, 27, 28, 29, 30, 31, 35]\n\n for v in range(h):\n # Count up totals\n total = 0\n for w in q:\n count = question + str(w)\n\n answered = data.loc[v, count]\n if (str(answered) == 'nan' or str(answered) == ' '):\n continue\n else:\n total = int(np.nansum([total, 1]))\n\n data.loc[v, semester + '_QCOMPLETE'] = total\n\n # Add completed flag\n if total == len(q):\n data.loc[v, semester + '_COMPFLAG'] = 1\n else:\n data.loc[v, semester + '_COMPFLAG'] = 0\n except:\n KeyError\n\n # Calculating effort column\n\n for v in range(h):\n # If there is no response for effort, mark completion as 0 for that student!\n if (pd.isnull(data.loc[v, semester + '_EFFORT'])):\n data.loc[v, semester + '_COMPFLAG'] = 0\n\n # If there is high effort, give full marks in flag\n if data.loc[v, semester + '_EFFORT'] == 4 or data.loc[v, semester + '_EFFORT'] == 5:\n data.loc[v, semester +'_EFFFLAG'] = 1\n\n # Some effort gives you only so many marks...\n elif data.loc[v, semester + '_EFFORT'] == 3:\n data.loc[v, semester +'_EFFFLAG'] = 0.5\n\n # NO EFFORT!! :-(\n elif data.loc[v, semester + '_EFFORT'] == 2 or data.loc[v, semester + '_EFFORT'] == 1:\n data.loc[v, semester +'_EFFFLAG'] = 0\n\n # Factor Analysis!\n if (semester == \"PRE\" and e == 30) or (semester == \"PRE\" and e == 22) or (semester == \"PRE\" and e == 28):\n # Fill out whymajs with 0 instead of NaN values so we can\n # perform FA on them\n nan_columns = [semester + \"_WHYMAJ_1\", semester + \"_WHYMAJ_2\", semester + \"_WHYMAJ_3\",\n semester + \"_WHYMAJ_4\", semester + \"_WHYMAJ_5\", semester + \"_WHYMAJ_6\",\n semester + \"_WHYMAJ_7\", semester + \"_WHYMAJ_8\", semester + \"_WHYCS_1\",\n semester + \"_WHYCS_2\", semester + \"_WHYCS_3\", semester + \"_WHYCS_4\",\n semester + \"_WHYCS_5\", semester + \"_WHYCS_6\", semester + \"_WHYCS_7\"\n ]\n for i in data.index:\n for column in nan_columns:\n if pd.isna(data.at[i, column]):\n data.at[i, column] = 0\n\n # Factor Analysis variables\n att = [semester + '_FREQEN', semester + '_DAILYM', semester + '_DAILYG',\n semester + '_ATT_DL_3', semester + '_ATT_SC_1', semester + '_ATT_SC_2',\n semester + '_ATT_SC_4', semester + '_ATT_SC_5', semester + '_LK1',\n semester + '_LK2', semester + '_LK5', semester + '_ANX#1_1',\n semester + '_ANX#1_2', semester + '_ANX#1_3', semester + '_ANX#1_4',\n semester + '_CF_TOTAL', semester + '_ATT_DL_2', semester + '_ATT_SC_3',\n semester + \"_WHYCS_1\", semester + \"_WHYCS_3\", semester + \"_WHYCS_5\",\n semester + \"_WHYCS_6\", semester + \"_EFFORT\"\n ]\n\n # Variable selection\n att_data = data.loc[ data[semester + '_COMPFLAG']==1 ]\n att_data = att_data[att]\n # Drop all rows with NaN values\n att_data.dropna(inplace=True)\n\n swapList = ['_ATT_DL_2', '_ATT_DL_3', '_ATT_SC_1', '_ATT_SC_2',\n '_ATT_SC_3', '_ATT_SC_4', '_ATT_SC_5'\n ]\n for i in att_data.index:\n for col in swapList:\n swapOrdering(att_data, i, semester + col)\n\n # KMO and Barlett tests\n X = att_data.copy().values\n X = check_array(X, force_all_finite='allow-nan')\n\n statistic, p_value = calculate_bartlett_sphericity(X)\n print(\"\\nBarlett sphericity p={0}\".format(p_value))\n kmo_per_variable, kmo_total = calculate_kmo(X)\n print(\"Kaiser-Meyer-Olkin measure of sampling adequacy = {0}\\n\".format(kmo_total))\n\n # Create factor analysis object and perform factor analysis\n # Using maximum likelihood analysis (ml)\n n_factors = 5\n fa = FactorAnalyzer(rotation=None, n_factors=n_factors, method=\"ml\")\n fa.fit(att_data)\n\n # Kaiser normalization and oblimin rotation\n rotator = Rotator(method=\"oblimin\", normalize=True, max_iter=25)\n loadings = rotator.fit_transform(fa.loadings_)\n\n # Set FA loadings to be rotator loadings\n fa.loadings_ = loadings\n\n # Get factor scores\n factor_scores = fa.transform(att_data)\n factor_scores = pd.DataFrame(data=factor_scores, index=att_data.index, columns=[\"Factor \"+str(i+1) for i in range(n_factors)])\n # print(\"\\nFactor scores: \\n\", factor_scores)\n\n factor_names = [\"Numerical Self Efficacy\", \"School Math\",\n \"Academic maturity\", \"Numerical Relevancy\", \"Math Anxiety\"]\n # Convert factor loadings to a df\n loadings = pd.DataFrame(data=loadings, index=att, columns=factor_names)\n\n # Drop non-meaningful values\n loadings = loadings.where(abs(loadings) > 0.32)\n print(\"Factor loadings: \\n\", loadings)\n\n scores1 = factor_scores['Factor 1'].tolist()\n plt.hist(scores1, bins=[x for x in np.arange(-4.0, 4.0, 0.2)])\n plt.title(\"Numerical Self Efficacy\")\n # plt.show()\n\n scores2 = factor_scores['Factor 2'].tolist()\n plt.hist(scores2, bins=[x for x in np.arange(-4.0, 4.0, 0.2)])\n plt.title(\"School Math\")\n # plt.show()\n\n scores3 = factor_scores['Factor 3'].tolist()\n plt.hist(scores3, bins=[x for x in np.arange(-4.0, 4.0, 0.2)])\n plt.title(\"Academic maturity\")\n # plt.show()\n\n scores4 = factor_scores['Factor 4'].tolist()\n plt.hist(scores4, bins=[x for x in np.arange(-4.0, 4.0, 0.2)])\n plt.title(\"Numerical Relevancy\")\n # plt.show()\n\n scores5 = factor_scores['Factor 5'].tolist()\n plt.hist(scores5, bins=[x for x in np.arange(-4.0, 4.0, 0.2)])\n plt.title(\"Math Anxiety\")\n # plt.show()\n\n # Update composite variables\n for i in factor_scores.index:\n data.at[i, semester + '_SELFEFF'] = factor_scores.at[i, 'Factor 1']\n data.at[i, semester + '_SCHMATH'] = factor_scores.at[i, 'Factor 2']\n data.at[i, semester + '_ACADMAT'] = factor_scores.at[i, 'Factor 3']\n data.at[i, semester + '_MATHREL'] = factor_scores.at[i, 'Factor 4']\n data.at[i, semester + '_MATHANX'] = factor_scores.at[i, 'Factor 5']\n\n #data.to_csv(semester+\"_scored.csv\", encoding='utf-8',index=False)\n\n #print(\"Results saved to \" + savedname + \"_scored.csv\")\n\n return data\n\ndef swapOrdering(db, index, colname):\n '''\n Swaps ordering of columns so that they're ordered negative -> positive\n Used in Factor Analysis\n '''\n check = int(db.at[index, colname])\n if check == 4:\n db.at[index, colname] = 1\n elif check == 3:\n db.at[index, colname] = 2\n elif check == 2:\n db.at[index, colname] = 3\n elif check == 1:\n db.at[index, colname] = 4\n" ]
[ [ "pandas.read_csv", "pandas.isnull", "numpy.unique", "matplotlib.pyplot.title", "sklearn.utils.check_array", "numpy.arange", "pandas.DataFrame", "numpy.nansum", "pandas.isna" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
andyreagan/dbdiff
[ "6fccc6cd7c88e1e91def7bfc89057b0c0fd73883" ]
[ "tests/test_dbdiff.py" ]
[ "import logging\nimport os\nfrom pathlib import Path\n\nimport pandas as pd\nimport pytest\nfrom click.testing import CliRunner\n\nfrom dbdiff.main import check_primary_key\nfrom dbdiff.main import create_diff_table\nfrom dbdiff.main import create_joined_table\nfrom dbdiff.main import get_column_diffs\nfrom dbdiff.main import get_diff_columns\nfrom dbdiff.main import get_diff_rows\nfrom dbdiff.main import get_unmatched_rows\nfrom dbdiff.main import get_unmatched_rows_straight\nfrom dbdiff.main import insert_diff_table\nfrom dbdiff.main import select_distinct_rows\nfrom dbdiff.cli import cli\nfrom dbdiff.vertica import get_column_info\nfrom dbdiff.vertica import get_column_info_lookup\nfrom dbdiff.vertica import get_cur\nfrom dbdiff.vertica import get_table_exists\n\nlogging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)\nVALID_COL = {'comparable': True, 'exclude': False}\nINT_DTYPES = {d: 'int' for d in {'x_dtype', 'y_dtype'}}\nVARCHAR_DTYPES = {d: 'varchar(10)' for d in {'x_dtype', 'y_dtype'}}\nDATE_DTYPES = {d: 'date' for d in {'x_dtype', 'y_dtype'}}\nCOMPARE_COLS = pd.DataFrame({'data1': {**INT_DTYPES, **VALID_COL},\n 'data2': {**INT_DTYPES, **VALID_COL},\n 'data3': {**DATE_DTYPES, **VALID_COL},\n 'data4': {**VARCHAR_DTYPES, **VALID_COL},}).transpose()\nJOIN_COLS = pd.DataFrame({'join1': {**VARCHAR_DTYPES, **VALID_COL},\n 'join2': {**VARCHAR_DTYPES, **VALID_COL}}).transpose()\n\n\[email protected](scope='session')\ndef cur():\n # vsql -d docker -u dbadmin\n # export VERTICA_HOST=\"localhost\"\n # export VERTICA_PORT=\"5433\"\n # export VERTICA_DATABASE=\"docker\"\n # export VERTICA_USERNAME=\"dbadmin\"\n # export VERTICA_PASSWORD=\"\"\n os.environ['VERTICA_HOST'] = 'localhost'\n os.environ['VERTICA_PORT'] = '5433'\n os.environ['VERTICA_DATABASE'] = 'VMart'\n os.environ['VERTICA_USERNAME'] = 'dbadmin'\n os.environ['VERTICA_PASSWORD'] = ''\n with get_cur() as c:\n yield c\n\n\ndef create_schema(cur):\n cur.execute('CREATE SCHEMA dbdiff;')\n\n\ndef create_x_table(cur):\n cur.execute('CREATE TABLE dbdiff.x_table ( join1 varchar(10), join2 varchar(10), missingx int, missingx2 int, dtypemiss int, data1 int, data2 int, data3 date, data4 varchar(10));')\n cur.execute(\"INSERT INTO dbdiff.x_table ( join1, join2, missingx, missingx2, dtypemiss, data1, data2, data3, data4) (select 'match1', 'matchdup21', 0, 0, 0, 0, 0, '2017-10-11', '');\")\n cur.execute(\"INSERT INTO dbdiff.x_table ( join1, join2, missingx, missingx2, dtypemiss, data1, data2, data3, data4) (select 'match1', 'match22', 0, 0, 0, 0, 0, '2017-10-11', 'a');\")\n cur.execute(\"INSERT INTO dbdiff.x_table ( join1, join2, missingx, missingx2, dtypemiss, data1, data2, data3, data4) (select 'match1', 'match23', 0, 0, 0, 1, 1, '2017-10-11', '');\")\n cur.execute(\"INSERT INTO dbdiff.x_table ( join1, join2, missingx, missingx2, dtypemiss, data1, data2, data3, data4) (select 'match1', 'missx21', null, null, null, null, null, null, '');\")\n cur.execute(\"INSERT INTO dbdiff.x_table ( join1, join2, missingx, missingx2, dtypemiss, data1, data2, data3, data4) (select 'match1', 'missx22', null, null, null, null, null, null, '');\")\n cur.execute(\"INSERT INTO dbdiff.x_table ( join1, join2, missingx, missingx2, dtypemiss, data1, data2, data3, data4) (select 'missx11', null, null, null, null, null, null, null, '');\")\n cur.execute(\"INSERT INTO dbdiff.x_table ( join1, join2, missingx, missingx2, dtypemiss, data1, data2, data3, data4) (select 'missx12', null, null, null, null, null, null, null, '');\")\n cur.execute(\"INSERT INTO dbdiff.x_table ( join1, join2, missingx, missingx2, dtypemiss, data1, data2, data3, data4) (select null, null, null, null, null, null, null, null, '');\")\n cur.execute('COMMIT;')\n\n\ndef create_y_table(cur, case_off: bool = False):\n cur.execute('CREATE TABLE dbdiff.y_table ( join1 varchar(10), join2 varchar(10), missingy int, dtypemiss date, data1 int, data2 int, data3 date, data4 varchar(10));')\n cur.execute(\"INSERT INTO dbdiff.y_table ( join1, join2, missingy, dtypemiss, data1, data2, data3, data4) (select 'match1', 'matchdup21', 0, '2019-04-22', 0, 0, '2017-10-11', '');\")\n cur.execute(\"INSERT INTO dbdiff.y_table ( join1, join2, missingy, dtypemiss, data1, data2, data3, data4) (select 'match1', 'matchdup21', 0, '2019-04-22', 0, 0, '2017-10-11', '');\")\n if case_off:\n # here, we'll uppercase the 'A' so that these don't match\n cur.execute(\"INSERT INTO dbdiff.y_table ( join1, join2, missingy, dtypemiss, data1, data2, data3, data4) (select 'match1', 'match22', 0, '2019-04-22', 0, 1, '2017-10-12', 'A');\")\n else:\n cur.execute(\"INSERT INTO dbdiff.y_table ( join1, join2, missingy, dtypemiss, data1, data2, data3, data4) (select 'match1', 'match22', 0, '2019-04-22', 0, 1, '2017-10-12', 'a');\")\n cur.execute(\"INSERT INTO dbdiff.y_table ( join1, join2, missingy, dtypemiss, data1, data2, data3, data4) (select 'match1', 'match23', 0, '2019-04-22', 0, 0, '2017-10-13', '');\")\n cur.execute(\"INSERT INTO dbdiff.y_table ( join1, join2, missingy, dtypemiss, data1, data2, data3, data4) (select 'match1', 'missy21', 0, '2019-04-22', 0, 0, null, '');\")\n cur.execute(\"INSERT INTO dbdiff.y_table ( join1, join2, missingy, dtypemiss, data1, data2, data3, data4) (select 'missy11', null, 0, '2019-04-22', 0, 0, null, '');\")\n cur.execute('COMMIT;')\n\n\ndef drop_schema(cur):\n cur.execute('DROP SCHEMA IF EXISTS dbdiff CASCADE;')\n\n\ndef test_drop_data_start(cur):\n drop_schema(cur)\n\n\ndef test_create_data(cur):\n create_schema(cur)\n create_x_table(cur)\n create_y_table(cur)\n\n\ndef test_get_column_info(cur):\n column_info = get_column_info(cur, 'dbdiff', 'x_table')\n assert type(column_info) == pd.DataFrame\n assert 'column_name' in column_info.columns\n assert 'data_type' in column_info.columns\n\n\ndef test_get_column_info_lookup(cur):\n column_info_lookup = get_column_info_lookup(cur, 'dbdiff', 'x_table')\n assert 'data1' in column_info_lookup\n assert column_info_lookup['join1'].lower() == 'varchar(10)'\n assert column_info_lookup['data1'] == 'int'\n assert column_info_lookup['data2'] == 'int'\n assert column_info_lookup['data3'] == 'date'\n assert len(column_info_lookup) == 9\n\n\ndef test_get_table_exists(cur):\n assert get_table_exists(cur, 'dbdiff', 'x_table')\n assert get_table_exists(cur, 'dbdiff', 'y_table')\n assert not get_table_exists(cur, 'dbdiff', 'z_table')\n\n\ndef test_check_primary_key(cur):\n assert (\n check_primary_key(\n cur,\n 'dbdiff',\n 'x_table',\n ['join1', 'join2']\n ) == 0\n )\n assert check_primary_key(cur, 'dbdiff', 'x_table', ['join1']) == 4\n\n\ndef test_select_distinct_rows(cur):\n x_table_rows = 8\n x_table_columns = 9\n for use_temp_tables in {True, False}:\n new_table_schema, new_table_name = select_distinct_rows(cur, 'dbdiff', 'x_table', ['join1'])\n # check that new table gets create with N rows\n assert get_table_exists(cur, new_table_schema, 'x_table_dup')\n assert get_table_exists(cur, new_table_schema, 'x_table_dedup')\n cur.execute('select * from {schema}.{table}'.format(\n schema=new_table_schema,\n table=new_table_name)\n )\n dedup = pd.DataFrame(cur.fetchall())\n assert dedup.shape[0] == 3\n assert dedup.shape[1] == x_table_columns\n cur.execute('select * from {schema}.{table}'.format(\n schema=new_table_schema,\n table='x_table_dup')\n )\n dup = pd.DataFrame(cur.fetchall())\n assert dup.shape[0] == (x_table_rows - dedup.shape[0])\n assert dup.shape[1] == (x_table_columns + 1)\n\n\ndef test_create_joined_table(cur):\n create_joined_table(\n cur,\n x_schema='dbdiff',\n y_schema='dbdiff',\n x_table='x_table',\n y_table='y_table',\n join_cols=['join1', 'join2'],\n compare_cols=pd.concat([COMPARE_COLS, JOIN_COLS]),\n joined_schema='dbdiff',\n joined_table='x_table_JOINED'\n )\n # check that it is created and has the right number of rows, columns...\n assert get_table_exists(cur, 'dbdiff', 'x_table_JOINED')\n cur.execute(\n 'select * from {schema}.{table}'.format(\n schema='dbdiff',\n table='x_table_JOINED'\n )\n )\n df = pd.DataFrame(cur.fetchall())\n assert df.shape[0] == 4\n # double the comparing columns (x_* and y_*), and pk/join columns:\n assert df.shape[1] == ((COMPARE_COLS.shape[0] * 2) + JOIN_COLS.shape[0])\n\n\ndef test_get_unmatched_rows_straight(cur):\n join_cols = ['join1', 'join2']\n # these are a bit flipped:\n # the missing_x_join are counts for rows in y that are missing in x\n # and the missing_y_join are counts for rows *in x* that are *not in y*\n # the name coming from the *not in y* part of it.\n y_minus_x = [2, 1] # formerly, \"missing_x_join\", now using set notation\n x_minus_y = [3, 2] # etc\n results = get_unmatched_rows_straight(\n cur,\n 'dbdiff',\n 'dbdiff',\n 'x_table',\n 'y_table',\n join_cols,\n 100\n )\n expected_results = {\n 'x': {\n 'count': sum(x_minus_y),\n 'sample_shape': (sum(x_minus_y), len(join_cols))\n },\n 'y': {\n 'count': sum(y_minus_x),\n 'sample_shape': (sum(y_minus_x), len(join_cols))\n }\n }\n print(results)\n print(expected_results)\n assert results['x']['count'] == expected_results['x']['count']\n assert results['x']['sample'].shape[0] == expected_results['x']['sample_shape'][0]\n assert results['x']['sample'].shape[1] == expected_results['x']['sample_shape'][1]\n assert results['y']['count'] == expected_results['y']['count']\n assert results['y']['sample'].shape[0] == expected_results['y']['sample_shape'][0]\n assert results['y']['sample'].shape[1] == expected_results['y']['sample_shape'][1]\n\n\ndef test_get_unmatched_rows(cur):\n join_cols = ['join1', 'join2']\n # these are, again, a litte wierd. see note in test_get_unmatched_rows_straight()\n y_minus_x = [2, 1]\n x_minus_y = [3, 2]\n results = get_unmatched_rows(\n cur,\n 'dbdiff',\n 'dbdiff',\n 'x_table',\n 'y_table',\n join_cols,\n 100\n )\n expected_results = {\n j: {\n side: {\n 'count': d[i],\n 'sample_shape': (d[i], i + 1)\n } for side, d in {\n 'x': x_minus_y,\n 'y': y_minus_x\n }.items()\n } for i, j in enumerate(join_cols)\n }\n for col, expected in expected_results.items():\n logging.info(col)\n for side, expected_info in expected.items():\n logging.info(side)\n logging.info(results[col][side]['count'])\n logging.info(results[col][side]['sample'])\n assert 'sample' in results[col][side]\n assert 'query' in results[col][side]\n assert results[col][side]['count'] == expected_info['count']\n for i in {0, 1}:\n assert results[col][side]['sample'].shape[i] == expected_info['sample_shape'][i]\n if col == 'join2':\n assert 'sample_grouped' in results[col][side]\n assert 'query_grouped' in results[col][side]\n\n\ndef test_create_diff_table(cur):\n create_diff_table(cur, 'dbdiff', 'x_table_DIFF', ['join1', 'join2'],\n pd.concat([COMPARE_COLS, JOIN_COLS]))\n assert get_table_exists(cur, 'dbdiff', 'x_table_DIFF')\n\n\ndef test_insert_diff_table(cur):\n cur.execute('select * from dbdiff.x_table_JOINED')\n logging.info(cur.fetchall())\n cur.execute('select * from dbdiff.x_table_DIFF')\n logging.info(cur.fetchall())\n insert_diff_table(\n cur,\n joined_schema='dbdiff',\n joined_table='x_table_JOINED',\n diff_schema='dbdiff',\n diff_table='x_table_DIFF',\n join_cols=['join1', 'join2'],\n column='data1'\n )\n cur.execute('select * from {schema}.{table}'.format(schema='dbdiff', table='x_table_DIFF'))\n df = pd.DataFrame(cur.fetchall())\n assert df.shape[0] == 1\n assert df.shape[1] == 3\n insert_diff_table(\n cur,\n joined_schema='dbdiff',\n joined_table='x_table_JOINED',\n diff_schema='dbdiff',\n diff_table='x_table_DIFF',\n join_cols=['join1', 'join2'],\n column='data2'\n )\n cur.execute('select * from {schema}.{table}'.format(schema='dbdiff', table='x_table_DIFF'))\n df = pd.DataFrame(cur.fetchall())\n assert df.shape[0] == 3\n assert df.shape[1] == 3\n\n\n# def test_implicit_dytpe_comparison():\n# implicit_dytpe_comparison(x_dtype, y_dtype)\n\n\ndef test_get_diff_rows(cur):\n diff_summary = get_diff_rows(\n cur,\n 'dbdiff',\n 'x_table',\n ['join1', 'join2'],\n 100\n )\n assert diff_summary['count'] == 2\n assert diff_summary['total_count'] == 3\n assert diff_summary['sample'].shape[0] == 2\n # assert diff_summary['sample'].shape[1] == 10\n\n\ndef test_get_diff_columns(cur):\n df = get_diff_columns(cur, 'dbdiff', 'x_table')\n assert df.shape[0] == 2\n assert df.shape[1] == 2\n\n\ndef test_get_column_diffs(cur):\n join_cols = ['join1', 'join2']\n diff_columns = get_diff_columns(cur, 'dbdiff', 'x_table')\n\n grouped_column_diffs = get_column_diffs(\n diff_columns, cur,\n 'dbdiff',\n 'dbdiff',\n 'x_table',\n 'dbdiff',\n 'y_table',\n ['join1', 'join2'],\n 100,\n COMPARE_COLS,\n True\n )\n logging.info(grouped_column_diffs)\n\n data1_misses = 1\n data2_misses = 2\n\n expected = {'data1': {'count': data1_misses, 'df_shape': (data1_misses, 3),\n 'df_raw_shape': (data1_misses, 2 + len(join_cols)),\n 'df_h_x_shape': (5, 1 + len(join_cols)),\n 'df_h_y_shape': (5, 1 + len(join_cols))},\n 'data2': {'count': data2_misses, 'df_shape': (data2_misses, 3),\n 'df_raw_shape': (data2_misses, 2 + len(join_cols)),\n 'df_h_x_shape': (5, 1 + len(join_cols)),\n 'df_h_y_shape': (5, 1 + len(join_cols))}}\n\n for column_name in expected.keys():\n grouped_column_diffs[column_name]\n logging.info(grouped_column_diffs[column_name])\n assert expected[column_name]['count'] == grouped_column_diffs[column_name]['count']\n for q_name in {'q', 'q_raw', 'q_h_x', 'q_h_y'}:\n assert q_name in grouped_column_diffs[column_name]\n for i in {0, 1}:\n assert expected[column_name]['df_shape'][i] == grouped_column_diffs[column_name]['df'].shape[i]\n assert expected[column_name]['df_raw_shape'][i] == grouped_column_diffs[column_name]['df_raw'].shape[i]\n assert expected[column_name]['df_h_x_shape'][i] == grouped_column_diffs[column_name]['df_h_x'].shape[i]\n assert expected[column_name]['df_h_y_shape'][i] == grouped_column_diffs[column_name]['df_h_y'].shape[i]\n\n\ndef test_drop_data_end(cur):\n drop_schema(cur)\n\n\ndef test_main(cur):\n create_schema(cur)\n create_x_table(cur)\n create_y_table(cur)\n\n base_options = ['dbdiff', 'x_table', 'y_table', 'join1,join2']\n runner = CliRunner()\n\n def runner_wrapper(runner, base_options, addl_options):\n result = runner.invoke(\n cli,\n base_options + addl_options,\n catch_exceptions=False\n )\n # if result.exit_code != 0:\n # print(result.output)\n # logging.info(str(result.exception) + str(result.exc_info))\n assert result.exit_code == 0\n\n runner_wrapper(runner, base_options, [])\n # save the report:\n # Path('x_table_report.html').rename('base_report.html')\n # clear the output\n drop_schema(cur)\n create_schema(cur)\n create_x_table(cur)\n create_y_table(cur)\n\n runner_wrapper(runner, base_options, ['--drop-output-tables'])\n runner_wrapper(runner, base_options, ['--drop-output-tables', '--output-format=XLSX'])\n runner_wrapper(runner, base_options, ['--hierarchical-join'])\n runner_wrapper(runner, base_options, ['--drop-output-tables'])\n runner_wrapper(runner, base_options, ['--drop-output-tables', '--output-format=XLSX'])\n runner_wrapper(runner, base_options, ['--use-diff-table'])\n runner_wrapper(runner, base_options, ['--hierarchical-join', '--use-diff-table'])\n\n Path('x_table_report.html').unlink()\n Path('x_table_report.xlsx').unlink()\n\n Path('x_table_temp.sql').write_text('select * from dbdiff.x_table')\n x_table_temp_options = ['dbdiff', 'x_table_temp.sql', 'y_table', 'join1,join2', '--x-table-query']\n runner_wrapper(runner, x_table_temp_options, ['--drop-output-tables'])\n runner_wrapper(runner, x_table_temp_options, ['--drop-output-tables', '--output-format=XLSX'])\n runner_wrapper(runner, x_table_temp_options, ['--hierarchical-join'])\n\n Path('y_table_temp.sql').write_text('select * from dbdiff.y_table')\n both_table_temp_options = ['dbdiff', 'x_table_temp.sql', 'y_table_temp.sql', 'join1,join2', '--x-table-query', '--y-table-query']\n runner_wrapper(runner, both_table_temp_options, ['--drop-output-tables'])\n runner_wrapper(runner, both_table_temp_options, ['--drop-output-tables', '--output-format=XLSX'])\n runner_wrapper(runner, both_table_temp_options, ['--hierarchical-join'])\n runner_wrapper(runner, both_table_temp_options, ['--save-column-summary'])\n runner_wrapper(runner, both_table_temp_options, ['--save-column-summary', '--save-column-summary-format=pickle'])\n\n\n Path('x_table_temp.sql').unlink()\n Path('y_table_temp.sql').unlink()\n Path('x_table_temp_report.html').unlink()\n Path('x_table_temp_report.xlsx').unlink()\n Path('x_table_temp_col_info.csv').unlink()\n Path('x_table_temp_col_info.pkl').unlink()\n\n # clear the output\n drop_schema(cur)\n create_schema(cur)\n create_x_table(cur)\n create_y_table(cur, case_off=True)\n\n runner_wrapper(runner, base_options, [])\n # Path('x_table_report.html').rename('case_on.html')\n runner_wrapper(runner, base_options, ['--case-insensitive'])\n # Path('x_table_report.html').rename('case_off.html')\n runner_wrapper(runner, base_options, ['--save-json-summary'])\n runner_wrapper(runner, base_options, ['--hierarchical-join', '--save-json-summary'])\n\n Path('x_table_report.html').unlink()\n Path('x_table_diff_summary.json').unlink()\n" ]
[ [ "pandas.concat", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
jessemin/D3BayesNet
[ "75788750a43053fc8fa6965623a1958f6a6f082a" ]
[ "app/bayesian.py" ]
[ "import sys\nimport networkx as nx\nimport numpy as np\nfrom math import lgamma\n\n\ndef write_gph(dag, idx2names, filename):\n with open(filename, 'w') as f:\n for edge in dag.edges():\n f.write(\"{}, {}\\n\".format(idx2names[edge[0]], idx2names[edge[1]]))\n\n\ndef get_idx2names(line):\n idx2names = {}\n names = line.split(\",\")\n for index, name in enumerate(names):\n idx2names[index] = name\n return idx2names\n\n\ndef compute_bayesian_score(dag, n, r, D):\n bayesian_score = 0.0\n for i in range(n):\n bayesian_score += compute_bayesian_score_for_node(dag, n, r, i, D)\n return bayesian_score\n\n\ndef run_k2(dag, n, r, D, number_of_parents):\n # random ordering\n ordering = np.random.permutation(range(n))\n for index in range(n):\n old_score = compute_bayesian_score(dag, n, r, D)\n i = ordering[index]\n for j_index in range(index+1, n):\n j = ordering[j_index]\n if len(list(dag.predecessors(i))) <= number_of_parents:\n dag.add_edge(j, i)\n new_score = compute_bayesian_score(dag, n, r, D)\n if len(list(nx.simple_cycles(dag))) == 0:\n if new_score > old_score:\n old_score = new_score\n else:\n dag.remove_edge(j, i)\n else:\n dag.remove_edge(j, i)\n return dag\n\n\ndef initialize(infile, outfile):\n dag = nx.DiGraph()\n bayesian_score = 0.0\n n = 0\n r = {}\n is_first_line, is_first_data = True, True\n D = None\n idx2names = None\n with open(infile) as f:\n for raw_line in f:\n line = raw_line.strip()\n # fetch the idx2names dictionary\n if is_first_line:\n idx2names = get_idx2names(line)\n n = len(idx2names.keys())\n dag.add_nodes_from([node for node in range(n)])\n for i in range(n):\n r[i] = 0\n is_first_line = False\n continue\n values = [int(value) for value in line.split(\",\")]\n # read and parse data into numpy matrix D\n if is_first_data:\n D = np.array([values])\n is_first_data = False\n else:\n D = np.append(D, [values], axis=0)\n # update each r_i with max value in each column\n for i in range(n):\n r[i] = np.max(D, axis=0)[i]\n return dag, n, r, D, idx2names\n\n\ndef compute_bayesian_score_for_node(dag, n, r, i, D):\n bayesian_score_for_node = 0.0\n # dictionary table for m_ij0 and m_ijk respectively\n m_ij0_table, m_ijk_table = {}, {}\n # fetch the relevant data columns from the dataset\n # special case: when node i has no parent\n if len(list(dag.predecessors(i))) == 0:\n node_i = D[:, i]\n for row in node_i:\n m_i1k = (row)\n if m_i1k not in m_ijk_table.keys():\n m_ijk_table[m_i1k] = 1\n else:\n m_ijk_table[m_i1k] += 1\n bayesian_score_for_node += (lgamma(r[i]) - lgamma(r[i] + D.shape[0]))\n for m_i1k in m_ijk_table.values():\n bayesian_score_for_node += lgamma(m_i1k+1)\n return bayesian_score_for_node\n # normal case: when node i has at least one parent\n node_i_and_parents = D[:, [i]+list(dag.predecessors(i))]\n for row in node_i_and_parents:\n # update the count for m_ij0 and m_ijk based on the current row\n m_ij0, m_ijk = tuple(row[1:]), tuple(row)\n if m_ij0 not in m_ij0_table.keys():\n m_ij0_table[m_ij0] = 1\n else:\n m_ij0_table[m_ij0] += 1\n if m_ijk not in m_ijk_table.keys():\n m_ijk_table[m_ijk] = 1\n else:\n m_ijk_table[m_ijk] += 1\n left_term, right_term = 0.0, 0.0\n for m_ijk in m_ijk_table.values():\n right_term += lgamma(m_ijk+1)\n for m_ij0 in m_ij0_table.values():\n left_term += (lgamma(r[i]) - lgamma(r[i]+m_ij0))\n bayesian_score_for_node = left_term + right_term\n return bayesian_score_for_node\n" ]
[ [ "numpy.max", "numpy.append", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
co2palm/antivirus_demo
[ "015b2b91042fede067b1d34043a19fe87fb53c4b" ]
[ "demo.py" ]
[ "import numpy as np\nimport pandas as pd\nimport pickle\nimport sklearn.ensemble as ske\nfrom sklearn import cross_validation, tree, linear_model\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.externals import joblib\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import confusion_matrix\n\ndata = pd.read_csv('MalwareData.csv', sep = '|')\nX = data.drop(['Name', 'md5', 'legitimate'], axis=1).values\nY = data['legitimate'].values\n\nprint('Researching important feature based on %i total features\\n' % X.shape[1])\n\nfsel = ske.ExtraTreesClassifier().fit(X, Y)\nmodel = SelectFromModel(fsel, prefit=True)\nX_new = model.transform(X)\nnb_features = X_new.shape[1]\nX_train, X_test, Y_train, Y_test = cross_validation.train_test_split(X_new, Y, test_size=0.2)\n\nfeatures = []\n\nprint('%i features identifed as important :' % nb_features)\n\nindices = np.argsort(fsel.feature_importances_)[::-1][:nb_features]\n\nfor f in range(nb_features):\n print(\"%d. feature %s (%f)\" % (f + 1, data.columns[2+indices[f]], fsel.feature_importances_[indices[f]]))\n\nalgorithms = {\n \"DecisionTree\": tree.DecisionTreeClassifier(max_depth=10),\n \"RandomForest\": ske.RandomForestClassifier(n_estimators=50),\n \"GradientBoosting\": ske.GradientBoostingClassifier(n_estimators=50),\n \"AdaBoost\": ske.AdaBoostClassifier(n_estimators=100),\n \"GNB\": GaussianNB()\n}\n\nresults = {}\nprint(\"\\nNow testing algorithms\")\nfor algo in algorithms:\n clf = algorithms[algo]\n clf.fit(X_train, Y_train)\n score = clf.score(X_test, Y_test)\n print(\"%s : %f %%\" % (algo, score*100))\n results[algo] = score\n\nwinner = max(results, key = results.get)\nprint('\\nWinner algorithm is %s with a %f %% success' % (winner, results[winner]*100))\n\nprint('Saving algorithm and feature list in classifier directory...')\njoblib.dump(algorithms[winner], 'classifier/claasifier.pkl')\nopen('classifier/features.pkl' 'w').write(pickle.dumps(features))\nprint('Saved')\n\nclf = algorithms[winner]\n\nres = clf.predict(X_test)\nmt = confusion_matrix(Y_test, res)\nprint(\"False positive rate : %f %%\" % ((mt[0][1] / float(sum(mt[0])))*100))\nprint('False negative rate : %f %%' % ((mt[1][0] / float(sum(mt[1]))*100)))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description = 'Detect malicious file from manalyzer infos')\n\nparser.add_argument('URL', help = 'Manalyzer url')\n\nargs = parser.parse_args()\n\nclf = joblib.load(os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n 'classifier/classifier.pkl'\n))\nfeatures = pickle.loads(open(os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n 'classifier/features.pkl'),\n 'r').read()\n)\n" ]
[ [ "sklearn.externals.joblib.dump", "sklearn.cross_validation.train_test_split", "pandas.read_csv", "sklearn.naive_bayes.GaussianNB", "sklearn.ensemble.RandomForestClassifier", "sklearn.ensemble.ExtraTreesClassifier", "sklearn.metrics.confusion_matrix", "sklearn.tree.DecisionTreeClassifier", "sklearn.ensemble.AdaBoostClassifier", "sklearn.ensemble.GradientBoostingClassifier", "numpy.argsort", "sklearn.feature_selection.SelectFromModel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
gregversteeg/esh_dynamics
[ "c0811e62306c0cdff659abf5fa9b884ec6b556df" ]
[ "generate_figures/plot_valley.py" ]
[ "\"\"\"Produce a plot for the paper, comparing ESH MC steps to Langevin dynamics.\"\"\"\nimport numpy as np\nimport torch as t\nfrom esh import samplers, datasets\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.style.use('seaborn-paper')\nsns.set_context(\"paper\", font_scale=1.5, rc={\"lines.linewidth\": 2.5})\n\n\nif __name__ == '__main__':\n # Seed for reproducibility\n scenario = 1 # 0 for deep well 1 for valley\n name = ['deepwell', 'valley'][scenario]\n print('scenario: {}'.format(name))\n seed = 0\n t.manual_seed(seed)\n n_steps = [5, 50][scenario] # 5 or 50\n\n m = datasets.GaussianTest(2)\n m.energy.weight.data[0, 0] = [100,1][scenario] # 1 for valley, 100 for deep well\n m.energy.weight.data[1, 1] = 100. \n f = m.energy\n r, n_x, alpha = 3, 100, 0.7\n xv, yv = np.meshgrid(np.linspace(-r, r, n_x), np.linspace(-r, r, n_x))\n x_grid = np.array([xv, yv]).reshape((2, n_x * n_x)).T\n with t.no_grad():\n energy = f(t.tensor(x_grid, dtype=t.float32)).cpu().numpy()\n\n e_history_grid = energy.reshape((n_x, n_x))\n xs_grid = x_grid[:, 0].reshape((n_x, n_x))\n ys_grid = x_grid[:, 1].reshape((n_x, n_x))\n p_grid = np.exp(-e_history_grid) / np.sum(np.exp(-e_history_grid))\n grid = [-4. + 0.1 + i + np.log(p_grid.max()) for i in range(5)]\n\n xs, vs, ts = samplers.hmc_integrate(f, t.tensor([4., -0.4]), n_steps, epsilon=0.1, k=1, mh_reject=False)\n nxs, nvs = samplers.newton_dynamics(f, t.tensor([4., 0.4]), n_steps, epsilon=0.1)\n exs, evs, ets = samplers.leap_integrate(f, t.tensor([-4., 0.4]), n_steps, epsilon=0.1)\n\n # import IPython; IPython.embed()\n # %matplotlib\n fig, ax = plt.subplots(1,1)\n ax.contourf(xs_grid, ys_grid, np.log(p_grid), grid,\n # np.exp([-10, -5, -2.5, -1.25, -0.5, -0.1, 0.2, 0.9, 1.5]),\n cmap=\"OrRd\", zorder=0, alpha=alpha)\n ax.axis('off')\n ax.plot(xs[:, 0], xs[:, 1], label='Langevin dynamics', color='tab:orange')\n ax.text(1., -0.7, 'Langevin dynamics', color='tab:orange')\n ax.plot(nxs[:, 0], nxs[:, 1], label='Newtonian Hamiltonian dynamics', color='tab:green', alpha=0.5)\n ax.text(1., 0.7, 'Newtonian dynamics', color='tab:green')\n ax.plot(exs[:, 0], exs[:, 1], label='ESH dynamics', color='tab:blue')\n ax.text(-4, 0.7, 'ESH dynamics', color='tab:blue')\n fig.savefig('figs/{}.pdf'.format(name), bbox_inches='tight')\n" ]
[ [ "numpy.log", "numpy.linspace", "torch.manual_seed", "matplotlib.pyplot.subplots", "torch.tensor", "torch.no_grad", "numpy.array", "numpy.exp", "matplotlib.pyplot.style.use" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]