repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list | possible_versions
list |
---|---|---|---|---|---|
WangChen0902/FRSKD-Paddle
|
[
"d7e8313be6f7785e64a35623074271288d6c57aa"
] |
[
"segmentation/utils/efficientdet.py"
] |
[
"from efficientnet_pytorch import EfficientNet\nimport torch.nn as nn\nimport torch\nimport torch.nn.functional as F\nfrom .BiFPN import BiFPNSeg\n\n\nclass EfficientDet(nn.Module):\n def __init__(self, backbone=\"efficientnet-b0\"):\n super(EfficientDet, self).__init__()\n model = EfficientNet.from_pretrained(backbone)\n\n self.layer0 = nn.Sequential(model._conv_stem, model._bn0)\n if backbone == \"efficientnet-b0\":\n self.layer1 = nn.Sequential(model._blocks[0],model._blocks[1])\n self.layer2 = nn.Sequential(model._blocks[2],model._blocks[3])\n self.layer3 = nn.Sequential(model._blocks[4],model._blocks[5])\n self.layer4 = nn.Sequential(model._blocks[6],model._blocks[7],model._blocks[8],model._blocks[9],model._blocks[10],model._blocks[11])\n self.layer5 = nn.Sequential(model._blocks[12],model._blocks[13],model._blocks[14],model._blocks[15])\n else:\n self.layer1 = nn.Sequential(model._blocks[0],model._blocks[1],model._blocks[2])\n self.layer2 = nn.Sequential(model._blocks[3],model._blocks[4],model._blocks[5])\n self.layer3 = nn.Sequential(model._blocks[6],model._blocks[7],model._blocks[8])\n self.layer4 = nn.Sequential(model._blocks[9],model._blocks[10],model._blocks[11])\n self.layer5 = nn.Sequential(model._blocks[12],model._blocks[13],model._blocks[14],model._blocks[15]\n ,model._blocks[16],model._blocks[17],model._blocks[18],model._blocks[19]\n ,model._blocks[20],model._blocks[21],model._blocks[22])\n \n outc_candi = {\"efficientnet-b0\":64, \"efficientnet-b1\": 88, \"efficientnet-b2\": 112}\n outc = outc_candi[backbone]\n\n # Bottom-up layers\n\n self.conv6 = self.Conv( self.layer5[-1]._project_conv.weight.size()[0], outc, kernel_size=3, stride=2, padding=1)\n self.conv7 = self.Conv(outc, outc, kernel_size=3, stride=2, padding=1)\n # Top layer\n self.toplayer = self.Conv(self.layer5[-1]._project_conv.weight.size()[0], outc, kernel_size=1, stride=1, padding=0) # Reduce channels\n # Smooth layers\n self.smooth1 = self.Conv(outc, outc, kernel_size=3, stride=1, padding=1)\n self.smooth2 = self.Conv(outc, outc, kernel_size=3, stride=1, padding=1) \n # Lateral layers\n self.latlayer1 = self.Conv(self.layer3[-1]._project_conv.weight.size()[0], outc, kernel_size=1, stride=1, padding=0)\n self.latlayer2 = self.Conv(self.layer2[-1]._project_conv.weight.size()[0], outc, kernel_size=1, stride=1, padding=0)\n # loc, conf layers\n self.latlayer3 = self.Conv(self.layer1[-1]._project_conv.weight.size()[0], outc, kernel_size=1, stride=1, padding=0)\n self.BiFPN1 = nn.Sequential(BiFPNSeg(outc), BiFPNSeg(outc), BiFPNSeg(outc))\n self.BiFPN2 = nn.Sequential(BiFPNSeg(outc), BiFPNSeg(outc, True))\n\n self.classifier1 = nn.Sequential(nn.Conv2d(outc, 256, kernel_size=3, padding=1),\n nn.BatchNorm2d(256, eps=1e-4, momentum=0.997),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 21, kernel_size=3, padding=1))\n self.classifier2 = nn.Sequential(nn.Conv2d(outc, 256, kernel_size=3, padding=1),\n nn.BatchNorm2d(256, eps=1e-4, momentum=0.997),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 21, kernel_size=3, padding=1))\n\n def forward(self, x):\n _, _, H, W = x.size()\n x = self.layer0(x)\n p2 = self.layer1(x)\n p3 = self.layer2(p2)\n p4 = self.layer3(p3)\n p5 = self.layer4(p4)\n p5 = self.layer5(p5)\n\n p6 = self.conv6(p5)\n p7 = self.conv7(p6)\n\n p5 = self.toplayer(p5)\n p4 = self._upsample_add(p5, self.latlayer1(p4))\n p3 = self._upsample_add(p4, self.latlayer2(p3))\n p2 = self._upsample_add(p3, self.latlayer3(p2))\n sources = [p2, p3, p4, p5, p6, p7]\n\n sources1 = self.BiFPN1(sources)\n sources2 = self.BiFPN2(sources1)\n\n output1 = self.classifier1(sources1[0])\n output2 = self.classifier2(sources2[0])\n\n output1 = F.upsample(output1, size=(H, W), mode='bilinear')\n output2 = F.upsample(output2, size=(H, W), mode='bilinear')\n return output1, output2, sources1, sources2\n\n @staticmethod\n def Conv(in_channels, out_channels, kernel_size, stride, padding, groups=1):\n features = nn.Sequential(\n nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups),\n nn.BatchNorm2d(num_features=out_channels, eps=1e-4, momentum=0.997),\n nn.ReLU(inplace=True)\n )\n return features \n \n def _upsample_add(self, x, y):\n '''Upsample and add two feature maps.\n Args:\n x: (Variable) top feature map to be upsampled.\n y: (Variable) lateral feature map.\n Returns:\n (Variable) added feature map.\n Note in PyTorch, when input size is odd, the upsampled feature map\n with `F.upsample(..., scale_factor=2, mode='nearest')`\n maybe not equal to the lateral feature map size.\n e.g.\n original input size: [N,_,15,15] ->\n conv2d feature map size: [N,_,8,8] ->\n upsampled feature map size: [N,_,16,16]\n So we choose bilinear upsample which supports arbitrary output sizes.\n '''\n _,_,H,W = y.size()\n return F.upsample(x, size=(H,W), mode='bilinear') + y\n"
] |
[
[
"torch.nn.functional.upsample",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lw0517/transferlearning
|
[
"17583db86db19709ff483a24590f0d5b88e25fe5"
] |
[
"code/traditional/SFA.py"
] |
[
"import sys\nimport math\nimport numpy as np\nimport scipy.io as sio\nimport scipy.sparse as sp\nfrom scipy.sparse.linalg import svds as SVD\nfrom sklearn import svm\nfrom sklearn.metrics import accuracy_score\n\n\nclass SFA:\n '''\n spectrual feature alignment\n '''\n\n def __init__(self, l=500, K=100, base_classifer=svm.SVC()):\n self.l = l\n self.K = K\n self.m = 0\n self.ut = None\n self.phi = 1\n self.base_classifer = base_classifer\n self.ix = None\n self._ix = None\n return\n\n def fit(self, Xs, Xt):\n\n ix_s = np.argsort(np.sum(Xs, axis=0))\n ix_t = np.argsort(np.sum(Xt, axis=0))\n\n ix_s = ix_s[::-1][:self.l]\n ix_t = ix_t[::-1][:self.l]\n ix = np.intersect1d(ix_s, ix_t)\n _ix = np.setdiff1d(range(Xs.shape[1]), ix)\n self.ix = ix\n self._ix = _ix\n self.m = len(_ix)\n self.l = len(ix)\n\n X = np.concatenate((Xs, Xt), axis=0)\n DI = (X[:, ix] > 0).astype('float')\n DS = (X[:, _ix] > 0).astype('float')\n\n # construct co-occurrence matrix DSxDI\n M = np.zeros((self.m, self.l))\n for i in range(X.shape[0]):\n tem1 = np.reshape(DS[i], (1, self.m))\n tem2 = np.reshape(DI[i], (1, self.l))\n M += np.matmul(tem1.T, tem2)\n M = M/np.linalg.norm(M, 'fro')\n # #construct A matrix\n # tem_1 = np.zeros((self.m, self.m))\n # tem_2 = np.zeros((self.l, self.l))\n # A1 = np.concatenate((tem_1, M.T), axis=0)\n # A2 = np.concatenate((M, tem_2), axis=0)\n # A = np.concatenate((A1, A2), axis=1)\n # # compute laplace\n # D = np.zeros((A.shape[0], A.shape[1]))\n # for i in range(self.l+self.m):\n # \tD[i,i] = 1.0/np.sqrt(np.sum(A[i,:]))\n # L = (D.dot(A)).dot(D)\n # ut, _, _ = np.linalg.svd(L)\n M = sp.lil_matrix(M)\n D1 = sp.lil_matrix((self.m, self.m))\n D2 = sp.lil_matrix((self.l, self.l))\n for i in range(self.m):\n D1[i, i] = 1.0/np.sqrt(np.sum(M[1, :]).data[0])\n for i in range(self.l):\n D2[i, i] = 1.0/np.sqrt(np.sum(M[:, i]).T.data[0])\n B = (D1.tocsr().dot(M.tocsr())).dot(D2.tocsr())\n # print(\"Done.\")\n # print(\"Computing SVD...\")\n ut, s, vt = SVD(B.tocsc(), k=self.K)\n self.ut = ut\n return ut\n\n def transform(self, X):\n return np.concatenate((X, X[:, self._ix].dot(self.ut)), axis=1)\n\n def fit_predict(self, Xs, Xt, X_test, Ys, Y_test):\n ut = self.fit(Xs, Xt)\n Xs = self.transform(Xs)\n self.base_classifer.fit(Xs, Ys)\n X_test = self.transform(X_test)\n y_pred = self.base_classifer.predict(X_test)\n acc = accuracy_score(Y_test, y_pred)\n return acc\n"
] |
[
[
"numpy.reshape",
"sklearn.metrics.accuracy_score",
"numpy.matmul",
"numpy.linalg.norm",
"numpy.concatenate",
"numpy.intersect1d",
"sklearn.svm.SVC",
"numpy.zeros",
"numpy.sum",
"scipy.sparse.lil_matrix"
]
] |
[
{
"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": []
}
] |
Jayanth-kumar5566/CAMEB2-machine-learning
|
[
"36678cb55f15b75094fa097963ad4661a21b92d8"
] |
[
"pipeline_wilcoxon.py"
] |
[
"#!/usr/bin/env python3\n\n# Single pipeline to run all the analysis\nimport sys\nimport os\nimport pandas\nfrom joblib import Parallel, delayed\n\nargs=sys.argv\n\n'''\nRun as:\n\t./pipeline_wilcoxon.py dataset alpha dimension_reduction ml_algo param_dimred param_ml\n\ndataset:\n\tI - clinical attributes\n\tII - Microbiome (from Kaiju)\n\tIII - Microbial pathways (Unipathways)\n\tIV - Anti Microbial resistance (HUMMAN2)\n\tV - Bacteriophages contigs (Virome)\n\n\tCan also include I+II (or such combinations)\t\n\t\nalpha: alpha value \n\t0.1 (90%) or 0.05 (95%) used for Wilcoxon test - Feature selection\n\t\ndimension_reduction\t: \"none\", \"pca\", \"VAE\", \"rp\"\nml_algo \t\t\t: \"logit\", \"rf\" \nparam_dimred\t\t: parameters for dimension reduction algorthim seperated by ,\n\t\"none\"\t- none\n\t\"pca\"\t- ratio(explanined variance to preserve)\t\n\t\"rp\"\t- epsilon value\n\t\"vae\"\t- dimensions 80,20\nparam_ml\t\t\t: parameters for ML algorithm\n\t\"none\"\t- none [all built in] #just incase\n'''\n#Dataset\n\n#parse dataset code\ndataset_code=args[1].split(\"+\")\n\n#Feature selection with Wilcoxon\ndef dataset(number,args):\n\tif number==\"I\":\n\t\tos.system(\"python3 Codes_pipeline/pre-process_clinical.py\")\n\t\tos.system(\"./Codes_pipeline/fet_sel_clinical.R /home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Datasets/\"+number+\".csv /home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Feature_Selection/\"+number+\".csv \"+args[2])\n\t\treturn(None)\n\telif number==\"II\":\n\t\tos.system(\"python3 Codes_pipeline/pre-process.py\")\n\t\tos.system(\"./Codes_pipeline/fet_sel.R /home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Datasets/\"+number+\".csv /home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Feature_Selection/\"+number+\".csv \"+args[2])\n\t\treturn(None)\n\telif number==\"III\":\n\t\tos.system(\"python3 Codes_pipeline/pre-process_pathways.py\")\t\n\t\tos.system(\"./Codes_pipeline/fet_sel.R /home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Datasets/\"+number+\".csv /home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Feature_Selection/\"+number+\".csv \"+args[2])\n\t\treturn(None)\n\telif number==\"IV\":\n\t\tos.system(\"python3 Codes_pipeline/pre-process_amr.py\")\n\t\tos.system(\"./Codes_pipeline/fet_sel.R /home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Datasets/\"+number+\".csv /home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Feature_Selection/\"+number+\".csv \"+args[2])\t\n\t\treturn(None)\n\telif number==\"V\":\n\t\tos.system(\"python3 Codes_pipeline/pre-process_phage.py\")\n\t\tos.system(\"./Codes_pipeline/fet_sel.R /home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Datasets/\"+number+\".csv /home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Feature_Selection/\"+number+\".csv \"+args[2])\t\t\n\t\treturn(None)\n\telse:\n\t\tsys.exit(\"Please check your input\")\n\t\t\n#Execute Part 1 of the pipeline - dataset processing and feature selection\nParallel(n_jobs=16)(delayed(dataset)(i,args) for i in dataset_code) #Run in parallel \n\n#=============Part 2=========================\n\ndef import_fsel_data(number):\n df=pandas.read_csv(\"/home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Feature_Selection/\"+number+\".csv\",index_col=0)\n return(df)\n\t\ndatasets=[import_fsel_data(i) for i in dataset_code]\n\n#concatenate all the datafames in the list\ndata = pandas.concat([df.stack() for df in datasets], axis=0).unstack()\ndata.to_csv(\"/home/jayanth/OneDrive/21.ML_Bronch/Data/CAMEB2-machine-learning/Results/Feature_Selection/final_data.csv\")\n\n#=============Part 3============================\n#Machine Learning part\nos.system(\"sudo docker exec ed514c558732 /home/CAMEB2-machine-learning/Codes_pipeline/machine_learning.py /home/CAMEB2-machine-learning/Results/Feature_Selection/final_data.csv /home/METADATA/data_194.csv /home/METADATA/data_test.csv \"+args[3]+\" \"+args[4]+\" \"+args[5]+\" \"+args[6]+\" /home/CAMEB2-machine-learning/Results/Machine_Learning/ >> ./Results/out_res\"+str(args[1])+\".txt\")\n\n"
] |
[
[
"pandas.read_csv"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
deepang17/pandas
|
[
"bf31347a1e82ac5e17b4d515b07e16aae738e60b"
] |
[
"pandas/core/tools/datetimes.py"
] |
[
"from __future__ import annotations\n\nfrom collections import abc\nfrom datetime import datetime\nfrom functools import partial\nfrom itertools import islice\nfrom typing import (\n TYPE_CHECKING,\n Callable,\n Hashable,\n List,\n Optional,\n Tuple,\n TypeVar,\n Union,\n overload,\n)\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs import tslib\nfrom pandas._libs.tslibs import (\n OutOfBoundsDatetime,\n Timedelta,\n Timestamp,\n conversion,\n iNaT,\n nat_strings,\n parsing,\n)\nfrom pandas._libs.tslibs.parsing import ( # noqa\n DateParseError,\n format_is_iso,\n guess_datetime_format,\n)\nfrom pandas._libs.tslibs.strptime import array_strptime\nfrom pandas._typing import (\n AnyArrayLike,\n ArrayLike,\n Timezone,\n)\n\nfrom pandas.core.dtypes.common import (\n ensure_object,\n is_datetime64_dtype,\n is_datetime64_ns_dtype,\n is_datetime64tz_dtype,\n is_float,\n is_integer,\n is_integer_dtype,\n is_list_like,\n is_numeric_dtype,\n is_scalar,\n)\nfrom pandas.core.dtypes.generic import (\n ABCDataFrame,\n ABCSeries,\n)\nfrom pandas.core.dtypes.missing import notna\n\nfrom pandas.arrays import (\n DatetimeArray,\n IntegerArray,\n)\nfrom pandas.core import algorithms\nfrom pandas.core.algorithms import unique\nfrom pandas.core.arrays.datetimes import (\n maybe_convert_dtype,\n objects_to_datetime64ns,\n tz_to_dtype,\n)\nfrom pandas.core.indexes.base import Index\nfrom pandas.core.indexes.datetimes import DatetimeIndex\n\nif TYPE_CHECKING:\n from pandas._libs.tslibs.nattype import NaTType\n\n from pandas import Series\n\n# ---------------------------------------------------------------------\n# types used in annotations\n\nArrayConvertible = Union[List, Tuple, AnyArrayLike, \"Series\"]\nScalar = Union[int, float, str]\nDatetimeScalar = TypeVar(\"DatetimeScalar\", Scalar, datetime)\nDatetimeScalarOrArrayConvertible = Union[DatetimeScalar, ArrayConvertible]\n\n\n# ---------------------------------------------------------------------\n\n\ndef _guess_datetime_format_for_array(arr, **kwargs):\n # Try to guess the format based on the first non-NaN element\n non_nan_elements = notna(arr).nonzero()[0]\n if len(non_nan_elements):\n return guess_datetime_format(arr[non_nan_elements[0]], **kwargs)\n\n\ndef should_cache(\n arg: ArrayConvertible, unique_share: float = 0.7, check_count: Optional[int] = None\n) -> bool:\n \"\"\"\n Decides whether to do caching.\n\n If the percent of unique elements among `check_count` elements less\n than `unique_share * 100` then we can do caching.\n\n Parameters\n ----------\n arg: listlike, tuple, 1-d array, Series\n unique_share: float, default=0.7, optional\n 0 < unique_share < 1\n check_count: int, optional\n 0 <= check_count <= len(arg)\n\n Returns\n -------\n do_caching: bool\n\n Notes\n -----\n By default for a sequence of less than 50 items in size, we don't do\n caching; for the number of elements less than 5000, we take ten percent of\n all elements to check for a uniqueness share; if the sequence size is more\n than 5000, then we check only the first 500 elements.\n All constants were chosen empirically by.\n \"\"\"\n do_caching = True\n\n # default realization\n if check_count is None:\n # in this case, the gain from caching is negligible\n if len(arg) <= 50:\n return False\n\n if len(arg) <= 5000:\n check_count = len(arg) // 10\n else:\n check_count = 500\n else:\n assert (\n 0 <= check_count <= len(arg)\n ), \"check_count must be in next bounds: [0; len(arg)]\"\n if check_count == 0:\n return False\n\n assert 0 < unique_share < 1, \"unique_share must be in next bounds: (0; 1)\"\n\n unique_elements = set(islice(arg, check_count))\n if len(unique_elements) > check_count * unique_share:\n do_caching = False\n return do_caching\n\n\ndef _maybe_cache(\n arg: ArrayConvertible,\n format: Optional[str],\n cache: bool,\n convert_listlike: Callable,\n) -> Series:\n \"\"\"\n Create a cache of unique dates from an array of dates\n\n Parameters\n ----------\n arg : listlike, tuple, 1-d array, Series\n format : string\n Strftime format to parse time\n cache : boolean\n True attempts to create a cache of converted values\n convert_listlike : function\n Conversion function to apply on dates\n\n Returns\n -------\n cache_array : Series\n Cache of converted, unique dates. Can be empty\n \"\"\"\n from pandas import Series\n\n cache_array = Series(dtype=object)\n\n if cache:\n # Perform a quicker unique check\n if not should_cache(arg):\n return cache_array\n\n unique_dates = unique(arg)\n if len(unique_dates) < len(arg):\n cache_dates = convert_listlike(unique_dates, format)\n cache_array = Series(cache_dates, index=unique_dates)\n return cache_array\n\n\ndef _box_as_indexlike(\n dt_array: ArrayLike, utc: Optional[bool] = None, name: Hashable = None\n) -> Index:\n \"\"\"\n Properly boxes the ndarray of datetimes to DatetimeIndex\n if it is possible or to generic Index instead\n\n Parameters\n ----------\n dt_array: 1-d array\n Array of datetimes to be wrapped in an Index.\n tz : object\n None or 'utc'\n name : string, default None\n Name for a resulting index\n\n Returns\n -------\n result : datetime of converted dates\n - DatetimeIndex if convertible to sole datetime64 type\n - general Index otherwise\n \"\"\"\n\n if is_datetime64_dtype(dt_array):\n tz = \"utc\" if utc else None\n return DatetimeIndex(dt_array, tz=tz, name=name)\n return Index(dt_array, name=name)\n\n\ndef _convert_and_box_cache(\n arg: DatetimeScalarOrArrayConvertible,\n cache_array: Series,\n name: Optional[str] = None,\n) -> Index:\n \"\"\"\n Convert array of dates with a cache and wrap the result in an Index.\n\n Parameters\n ----------\n arg : integer, float, string, datetime, list, tuple, 1-d array, Series\n cache_array : Series\n Cache of converted, unique dates\n name : string, default None\n Name for a DatetimeIndex\n\n Returns\n -------\n result : Index-like of converted dates\n \"\"\"\n from pandas import Series\n\n result = Series(arg).map(cache_array)\n # error: Value of type variable \"ArrayLike\" of \"_box_as_indexlike\" cannot\n # be \"Series\"\n return _box_as_indexlike(result, utc=None, name=name) # type: ignore[type-var]\n\n\ndef _return_parsed_timezone_results(result: np.ndarray, timezones, tz, name) -> Index:\n \"\"\"\n Return results from array_strptime if a %z or %Z directive was passed.\n\n Parameters\n ----------\n result : ndarray[int64]\n int64 date representations of the dates\n timezones : ndarray\n pytz timezone objects\n tz : object\n None or pytz timezone object\n name : string, default None\n Name for a DatetimeIndex\n\n Returns\n -------\n tz_result : Index-like of parsed dates with timezone\n \"\"\"\n tz_results = np.array(\n [Timestamp(res).tz_localize(zone) for res, zone in zip(result, timezones)]\n )\n if tz is not None:\n # Convert to the same tz\n tz_results = np.array([tz_result.tz_convert(tz) for tz_result in tz_results])\n\n return Index(tz_results, name=name)\n\n\ndef _convert_listlike_datetimes(\n arg,\n format: Optional[str],\n name: Hashable = None,\n tz: Optional[Timezone] = None,\n unit: Optional[str] = None,\n errors: Optional[str] = None,\n infer_datetime_format: bool = False,\n dayfirst: Optional[bool] = None,\n yearfirst: Optional[bool] = None,\n exact: bool = True,\n):\n \"\"\"\n Helper function for to_datetime. Performs the conversions of 1D listlike\n of dates\n\n Parameters\n ----------\n arg : list, tuple, ndarray, Series, Index\n date to be parsed\n name : object\n None or string for the Index name\n tz : object\n None or 'utc'\n unit : string\n None or string of the frequency of the passed data\n errors : string\n error handing behaviors from to_datetime, 'raise', 'coerce', 'ignore'\n infer_datetime_format : bool, default False\n inferring format behavior from to_datetime\n dayfirst : boolean\n dayfirst parsing behavior from to_datetime\n yearfirst : boolean\n yearfirst parsing behavior from to_datetime\n exact : bool, default True\n exact format matching behavior from to_datetime\n\n Returns\n -------\n Index-like of parsed dates\n \"\"\"\n\n if isinstance(arg, (list, tuple)):\n arg = np.array(arg, dtype=\"O\")\n\n arg_dtype = getattr(arg, \"dtype\", None)\n # these are shortcutable\n if is_datetime64tz_dtype(arg_dtype):\n if not isinstance(arg, (DatetimeArray, DatetimeIndex)):\n return DatetimeIndex(arg, tz=tz, name=name)\n if tz == \"utc\":\n arg = arg.tz_convert(None).tz_localize(tz)\n return arg\n\n elif is_datetime64_ns_dtype(arg_dtype):\n if not isinstance(arg, (DatetimeArray, DatetimeIndex)):\n try:\n return DatetimeIndex(arg, tz=tz, name=name)\n except ValueError:\n pass\n elif tz:\n # DatetimeArray, DatetimeIndex\n return arg.tz_localize(tz)\n\n return arg\n\n elif unit is not None:\n if format is not None:\n raise ValueError(\"cannot specify both format and unit\")\n return _to_datetime_with_unit(arg, unit, name, tz, errors)\n elif getattr(arg, \"ndim\", 1) > 1:\n raise TypeError(\n \"arg must be a string, datetime, list, tuple, 1-d array, or Series\"\n )\n\n # warn if passing timedelta64, raise for PeriodDtype\n # NB: this must come after unit transformation\n orig_arg = arg\n try:\n arg, _ = maybe_convert_dtype(arg, copy=False)\n except TypeError:\n if errors == \"coerce\":\n result = np.array([\"NaT\"], dtype=\"datetime64[ns]\").repeat(len(arg))\n return DatetimeIndex(result, name=name)\n elif errors == \"ignore\":\n # error: Incompatible types in assignment (expression has type\n # \"Index\", variable has type \"ExtensionArray\")\n result = Index(arg, name=name) # type: ignore[assignment]\n return result\n raise\n\n arg = ensure_object(arg)\n require_iso8601 = False\n\n if infer_datetime_format and format is None:\n format = _guess_datetime_format_for_array(arg, dayfirst=dayfirst)\n\n if format is not None:\n # There is a special fast-path for iso8601 formatted\n # datetime strings, so in those cases don't use the inferred\n # format because this path makes process slower in this\n # special case\n format_is_iso8601 = format_is_iso(format)\n if format_is_iso8601:\n require_iso8601 = not infer_datetime_format\n format = None\n\n # error: Incompatible types in assignment (expression has type \"None\", variable has\n # type \"ExtensionArray\")\n result = None # type: ignore[assignment]\n\n if format is not None:\n # error: Incompatible types in assignment (expression has type\n # \"Optional[Index]\", variable has type \"ndarray\")\n result = _to_datetime_with_format( # type: ignore[assignment]\n arg, orig_arg, name, tz, format, exact, errors, infer_datetime_format\n )\n if result is not None:\n return result\n\n if result is None:\n assert format is None or infer_datetime_format\n utc = tz == \"utc\"\n result, tz_parsed = objects_to_datetime64ns(\n arg,\n dayfirst=dayfirst,\n yearfirst=yearfirst,\n utc=utc,\n errors=errors,\n require_iso8601=require_iso8601,\n allow_object=True,\n )\n\n if tz_parsed is not None:\n # We can take a shortcut since the datetime64 numpy array\n # is in UTC\n dta = DatetimeArray(result, dtype=tz_to_dtype(tz_parsed))\n return DatetimeIndex._simple_new(dta, name=name)\n\n utc = tz == \"utc\"\n return _box_as_indexlike(result, utc=utc, name=name)\n\n\ndef _array_strptime_with_fallback(\n arg,\n name,\n tz,\n fmt: str,\n exact: bool,\n errors: Optional[str],\n infer_datetime_format: bool,\n) -> Optional[Index]:\n \"\"\"\n Call array_strptime, with fallback behavior depending on 'errors'.\n \"\"\"\n utc = tz == \"utc\"\n\n try:\n result, timezones = array_strptime(arg, fmt, exact=exact, errors=errors)\n if \"%Z\" in fmt or \"%z\" in fmt:\n return _return_parsed_timezone_results(result, timezones, tz, name)\n except OutOfBoundsDatetime:\n if errors == \"raise\":\n raise\n elif errors == \"coerce\":\n result = np.empty(arg.shape, dtype=\"M8[ns]\")\n iresult = result.view(\"i8\")\n iresult.fill(iNaT)\n else:\n result = arg\n except ValueError:\n # if fmt was inferred, try falling back\n # to array_to_datetime - terminate here\n # for specified formats\n if not infer_datetime_format:\n if errors == \"raise\":\n raise\n elif errors == \"coerce\":\n result = np.empty(arg.shape, dtype=\"M8[ns]\")\n iresult = result.view(\"i8\")\n iresult.fill(iNaT)\n else:\n result = arg\n else:\n # Indicates to the caller to fallback to objects_to_datetime64ns\n return None\n\n return _box_as_indexlike(result, utc=utc, name=name)\n\n\ndef _to_datetime_with_format(\n arg,\n orig_arg,\n name,\n tz,\n fmt: str,\n exact: bool,\n errors: Optional[str],\n infer_datetime_format: bool,\n) -> Optional[Index]:\n \"\"\"\n Try parsing with the given format, returning None on failure.\n \"\"\"\n result = None\n try:\n # shortcut formatting here\n if fmt == \"%Y%m%d\":\n # pass orig_arg as float-dtype may have been converted to\n # datetime64[ns]\n orig_arg = ensure_object(orig_arg)\n try:\n # may return None without raising\n result = _attempt_YYYYMMDD(orig_arg, errors=errors)\n except (ValueError, TypeError, OutOfBoundsDatetime) as err:\n raise ValueError(\n \"cannot convert the input to '%Y%m%d' date format\"\n ) from err\n if result is not None:\n utc = tz == \"utc\"\n return _box_as_indexlike(result, utc=utc, name=name)\n\n # fallback\n if result is None:\n # error: Incompatible types in assignment (expression has type\n # \"Optional[Index]\", variable has type \"Optional[ndarray]\")\n result = _array_strptime_with_fallback( # type: ignore[assignment]\n arg, name, tz, fmt, exact, errors, infer_datetime_format\n )\n if result is not None:\n return result\n\n except ValueError as e:\n # Fallback to try to convert datetime objects if timezone-aware\n # datetime objects are found without passing `utc=True`\n try:\n values, tz = conversion.datetime_to_datetime64(arg)\n dta = DatetimeArray(values, dtype=tz_to_dtype(tz))\n return DatetimeIndex._simple_new(dta, name=name)\n except (ValueError, TypeError):\n raise e\n\n # error: Incompatible return value type (got \"Optional[ndarray]\", expected\n # \"Optional[Index]\")\n return result # type: ignore[return-value]\n\n\ndef _to_datetime_with_unit(arg, unit, name, tz, errors: Optional[str]) -> Index:\n \"\"\"\n to_datetime specalized to the case where a 'unit' is passed.\n \"\"\"\n arg = getattr(arg, \"_values\", arg)\n\n # GH#30050 pass an ndarray to tslib.array_with_unit_to_datetime\n # because it expects an ndarray argument\n if isinstance(arg, IntegerArray):\n result = arg.astype(f\"datetime64[{unit}]\")\n tz_parsed = None\n else:\n result, tz_parsed = tslib.array_with_unit_to_datetime(arg, unit, errors=errors)\n\n if errors == \"ignore\":\n # Index constructor _may_ infer to DatetimeIndex\n\n # error: Incompatible types in assignment (expression has type \"Index\", variable\n # has type \"ExtensionArray\")\n result = Index(result, name=name) # type: ignore[assignment]\n else:\n # error: Incompatible types in assignment (expression has type \"DatetimeIndex\",\n # variable has type \"ExtensionArray\")\n result = DatetimeIndex(result, name=name) # type: ignore[assignment]\n\n if not isinstance(result, DatetimeIndex):\n # error: Incompatible return value type (got \"ExtensionArray\", expected \"Index\")\n return result # type: ignore[return-value]\n\n # GH#23758: We may still need to localize the result with tz\n # GH#25546: Apply tz_parsed first (from arg), then tz (from caller)\n # result will be naive but in UTC\n result = result.tz_localize(\"UTC\").tz_convert(tz_parsed)\n\n if tz is not None:\n if result.tz is None:\n result = result.tz_localize(tz)\n else:\n result = result.tz_convert(tz)\n return result\n\n\ndef _adjust_to_origin(arg, origin, unit):\n \"\"\"\n Helper function for to_datetime.\n Adjust input argument to the specified origin\n\n Parameters\n ----------\n arg : list, tuple, ndarray, Series, Index\n date to be adjusted\n origin : 'julian' or Timestamp\n origin offset for the arg\n unit : string\n passed unit from to_datetime, must be 'D'\n\n Returns\n -------\n ndarray or scalar of adjusted date(s)\n \"\"\"\n if origin == \"julian\":\n original = arg\n j0 = Timestamp(0).to_julian_date()\n if unit != \"D\":\n raise ValueError(\"unit must be 'D' for origin='julian'\")\n try:\n arg = arg - j0\n except TypeError as err:\n raise ValueError(\n \"incompatible 'arg' type for given 'origin'='julian'\"\n ) from err\n\n # preemptively check this for a nice range\n j_max = Timestamp.max.to_julian_date() - j0\n j_min = Timestamp.min.to_julian_date() - j0\n if np.any(arg > j_max) or np.any(arg < j_min):\n raise OutOfBoundsDatetime(\n f\"{original} is Out of Bounds for origin='julian'\"\n )\n else:\n # arg must be numeric\n if not (\n (is_scalar(arg) and (is_integer(arg) or is_float(arg)))\n or is_numeric_dtype(np.asarray(arg))\n ):\n raise ValueError(\n f\"'{arg}' is not compatible with origin='{origin}'; \"\n \"it must be numeric with a unit specified\"\n )\n\n # we are going to offset back to unix / epoch time\n try:\n offset = Timestamp(origin)\n except OutOfBoundsDatetime as err:\n raise OutOfBoundsDatetime(f\"origin {origin} is Out of Bounds\") from err\n except ValueError as err:\n raise ValueError(\n f\"origin {origin} cannot be converted to a Timestamp\"\n ) from err\n\n if offset.tz is not None:\n raise ValueError(f\"origin offset {offset} must be tz-naive\")\n offset -= Timestamp(0)\n\n # convert the offset to the unit of the arg\n # this should be lossless in terms of precision\n offset = offset // Timedelta(1, unit=unit)\n\n # scalars & ndarray-like can handle the addition\n if is_list_like(arg) and not isinstance(arg, (ABCSeries, Index, np.ndarray)):\n arg = np.asarray(arg)\n arg = arg + offset\n return arg\n\n\n@overload\ndef to_datetime(\n arg: DatetimeScalar,\n errors: str = ...,\n dayfirst: bool = ...,\n yearfirst: bool = ...,\n utc: Optional[bool] = ...,\n format: Optional[str] = ...,\n exact: bool = ...,\n unit: Optional[str] = ...,\n infer_datetime_format: bool = ...,\n origin=...,\n cache: bool = ...,\n) -> Union[DatetimeScalar, NaTType]:\n ...\n\n\n@overload\ndef to_datetime(\n arg: Series,\n errors: str = ...,\n dayfirst: bool = ...,\n yearfirst: bool = ...,\n utc: Optional[bool] = ...,\n format: Optional[str] = ...,\n exact: bool = ...,\n unit: Optional[str] = ...,\n infer_datetime_format: bool = ...,\n origin=...,\n cache: bool = ...,\n) -> Series:\n ...\n\n\n@overload\ndef to_datetime(\n arg: Union[List, Tuple],\n errors: str = ...,\n dayfirst: bool = ...,\n yearfirst: bool = ...,\n utc: Optional[bool] = ...,\n format: Optional[str] = ...,\n exact: bool = ...,\n unit: Optional[str] = ...,\n infer_datetime_format: bool = ...,\n origin=...,\n cache: bool = ...,\n) -> DatetimeIndex:\n ...\n\n\ndef to_datetime(\n arg: DatetimeScalarOrArrayConvertible,\n errors: str = \"raise\",\n dayfirst: bool = False,\n yearfirst: bool = False,\n utc: Optional[bool] = None,\n format: Optional[str] = None,\n exact: bool = True,\n unit: Optional[str] = None,\n infer_datetime_format: bool = False,\n origin=\"unix\",\n cache: bool = True,\n) -> Union[DatetimeIndex, Series, DatetimeScalar, NaTType]:\n \"\"\"\n Convert argument to datetime.\n\n Parameters\n ----------\n arg : int, float, str, datetime, list, tuple, 1-d array, Series, DataFrame/dict-like\n The object to convert to a datetime.\n errors : {'ignore', 'raise', 'coerce'}, default 'raise'\n - If 'raise', then invalid parsing will raise an exception.\n - If 'coerce', then invalid parsing will be set as NaT.\n - If 'ignore', then invalid parsing will return the input.\n dayfirst : bool, default False\n Specify a date parse order if `arg` is str or its list-likes.\n If True, parses dates with the day first, eg 10/11/12 is parsed as\n 2012-11-10.\n Warning: dayfirst=True is not strict, but will prefer to parse\n with day first (this is a known bug, based on dateutil behavior).\n yearfirst : bool, default False\n Specify a date parse order if `arg` is str or its list-likes.\n\n - If True parses dates with the year first, eg 10/11/12 is parsed as\n 2010-11-12.\n - If both dayfirst and yearfirst are True, yearfirst is preceded (same\n as dateutil).\n\n Warning: yearfirst=True is not strict, but will prefer to parse\n with year first (this is a known bug, based on dateutil behavior).\n utc : bool, default None\n Return UTC DatetimeIndex if True (converting any tz-aware\n datetime.datetime objects as well).\n format : str, default None\n The strftime to parse time, eg \"%d/%m/%Y\", note that \"%f\" will parse\n all the way up to nanoseconds.\n See strftime documentation for more information on choices:\n https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior.\n exact : bool, True by default\n Behaves as:\n - If True, require an exact format match.\n - If False, allow the format to match anywhere in the target string.\n\n unit : str, default 'ns'\n The unit of the arg (D,s,ms,us,ns) denote the unit, which is an\n integer or float number. This will be based off the origin.\n Example, with unit='ms' and origin='unix' (the default), this\n would calculate the number of milliseconds to the unix epoch start.\n infer_datetime_format : bool, default False\n If True and no `format` is given, attempt to infer the format of the\n datetime strings based on the first non-NaN element,\n and if it can be inferred, switch to a faster method of parsing them.\n In some cases this can increase the parsing speed by ~5-10x.\n origin : scalar, default 'unix'\n Define the reference date. The numeric values would be parsed as number\n of units (defined by `unit`) since this reference date.\n\n - If 'unix' (or POSIX) time; origin is set to 1970-01-01.\n - If 'julian', unit must be 'D', and origin is set to beginning of\n Julian Calendar. Julian day number 0 is assigned to the day starting\n at noon on January 1, 4713 BC.\n - If Timestamp convertible, origin is set to Timestamp identified by\n origin.\n cache : bool, default True\n If True, use a cache of unique, converted dates to apply the datetime\n conversion. May produce significant speed-up when parsing duplicate\n date strings, especially ones with timezone offsets. The cache is only\n used when there are at least 50 values. The presence of out-of-bounds\n values will render the cache unusable and may slow down parsing.\n\n .. versionchanged:: 0.25.0\n - changed default value from False to True.\n\n Returns\n -------\n datetime\n If parsing succeeded.\n Return type depends on input:\n\n - list-like: DatetimeIndex\n - Series: Series of datetime64 dtype\n - scalar: Timestamp\n\n In case when it is not possible to return designated types (e.g. when\n any element of input is before Timestamp.min or after Timestamp.max)\n return will have datetime.datetime type (or corresponding\n array/Series).\n\n See Also\n --------\n DataFrame.astype : Cast argument to a specified dtype.\n to_timedelta : Convert argument to timedelta.\n convert_dtypes : Convert dtypes.\n\n Examples\n --------\n Assembling a datetime from multiple columns of a DataFrame. The keys can be\n common abbreviations like ['year', 'month', 'day', 'minute', 'second',\n 'ms', 'us', 'ns']) or plurals of the same\n\n >>> df = pd.DataFrame({'year': [2015, 2016],\n ... 'month': [2, 3],\n ... 'day': [4, 5]})\n >>> pd.to_datetime(df)\n 0 2015-02-04\n 1 2016-03-05\n dtype: datetime64[ns]\n\n If a date does not meet the `timestamp limitations\n <https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html\n #timeseries-timestamp-limits>`_, passing errors='ignore'\n will return the original input instead of raising any exception.\n\n Passing errors='coerce' will force an out-of-bounds date to NaT,\n in addition to forcing non-dates (or non-parseable dates) to NaT.\n\n >>> pd.to_datetime('13000101', format='%Y%m%d', errors='ignore')\n datetime.datetime(1300, 1, 1, 0, 0)\n >>> pd.to_datetime('13000101', format='%Y%m%d', errors='coerce')\n NaT\n\n Passing infer_datetime_format=True can often-times speedup a parsing\n if its not an ISO8601 format exactly, but in a regular format.\n\n >>> s = pd.Series(['3/11/2000', '3/12/2000', '3/13/2000'] * 1000)\n >>> s.head()\n 0 3/11/2000\n 1 3/12/2000\n 2 3/13/2000\n 3 3/11/2000\n 4 3/12/2000\n dtype: object\n\n >>> %timeit pd.to_datetime(s, infer_datetime_format=True) # doctest: +SKIP\n 100 loops, best of 3: 10.4 ms per loop\n\n >>> %timeit pd.to_datetime(s, infer_datetime_format=False) # doctest: +SKIP\n 1 loop, best of 3: 471 ms per loop\n\n Using a unix epoch time\n\n >>> pd.to_datetime(1490195805, unit='s')\n Timestamp('2017-03-22 15:16:45')\n >>> pd.to_datetime(1490195805433502912, unit='ns')\n Timestamp('2017-03-22 15:16:45.433502912')\n\n .. warning:: For float arg, precision rounding might happen. To prevent\n unexpected behavior use a fixed-width exact type.\n\n Using a non-unix epoch origin\n\n >>> pd.to_datetime([1, 2, 3], unit='D',\n ... origin=pd.Timestamp('1960-01-01'))\n DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'], \\\ndtype='datetime64[ns]', freq=None)\n \"\"\"\n if arg is None:\n return None\n\n if origin != \"unix\":\n arg = _adjust_to_origin(arg, origin, unit)\n\n tz = \"utc\" if utc else None\n convert_listlike = partial(\n _convert_listlike_datetimes,\n tz=tz,\n unit=unit,\n dayfirst=dayfirst,\n yearfirst=yearfirst,\n errors=errors,\n exact=exact,\n infer_datetime_format=infer_datetime_format,\n )\n\n if isinstance(arg, Timestamp):\n result = arg\n if tz is not None:\n if arg.tz is not None:\n result = result.tz_convert(tz)\n else:\n result = result.tz_localize(tz)\n elif isinstance(arg, ABCSeries):\n cache_array = _maybe_cache(arg, format, cache, convert_listlike)\n if not cache_array.empty:\n result = arg.map(cache_array)\n else:\n values = convert_listlike(arg._values, format)\n result = arg._constructor(values, index=arg.index, name=arg.name)\n elif isinstance(arg, (ABCDataFrame, abc.MutableMapping)):\n result = _assemble_from_unit_mappings(arg, errors, tz)\n elif isinstance(arg, Index):\n cache_array = _maybe_cache(arg, format, cache, convert_listlike)\n if not cache_array.empty:\n result = _convert_and_box_cache(arg, cache_array, name=arg.name)\n else:\n result = convert_listlike(arg, format, name=arg.name)\n elif is_list_like(arg):\n try:\n cache_array = _maybe_cache(arg, format, cache, convert_listlike)\n except OutOfBoundsDatetime:\n # caching attempts to create a DatetimeIndex, which may raise\n # an OOB. If that's the desired behavior, then just reraise...\n if errors == \"raise\":\n raise\n # ... otherwise, continue without the cache.\n from pandas import Series\n\n cache_array = Series([], dtype=object) # just an empty array\n if not cache_array.empty:\n result = _convert_and_box_cache(arg, cache_array)\n else:\n result = convert_listlike(arg, format)\n else:\n result = convert_listlike(np.array([arg]), format)[0]\n\n return result\n\n\n# mappings for assembling units\n_unit_map = {\n \"year\": \"year\",\n \"years\": \"year\",\n \"month\": \"month\",\n \"months\": \"month\",\n \"day\": \"day\",\n \"days\": \"day\",\n \"hour\": \"h\",\n \"hours\": \"h\",\n \"minute\": \"m\",\n \"minutes\": \"m\",\n \"second\": \"s\",\n \"seconds\": \"s\",\n \"ms\": \"ms\",\n \"millisecond\": \"ms\",\n \"milliseconds\": \"ms\",\n \"us\": \"us\",\n \"microsecond\": \"us\",\n \"microseconds\": \"us\",\n \"ns\": \"ns\",\n \"nanosecond\": \"ns\",\n \"nanoseconds\": \"ns\",\n}\n\n\ndef _assemble_from_unit_mappings(arg, errors, tz):\n \"\"\"\n assemble the unit specified fields from the arg (DataFrame)\n Return a Series for actual parsing\n\n Parameters\n ----------\n arg : DataFrame\n errors : {'ignore', 'raise', 'coerce'}, default 'raise'\n\n - If 'raise', then invalid parsing will raise an exception\n - If 'coerce', then invalid parsing will be set as NaT\n - If 'ignore', then invalid parsing will return the input\n tz : None or 'utc'\n\n Returns\n -------\n Series\n \"\"\"\n from pandas import (\n DataFrame,\n to_numeric,\n to_timedelta,\n )\n\n arg = DataFrame(arg)\n if not arg.columns.is_unique:\n raise ValueError(\"cannot assemble with duplicate keys\")\n\n # replace passed unit with _unit_map\n def f(value):\n if value in _unit_map:\n return _unit_map[value]\n\n # m is case significant\n if value.lower() in _unit_map:\n return _unit_map[value.lower()]\n\n return value\n\n unit = {k: f(k) for k in arg.keys()}\n unit_rev = {v: k for k, v in unit.items()}\n\n # we require at least Ymd\n required = [\"year\", \"month\", \"day\"]\n req = sorted(set(required) - set(unit_rev.keys()))\n if len(req):\n _required = \",\".join(req)\n raise ValueError(\n \"to assemble mappings requires at least that \"\n f\"[year, month, day] be specified: [{_required}] is missing\"\n )\n\n # keys we don't recognize\n excess = sorted(set(unit_rev.keys()) - set(_unit_map.values()))\n if len(excess):\n _excess = \",\".join(excess)\n raise ValueError(\n f\"extra keys have been passed to the datetime assemblage: [{_excess}]\"\n )\n\n def coerce(values):\n # we allow coercion to if errors allows\n values = to_numeric(values, errors=errors)\n\n # prevent overflow in case of int8 or int16\n if is_integer_dtype(values):\n values = values.astype(\"int64\", copy=False)\n return values\n\n values = (\n coerce(arg[unit_rev[\"year\"]]) * 10000\n + coerce(arg[unit_rev[\"month\"]]) * 100\n + coerce(arg[unit_rev[\"day\"]])\n )\n try:\n values = to_datetime(values, format=\"%Y%m%d\", errors=errors, utc=tz)\n except (TypeError, ValueError) as err:\n raise ValueError(f\"cannot assemble the datetimes: {err}\") from err\n\n for u in [\"h\", \"m\", \"s\", \"ms\", \"us\", \"ns\"]:\n value = unit_rev.get(u)\n if value is not None and value in arg:\n try:\n values += to_timedelta(coerce(arg[value]), unit=u, errors=errors)\n except (TypeError, ValueError) as err:\n raise ValueError(\n f\"cannot assemble the datetimes [{value}]: {err}\"\n ) from err\n return values\n\n\ndef _attempt_YYYYMMDD(arg: np.ndarray, errors: Optional[str]) -> Optional[np.ndarray]:\n \"\"\"\n try to parse the YYYYMMDD/%Y%m%d format, try to deal with NaT-like,\n arg is a passed in as an object dtype, but could really be ints/strings\n with nan-like/or floats (e.g. with nan)\n\n Parameters\n ----------\n arg : np.ndarray[object]\n errors : {'raise','ignore','coerce'}\n \"\"\"\n\n def calc(carg):\n # calculate the actual result\n carg = carg.astype(object)\n parsed = parsing.try_parse_year_month_day(\n carg / 10000, carg / 100 % 100, carg % 100\n )\n return tslib.array_to_datetime(parsed, errors=errors)[0]\n\n def calc_with_mask(carg, mask):\n result = np.empty(carg.shape, dtype=\"M8[ns]\")\n iresult = result.view(\"i8\")\n iresult[~mask] = iNaT\n\n masked_result = calc(carg[mask].astype(np.float64).astype(np.int64))\n result[mask] = masked_result.astype(\"M8[ns]\")\n return result\n\n # try intlike / strings that are ints\n try:\n return calc(arg.astype(np.int64))\n except (ValueError, OverflowError, TypeError):\n pass\n\n # a float with actual np.nan\n try:\n carg = arg.astype(np.float64)\n return calc_with_mask(carg, notna(carg))\n except (ValueError, OverflowError, TypeError):\n pass\n\n # string with NaN-like\n try:\n # error: Value of type variable \"AnyArrayLike\" of \"isin\" cannot be\n # \"Iterable[Any]\"\n mask = ~algorithms.isin(arg, list(nat_strings)) # type: ignore[type-var]\n return calc_with_mask(arg, mask)\n except (ValueError, OverflowError, TypeError):\n pass\n\n return None\n\n\ndef to_time(arg, format=None, infer_time_format=False, errors=\"raise\"):\n # GH#34145\n warnings.warn(\n \"`to_time` has been moved, should be imported from pandas.core.tools.times. \"\n \"This alias will be removed in a future version.\",\n FutureWarning,\n stacklevel=2,\n )\n from pandas.core.tools.times import to_time\n\n return to_time(arg, format, infer_time_format, errors)\n"
] |
[
[
"pandas._libs.tslibs.conversion.datetime_to_datetime64",
"pandas.core.indexes.datetimes.DatetimeIndex",
"pandas.core.dtypes.common.is_datetime64_ns_dtype",
"pandas.Series",
"pandas._libs.tslibs.Timestamp",
"pandas._libs.tslibs.Timestamp.min.to_julian_date",
"numpy.asarray",
"pandas.core.arrays.datetimes.tz_to_dtype",
"pandas.core.dtypes.common.is_datetime64tz_dtype",
"pandas.DataFrame",
"pandas.core.indexes.base.Index",
"pandas.core.dtypes.missing.notna",
"numpy.any",
"pandas.core.indexes.datetimes.DatetimeIndex._simple_new",
"pandas.core.dtypes.common.is_datetime64_dtype",
"pandas.core.dtypes.common.ensure_object",
"pandas.core.tools.times.to_time",
"pandas._libs.tslibs.parsing.guess_datetime_format",
"pandas.core.algorithms.unique",
"pandas._libs.tslibs.OutOfBoundsDatetime",
"pandas.core.dtypes.common.is_float",
"pandas.to_numeric",
"pandas.core.arrays.datetimes.maybe_convert_dtype",
"pandas.core.dtypes.common.is_integer_dtype",
"pandas.core.dtypes.common.is_list_like",
"pandas._libs.tslib.array_with_unit_to_datetime",
"pandas._libs.tslibs.parsing.try_parse_year_month_day",
"pandas._libs.tslibs.Timestamp.max.to_julian_date",
"numpy.array",
"pandas.core.arrays.datetimes.objects_to_datetime64ns",
"pandas._libs.tslibs.Timedelta",
"pandas._libs.tslib.array_to_datetime",
"pandas.core.dtypes.common.is_scalar",
"pandas.core.dtypes.common.is_integer",
"numpy.empty",
"pandas._libs.tslibs.strptime.array_strptime",
"pandas._libs.tslibs.parsing.format_is_iso"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
adityamangal410/nlp_with_pytorch
|
[
"81919102339ee483210f366aeaec0dd30273a846",
"81919102339ee483210f366aeaec0dd30273a846"
] |
[
"scripts/3.3-am-pl-rnn-glove-disaster-tweets.py",
"scripts/2.0-am-pl-mlp-house-prices.py"
] |
[
"from argparse import ArgumentParser\n\nimport sh\nimport torch.nn\nfrom sklearn.metrics import f1_score, accuracy_score, roc_auc_score\n\nfrom disaster_tweets_data_module import *\n\n\n# sh.rm('-r', '-f', 'lightning_logs/disaster_tweets_rnn_glove')\n\n\nclass DisasterTweetsClassifierRNN(pl.LightningModule):\n\n def __init__(self, rnn_hidden_size, num_classes,\n dropout_p, pretrained_embeddings, learning_rate,\n num_layers, bidirectional, aggregate_hiddens, aggregation_func='max'):\n super().__init__()\n\n self.save_hyperparameters('num_classes', 'dropout_p', 'learning_rate',\n 'rnn_hidden_size', 'num_layers', 'bidirectional',\n 'aggregate_hiddens', 'aggregation_func'\n )\n\n embedding_dim = pretrained_embeddings.size(1)\n num_embeddings = pretrained_embeddings.size(0)\n\n self.emb = torch.nn.Embedding(embedding_dim=embedding_dim,\n num_embeddings=num_embeddings,\n padding_idx=0,\n _weight=pretrained_embeddings)\n\n self.rnn = torch.nn.RNN(embedding_dim, rnn_hidden_size, num_layers=num_layers, bidirectional=bidirectional)\n rnn_output_size = rnn_hidden_size\n if bidirectional:\n rnn_output_size = rnn_hidden_size * 2\n self._dropout_p = dropout_p\n self.fc1 = torch.nn.Linear(rnn_output_size, rnn_hidden_size)\n self.fc2 = torch.nn.Linear(rnn_hidden_size, num_classes)\n\n self.loss = torch.nn.CrossEntropyLoss(reduction='none')\n\n def _initialize_hidden(self, batch_size):\n if self.hparams.bidirectional:\n return torch.zeros((self.hparams.num_layers * 2, batch_size, self.hparams.rnn_hidden_size)).to(self.device)\n else:\n return torch.zeros((self.hparams.num_layers, batch_size, self.hparams.rnn_hidden_size)).to(self.device)\n\n def forward(self, batch, batch_lengths):\n x_embedded = self.emb(batch)\n batch_size, seq_size, feat_size = x_embedded.size()\n x_embedded = x_embedded.permute(1, 0, 2)\n\n initial_hidden = self._initialize_hidden(batch_size)\n\n hidden_all, _ = self.rnn(x_embedded, initial_hidden)\n\n hidden_all = hidden_all.permute(1, 0, 2)\n if self.hparams.aggregate_hiddens:\n features = self.element_wise_aggregate(hidden_all, batch_lengths, self.hparams.aggregation_func)\n else:\n features = self.column_gather(hidden_all, batch_lengths)\n\n int1 = torch.nn.functional.relu(torch.nn.functional.dropout(self.fc1(features),\n p=self._dropout_p))\n output = self.fc2(torch.nn.functional.dropout(int1, p=self._dropout_p))\n return output\n\n def column_gather(self, hiddens, batch_lengths):\n batch_lengths = batch_lengths.long().detach().cpu().numpy() - 1\n out = []\n\n for batch_index, column_index in enumerate(batch_lengths):\n out.append(hiddens[batch_index, column_index])\n return torch.stack(out).to(self.device)\n\n def element_wise_aggregate(self, hiddens, batch_lengths, func='max'):\n batch_lengths = batch_lengths.long().detach().cpu().numpy() - 1\n out = []\n\n for batch_index, column_index in enumerate(batch_lengths):\n if func is 'max':\n out.append(torch.max(hiddens[batch_index, :column_index], 0).values)\n else:\n out.append(torch.mean(hiddens[batch_index, :column_index], 0))\n return torch.stack(out).to(self.device)\n\n def training_step(self, batch, batch_idx):\n y_pred = self(batch['x_data'], batch['x_length'])\n loss = self.loss(y_pred, batch['y_target']).mean()\n return {'loss': loss, 'log': {'train_loss': loss}}\n\n def validation_step(self, batch, batch_idx):\n y_pred = self(batch['x_data'], batch['x_length'])\n loss = self.loss(y_pred, batch['y_target'])\n acc = (y_pred.argmax(-1) == batch['y_target']).float()\n return {'loss': loss, 'acc': acc}\n\n def validation_epoch_end(self, outputs):\n loss = torch.cat([o['loss'] for o in outputs], 0).mean()\n acc = torch.cat([o['acc'] for o in outputs], 0).mean()\n out = {'val_loss': loss, 'val_acc': acc}\n return {**out, 'log': out}\n\n def configure_optimizers(self):\n return torch.optim.Adam(self.parameters(), lr=self.hparams.learning_rate)\n\n def test_step(self, batch, batch_idx):\n y_pred = self(batch['x_data'], batch['x_length'])\n loss = self.loss(y_pred, batch['y_target'])\n acc = (y_pred.argmax(-1) == batch['y_target']).float()\n return {'loss': loss, 'acc': acc}\n\n def test_epoch_end(self, outputs):\n loss = torch.cat([o['loss'] for o in outputs], 0).mean()\n acc = torch.cat([o['acc'] for o in outputs], 0).mean()\n out = {'test_loss': loss, 'test_acc': acc}\n return {**out, 'log': out}\n\n @staticmethod\n def add_model_specific_args(parent_parser):\n parser = ArgumentParser(parents=[parent_parser], add_help=False)\n parser.add_argument('--rnn_hidden_size', default=32, type=int)\n parser.add_argument('--dropout_p', default=0.7, type=float)\n parser.add_argument('--learning_rate', default=1e-5, type=float)\n parser.add_argument('--num_layers', default=3, type=int)\n parser.add_argument('--bidirectional', default=False, action='store_true')\n parser.add_argument('--aggregate_hiddens', default=False, action='store_true')\n parser.add_argument('--aggregation_func', default='max', type=str)\n return parser\n\n\nclass DisasterTweetsClassifierGRU(DisasterTweetsClassifierRNN):\n def __init__(self, rnn_hidden_size, num_classes,\n dropout_p, pretrained_embeddings, learning_rate,\n num_layers, bidirectional, aggregate_hiddens, aggregation_func='max'):\n super().__init__(rnn_hidden_size, num_classes,\n dropout_p, pretrained_embeddings, learning_rate,\n num_layers, bidirectional, aggregate_hiddens, aggregation_func=aggregation_func)\n\n embedding_dim = pretrained_embeddings.size(1)\n self.rnn = torch.nn.GRU(embedding_dim, rnn_hidden_size, num_layers=num_layers, bidirectional=bidirectional)\n\n\nclass DisasterTweetsClassifierLSTM(DisasterTweetsClassifierRNN):\n def __init__(self, rnn_hidden_size, num_classes,\n dropout_p, pretrained_embeddings, learning_rate):\n super().__init__(rnn_hidden_size, num_classes,\n dropout_p, pretrained_embeddings, learning_rate)\n\n embedding_dim = pretrained_embeddings.size(1)\n self.rnn = torch.nn.LSTMCell(embedding_dim, rnn_hidden_size)\n\n\ndef predict_target(text, classifier, vectorizer, max_seq_length):\n text_vector, vec_length = vectorizer.vectorize(text, max_seq_length)\n text_vector = torch.tensor(text_vector)\n vec_length = torch.tensor(vec_length)\n pred = torch.nn.functional.softmax(classifier(text_vector.unsqueeze(dim=0), vec_length.unsqueeze(dim=0)), dim=1)\n probability, target = pred.max(dim=1)\n\n return {'pred': target.item(), 'probability': probability.item()}\n\n\ndef predict_on_dataset(classifier, ds):\n classifier.eval()\n df = pd.DataFrame(columns=[\"text\", \"target\", \"pred\", \"probability\"])\n for sample in iter(ds):\n result = predict_target(sample['text'], classifier, ds.get_vectorizer(), ds.get_max_seq_length())\n result['target'] = sample['y_target'].item()\n result['text'] = sample['text']\n df = df.append(result, ignore_index=True)\n df.target = df.target.astype(np.int32)\n df.pred = df.pred.astype(np.int32)\n\n f1 = f1_score(df.target, df.pred)\n acc = accuracy_score(df.target, df.pred)\n roc_auc = roc_auc_score(df.target, df.probability)\n print(\"Result metrics - \\n Accuracy={} \\n F1-Score={} \\n ROC-AUC={}\".format(acc, f1, roc_auc))\n return df\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser = pl.Trainer.add_argparse_args(parser)\n\n parser.add_argument('--batch_size', default=8, type=int)\n parser.add_argument('--num_workers', default=0, type=int)\n parser.add_argument('--tweets_data_path',\n default='../data/processed/nlp_with_disaster_tweets/train_with_splits.csv',\n type=str)\n parser.add_argument('--embeddings_path',\n default='/Users/amangal/Desktop/machine-learning/nlp_with_disaster_tweets/data/glove.twitter'\n '.27B/glove.twitter.27B.25d.txt',\n type=str)\n\n parser = DisasterTweetsClassifierRNN.add_model_specific_args(parser)\n\n args = parser.parse_args()\n print(\"Args: \\n {}\".format(args))\n\n pl.seed_everything(42)\n\n dm = DisasterTweetsDataModule(tweets_data_path=args.tweets_data_path,\n embeddings_path=args.embeddings_path,\n batch_size=args.batch_size,\n num_workers=args.num_workers)\n\n dm.setup('fit')\n\n # model = DisasterTweetsClassifierRNN(rnn_hidden_size=args.rnn_hidden_size,\n # num_classes=2,\n # dropout_p=args.dropout_p,\n # pretrained_embeddings=dm.pretrained_embeddings,\n # learning_rate=args.learning_rate,\n # num_layers=args.num_layers,\n # bidirectional=args.bidirectional,\n # aggregate_hiddens=args.aggregate_hiddens,\n # aggregation_func=args.aggregation_func\n # )\n\n model = DisasterTweetsClassifierGRU(rnn_hidden_size=args.rnn_hidden_size,\n num_classes=2,\n dropout_p=args.dropout_p,\n pretrained_embeddings=dm.pretrained_embeddings,\n learning_rate=args.learning_rate,\n num_layers=args.num_layers,\n bidirectional=args.bidirectional,\n aggregate_hiddens=args.aggregate_hiddens,\n aggregation_func=args.aggregation_func)\n\n # model = DisasterTweetsClassifierLSTM(rnn_hidden_size=args.rnn_hidden_size,\n # num_classes=2,\n # dropout_p=args.dropout_p,\n # pretrained_embeddings=dm.pretrained_embeddings,\n # learning_rate=args.learning_rate)\n\n trainer = pl.Trainer.from_argparse_args(args,\n deterministic=True,\n weights_summary='full',\n early_stop_callback=False)\n\n trainer.configure_logger(pl.loggers.TensorBoardLogger('lightning_logs/',\n name='disaster_tweets_rnn_glove'))\n trainer.fit(model, dm)\n",
"from argparse import ArgumentParser\n\nimport pandas as pd\nimport pytorch_lightning as pl\nimport torch\nfrom sklearn.preprocessing import StandardScaler\nfrom torch.utils.data import Dataset\n\n\nclass FeatureDataset(Dataset):\n def __init__(self, file_name):\n df = pd.read_csv(file_name)\n\n df = df.select_dtypes(include=['int64'])\n X_df = df.drop(['Id', 'SalePrice'], axis=1)\n self._columns = X_df.columns\n X = X_df.values\n y = df.loc[:, 'SalePrice'].values\n self._scaler = StandardScaler()\n X = self._scaler.fit_transform(X)\n\n # Convert to tensors\n self.X = torch.tensor(X, dtype=torch.float32)\n self.y = torch.tensor(y, dtype=torch.float32)\n\n def __len__(self):\n return len(self.y)\n\n def __getitem__(self, idx):\n return {'x_data': self.X[idx], 'y_target': self.y[idx]}\n\n def get_scaler(self):\n return self._scaler\n\n def get_columns(self):\n return self._columns\n\n\nclass HousePricePredictor(pl.LightningModule):\n\n def __init__(self):\n super().__init__()\n self.fc1 = torch.nn.Linear(33, 32)\n self.fc2 = torch.nn.Linear(32, 16)\n self.fc3 = torch.nn.Linear(16, 8)\n self.fc4 = torch.nn.Linear(8, 1)\n self.loss = torch.nn.MSELoss(reduction='none')\n\n def setup(self, stage):\n self.train_ds = FeatureDataset('../data/raw/house_prices/train.csv')\n\n def train_dataloader(self):\n return torch.utils.data.DataLoader(\n self.train_ds,\n batch_size=args.batch_size,\n drop_last=True,\n shuffle=True\n )\n\n def forward(self, batch):\n int1 = torch.nn.functional.relu(self.fc1(batch))\n int2 = torch.nn.functional.relu(self.fc2(int1))\n int3 = torch.nn.functional.relu(self.fc3(int2))\n output = self.fc4(int3)\n return output\n\n def training_step(self, batch, batch_idx):\n y_pred = self(batch['x_data'])\n loss = self.loss(y_pred, batch['y_target']).mean()\n return {'loss': loss, 'log': {'train_loss': loss}}\n\n def configure_optimizers(self):\n return torch.optim.Adam(self.parameters(), lr=args.learning_rate)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser = pl.Trainer.add_argparse_args(parser)\n\n parser.add_argument('--batch_size', default=8, type=int)\n parser.add_argument('--learning_rate', default=1e-3, type=float)\n\n args = parser.parse_args()\n\n model = HousePricePredictor()\n trainer = pl.Trainer.from_argparse_args(args)\n trainer.configure_logger(pl.loggers.TensorBoardLogger('lightning_logs/', name='house_price', version=0))\n trainer.fit(model)\n"
] |
[
[
"sklearn.metrics.roc_auc_score",
"sklearn.metrics.f1_score",
"sklearn.metrics.accuracy_score"
],
[
"pandas.read_csv",
"torch.utils.data.DataLoader",
"torch.tensor",
"torch.nn.Linear",
"sklearn.preprocessing.StandardScaler",
"torch.nn.MSELoss"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
googlearchive/rgc-models
|
[
"0dea94bbd54f591d82d95169e33d40bb55b6be94",
"0dea94bbd54f591d82d95169e33d40bb55b6be94",
"0dea94bbd54f591d82d95169e33d40bb55b6be94",
"0dea94bbd54f591d82d95169e33d40bb55b6be94",
"0dea94bbd54f591d82d95169e33d40bb55b6be94"
] |
[
"response_model/python/metric_learning/end_to_end/data_util.py",
"response_model/python/metric_learning/score_fcns/mlnn_slim.py",
"response_model/python/metric_learning/end_to_end/s_r_embedding_multiple_retina.py",
"response_model/python/population_subunits/coarse/analysis/few_cells_tf_analyse_roc.py",
"response_model/python/metric_learning/end_to_end/stimulus_response_embedding.py"
] |
[
"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Collect responses across multiple retina for same stimulus.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os.path\nimport h5py\nimport numpy as np\nimport scipy.io as sio\nimport tensorflow as tf\nimport skimage.transform\nfrom tensorflow.python.platform import gfile\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef copy_locally(src, dst):\n \"\"\"Copy data locally if not already there.\"\"\"\n\n # Make the directory if it does not already exist.\n if not gfile.IsDirectory(dst):\n gfile.MkDir(dst)\n\n files = gfile.ListDirectory(src)\n for ifile in files:\n dst_file = os.path.join(dst, ifile)\n src_file = os.path.join(src, ifile)\n\n if not gfile.Exists(dst_file):\n gfile.Copy(src_file, dst_file)\n tf.logging.info('Copied %s' % src_file)\n else:\n tf.logging.info('File exists %s' % dst_file)\n\n tf.logging.info('File copied to/exists at local destination')\n\n\ndef get_stimulus_response(src_dir, src_dataset, stim_id, boundary=0,\n if_get_stim=True):\n \"\"\"Get stimulus-response data for all datasets.\n\n Args :\n src_dir : Location of all joint embedding datasets.\n src_dataset : Dataset corresponding of a specific stimulus.\n stim_id : string ID of the stimulus.\n boundary : Remove cells within a boundary to the edges.\n if_get_stim : If False, do not load stimulus\n\n Returns :\n stimulus : Stimulus matrix (Time x dimx x dimy).\n responses : Discretized cell responses (Time x n_cells).\n dimx : X dimension of stimulus.\n dimy : Y dimension of stimulus.\n num_cell_types : number of cell types.\n \"\"\"\n\n # Copy data locally.\n # Since gfile does not support reading of large files directly from CNS,\n # we need to copy the data locally first.\n src = os.path.join(src_dir, src_dataset)\n if not gfile.IsDirectory(FLAGS.tmp_dir):\n gfile.MkDir(FLAGS.tmp_dir)\n dst = os.path.join(FLAGS.tmp_dir, src_dataset)\n print('Source %s' % src)\n print('Destination %s' % dst)\n copy_locally(src, dst)\n\n # Load stimulus-response data.\n if if_get_stim:\n data = h5py.File(os.path.join(dst, 'stimulus.mat'))\n stimulus = np.array(data.get('stimulus'))\n\n # Make dynamic range of stimuli from -0.5 to 0.5\n stim_min = np.min(stimulus)\n stim_max = np.max(stimulus)\n stimulus -= stim_min\n stimulus /= (stim_max - stim_min)\n stimulus -= 0.5\n\n # Make the stimuli mean 0\n stimulus -= np.mean(stimulus)\n\n else:\n stimulus = None\n\n # Load responses from multiple retinas.\n datasets_list = os.path.join(dst, 'datasets.txt')\n datasets = open(datasets_list, 'r').read()\n training_datasets = [line for line in datasets.splitlines()]\n\n num_cell_types = 2\n dimx_desired = 80\n dimy_desired = 40\n if stimulus is not None:\n dimx_actual = stimulus.shape[1]\n dimy_actual = stimulus.shape[2]\n else:\n stix_sz = np.int(src_dataset.split('-')[1])\n dimx_actual = np.int(640 / stix_sz)\n dimy_actual = np.int(320 / stix_sz)\n\n responses = []\n for idata in training_datasets:\n print(idata)\n data_file = os.path.join(dst, idata)\n data = sio.loadmat(data_file)\n data.update({'stimulus_key': stim_id})\n process_dataset(data, dimx_desired, dimy_desired, dimx_actual, dimy_actual,\n num_cell_types, boundary=boundary)\n data.update({'piece': idata})\n responses += [data]\n\n if FLAGS.minimize_disk_usage:\n gfile.DeleteRecursively(dst)\n\n return stimulus, responses, dimx_desired, dimy_desired, num_cell_types\n\n\ndef process_dataset(iresp, dimx_desired, dimy_desired, dimx_actual, dimy_actual,\n num_cell_types, boundary=0):\n \"\"\"Clean data and compute auxillary properties of the responses.\n\n Args :\n iresp : Discretized cell response of one population (Time x n_cells).\n dimx_desired : Desired X dimension of stimulus.\n dimy_desired : Desired Y dimension of stimulus.\n dimx_actual : Actual X dimension of stimulus.\n dimy_actual : Actual Y dimension of stimulus.\n num_cell_types : number of cell types.\n boundary : Remove cells within a boundary to edges.\n\n Returns :\n iresp : Responses with added auxillary properties.\n \"\"\"\n\n # Scale centers from 'actual' dimensions to 'desired'.\n iresp['centers'][:, 0] = (dimx_desired *\n np.double(iresp['centers'][:, 0]) / dimx_actual)\n iresp['centers'][:, 1] = (dimy_desired *\n np.double(iresp['centers'][:, 1]) / dimy_actual)\n\n iresp['dimx_initial'] = dimx_actual\n iresp['dimy_initial'] = dimy_actual\n iresp['dimx_final'] = dimx_desired\n iresp['dimy_final'] = dimy_desired\n\n # Remove cells with RFs outide the visual space.\n valid_cells0 = np.logical_and(iresp['centers'][:, 0] <= dimx_desired - boundary,\n iresp['centers'][:, 1] <= dimy_desired - boundary)\n valid_cells1 = np.logical_and(iresp['centers'][:, 0] > boundary,\n iresp['centers'][:, 1] > boundary)\n valid_cells = np.logical_and(valid_cells0, valid_cells1)\n\n iresp.update({'valid_cells': valid_cells})\n\n # Remove invalid cells.\n iresp['centers'] = iresp['centers'][valid_cells, :]\n\n try:\n iresp['sta_params'] = iresp['sta_params'][valid_cells, :]\n except KeyError:\n print('No STA params')\n\n try:\n iresp['responses'] = iresp['responses'][:, valid_cells]\n mean_resp = np.mean(iresp['responses'], 0)\n iresp.update({'mean_firing_rate': mean_resp})\n except KeyError:\n print('No responses')\n\n try:\n iresp['repeats'] = iresp['repeats'][:, :, valid_cells]\n mean_resp = np.mean(np.mean(iresp['repeats'], 0), 0)\n iresp.update({'mean_firing_rate': mean_resp})\n except KeyError:\n print('No repeats')\n\n try:\n iresp['cellID_list'] = iresp['cellID_list'][:, valid_cells]\n except KeyError:\n print('No cell ID list')\n\n iresp['cell_type'] = iresp['cell_type'][:, valid_cells]\n\n # find mosaic separation for different cell types\n iresp['dist_nn_cell_type'] = get_mosaic_distances(iresp['centers'],\n iresp['cell_type'])\n\n print('Valid cells: %d/%d' % (np.sum(valid_cells), valid_cells.shape[0]))\n\n # Compute mean firing rate for cells.\n n_cells = np.squeeze(iresp['centers']).shape[0]\n\n # Do embedding of centers on a grid.\n _, _, map_cell_grid, mask_cells = give_cell_grid(iresp['centers'],\n dimx=dimx_desired,\n dimy=dimy_desired,\n resolution=1)\n iresp.update({'map_cell_grid': map_cell_grid})\n iresp.update({'mask_cells': mask_cells})\n\n # Encode cell type as 1-hot vector.\n ctype_1hot = np.zeros((n_cells, num_cell_types))\n for icell_type in np.arange(1, num_cell_types+1):\n ctype_1hot[:, icell_type-1] = np.double(iresp['cell_type'] == icell_type)\n\n iresp.update({'ctype_1hot': ctype_1hot})\n\n # get EIs\n iresp['ei_image'] = iresp['ei_image'][valid_cells, :, :]\n\ndef give_cell_grid(centers, resolution, dimx=80, dimy=40, mask_distance=6):\n \"\"\"Embeds each RF center on a discrete grid.\n\n Args:\n centers: center location of cells (n_cells x 2).\n resolution: Float specifying the resolution of grid.\n dimx : X dimension of grid.\n dimy : Y dimension of grid.\n mask_distance : Distance of pixel from center to be included in a cell's\n receptive field mask.\n\n Returns:\n centers_grid : Discretized centers (n_cells x 2).\n grid_size : dimensions of the grid (2D integer tuple).\n map_cell_grid : mapping between cells to grid (grid_x x grid_y x n_cells)\n mask_cells : Mask of receptive field for each cell\n (gird_x x grid_y x n_cells)\n \"\"\"\n\n n_cells = centers.shape[0]\n centers_grid = np.floor(centers - 1 / resolution).astype(np.int)\n # subtract 1 because matlab indexing starts from 1.\n\n grid_size = [dimx, dimy]\n\n # map_cell_grid is location of each cell to grid point\n map_cell_grid = np.zeros((grid_size[0], grid_size[1], n_cells))\n for icell in range(n_cells):\n map_cell_grid[centers_grid[icell, 0], centers_grid[icell, 1], icell] = 1\n\n # get mask\n mask_cells = np.zeros((grid_size[0], grid_size[1], n_cells))\n yy, xx = np.meshgrid(np.arange(dimy), np.arange(dimx))\n for icell in range(n_cells):\n mask_cell = (np.sqrt((xx - centers_grid[icell, 0]) ** 2 +\n (yy - centers_grid[icell, 1]) ** 2) <= mask_distance)\n mask_cells[:, :, icell] = mask_cell\n\n\n return centers_grid, grid_size, map_cell_grid, mask_cells\n\n\ndef get_mosaic_distances(center_locations_log, cell_type):\n \"\"\"Use cell locations to get nearest neighbor distances for each cell type.\n\n Args:\n center_locations_log : Cell locations (numpy array = # cells x 2)\n cell_type : Cell types (1: OFF parasol, 2: ON parasol)\n (numpy array of size # cells)\n\n Returns:\n dist_nn_cell_type : Dictionary {cell_type: nearest neighbor separation}.\n\n \"\"\"\n cell_type = np.squeeze(cell_type)\n\n # Find NN distance for each cell\n dist_nn_cell_type = {}\n for icell_type in np.unique(cell_type):\n cells_selected = np.where(cell_type == icell_type)[0]\n dist_nn = []\n for icell in cells_selected:\n d_cell = []\n for jcell in cells_selected:\n if icell == jcell:\n continue\n d_cell += [np.sqrt(np.sum((center_locations_log[icell, :] -\n center_locations_log[jcell, :]) ** 2))]\n dist_nn += [np.min(d_cell)]\n dist_nn_cell_type.update({icell_type: np.mean(dist_nn)})\n\n return dist_nn_cell_type\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# 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\"\"\"Embed each response using a MultilayeredNN using TF.SLIM and L2 distance.\n\nEach response sequence (cell x time) is passed through a NN and\nthe final output of NN is the embedding of the response vector.\nGiven tripelts of {anchor, positive, negative}, find a NN that\nd(embed(anchor), embed(positive)) < d(embed(anchor, negative)),\nwhere d(.,.) is the euclidean distance.\n\nTest :\n--model='mlnn_slim' --layers='10, 10' --logtostderr --lam_l1=0 \\\n--data_path='/cns/oi-d/home/bhaishahster/metric_learning/examples_pc2017_04_25_1/' \\\n--data_train='data012_lr_13_new_cells_groupb_with_stimulus_train.mat' \\\n--data_test='data012_lr_13_new_cells_groupb_with_stimulus_test.mat' \\\n--save_suffix='_2017_04_25_1_cells_13_new_groupb_train_mutiple_expts_local_struct' \\\n--triplet_type='a'\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport numpy as np\nimport tensorflow as tf\nfrom retina.response_model.python.metric_learning.score_fcns import metric\nfrom retina.response_model.python.metric_learning.score_fcns import mlnn_score\nimport tensorflow.contrib.slim as slim\n\nclass MetricMLNNSlim(mlnn_score.MetricMLNN):\n \"\"\"Euclidean distance in embedded responses using RNN.\"\"\"\n\n def _build_mlnn(self, n_cells, layers, time_window, lr, is_training):\n \"\"\"Builds the tensorflow graph for embedding responses and compute dist.\n\n Args :\n n_cells (int) : Number of cells for response.\n layers (strong) : specification of layers\n time_window (int) : The number of continuous time bins per response.\n lr (float) : Learning rate.\n\n \"\"\"\n\n self.layer_sizes = layers.split(',')\n self.layer_sizes = [np.int(i) for i in self.layer_sizes]\n self.num_layers = len(self.layer_sizes)\n tf.logging.info('Number of layers: %d' % self.num_layers)\n\n self.anchor = tf.placeholder(shape=[None, n_cells, time_window],\n dtype=tf.float32)\n self.pos = tf.placeholder(shape=[None, n_cells, time_window],\n dtype=tf.float32)\n self.neg = tf.placeholder(shape=[None, n_cells, time_window,],\n dtype=tf.float32)\n\n def embed_mlnn(response, reuse_variables=False):\n \"\"\"Gives RNN embedding of response ( bactch x n_cells x time_window)\"\"\"\n\n activation_fn = self._get_activation_fn()\n layers = self.layer_sizes\n n_layers = len(layers)\n tf.logging.info('Number of layers: %d' % n_layers)\n net = tf.reshape(response, [-1, n_cells * time_window])\n for ilayer in range(n_layers):\n tf.logging.info('Building layer: %d'\n % (layers[ilayer]))\n net = slim.fully_connected(net, int(layers[ilayer]),\n scope='layer_%d' % ilayer,\n reuse=reuse_variables,\n normalizer_fn=slim.batch_norm,\n activation_fn=activation_fn)\n\n return net\n\n # embed anchor, positive and negative examples.\n with slim.arg_scope([slim.batch_norm], is_training=is_training):\n self.embed_anchor = embed_mlnn(self.anchor, reuse_variables=False)\n self.embed_pos = embed_mlnn(self.pos, reuse_variables=True)\n self.embed_neg = embed_mlnn(self.neg, reuse_variables=True)\n\n # Loss for each point max(d(anchor, pos)^2 - d(anchor, neg)^2 + 1, 0)\n self.get_loss()\n\n # train model\n self.train_step = tf.train.AdagradOptimizer(lr).minimize(self.loss)\n\n\n def distance_squared(self, embed1, embed2):\n return tf.reduce_sum((embed1 - embed2)**2, 1)\n\n def get_loss(self):\n d_an = self.distance_squared(self.embed_anchor, self.embed_neg)\n d_ap = self.distance_squared(self.embed_anchor, self.embed_pos)\n d_pn = self.distance_squared(self.embed_pos, self.embed_neg)\n d_n = tf.minimum(d_an, d_pn) # Error ?\n\n # Loss for each point max(d(anchor, pos)^2 - d(anchor, neg)^2 + 1, 0)\n self.loss = tf.reduce_sum(tf.nn.relu(d_ap - d_n + 1), 0)\n\n def _get_activation_fn(self):\n return tf.nn.relu\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# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nr\"\"\"Jointly embed stim-resp from multiple retina, conv embed for resp, time filter for stim.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os.path\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom absl import app\nfrom absl import gfile\nimport numpy as np, h5py,numpy\nimport scipy.io as sio\nfrom numpy.random import RandomState\n\n# for plotting stuff\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport pickle\nimport retina.response_model.python.metric_learning.end_to_end.utils as utils\nimport retina.response_model.python.metric_learning.end_to_end.convolutional_embed_resp as conv\nimport retina.response_model.python.metric_learning.end_to_end.data_util as data_util\nfrom tensorflow.python.profiler.model_analyzer import PrintModelAnalysis\n\nflags = tf.app.flags\nflags.DEFINE_string('src_dir', '/home/bhaishahster/stim-resp4', 'Where is the datasets are')\nflags.DEFINE_string('tmp_dir',\n '/home/bhaishahster/'\n 'Downloads/stim-resp4',\n 'temporary folder on machine for better I/O')\nflags.DEFINE_string('save_folder', '/home/bhaishahster/end_to_end4',\n 'where to store model and analysis')\nflags.DEFINE_integer('max_iter', 2000000,\n 'Maximum number of iterations')\nflags.DEFINE_integer('taskid', 0,\n 'Maximum number of iterations')\n\nflags.DEFINE_integer('is_test', 0,\n 'If testing 1 , training 0')\nflags.DEFINE_string('save_suffix',\n '',\n 'suffix to save files')\n\nflags.DEFINE_string('resp_layers',\n '3, 128, 1, 3, 128, 1, 3, 128, 1, 3, 128, 2, 3, 128, 2, 3, 1, 1',\n 'suffix to save files')\n\nflags.DEFINE_string('stim_layers',\n '1, 5, 1, 3, 128, 1, 3, 128, 1, 3, 128, 1, 3, 128, 2, 3, 128, 2, 3, 1, 1',\n 'suffix to save files')\n\nflags.DEFINE_bool('batch_norm',\n True,\n 'Do we apply batch-norm regularization between layers?')\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef main(unused_argv=()):\n\n ## copy data locally\n dst = FLAGS.tmp_dir\n print('Starting Copy')\n if not gfile.IsDirectory(dst):\n gfile.MkDir(dst)\n\n files = gfile.ListDirectory(FLAGS.src_dir)\n for ifile in files:\n ffile = os.path.join(dst, ifile)\n if not gfile.Exists(ffile):\n gfile.Copy(os.path.join(FLAGS.src_dir, ifile), ffile)\n print('Copied %s' % os.path.join(FLAGS.src_dir, ifile))\n else:\n print('File exists %s' % ffile)\n\n print('File copied to destination')\n\n\n ## load data\n # load stimulus\n data = h5py.File(os.path.join(dst, 'stimulus.mat'))\n stimulus = np.array(data.get('stimulus')) - 0.5\n\n # load responses from multiple retina\n datasets_list = os.path.join(dst, 'datasets.txt')\n datasets = open(datasets_list, \"r\").read()\n training_datasets = [line for line in datasets.splitlines()]\n\n responses = []\n for idata in training_datasets:\n print(idata)\n data_file = os.path.join(dst, idata)\n data = sio.loadmat(data_file)\n responses += [data]\n print(np.max(data['centers'], 0))\n\n # generate additional features for responses\n num_cell_types = 2\n dimx = 80\n dimy = 40\n for iresp in responses:\n # remove cells which are outside 80x40 window.\n process_dataset(iresp, dimx, dimy, num_cell_types)\n\n ## generate graph -\n if FLAGS.is_test == 0:\n is_training = True\n if FLAGS.is_test == 1:\n is_training = True # False\n\n with tf.Session() as sess:\n\n ## Make graph\n # embed stimulus.\n time_window = 30\n stimx = stimulus.shape[1]\n stimy = stimulus.shape[2]\n stim_tf = tf.placeholder(tf.float32,\n shape=[None, stimx,\n stimy, time_window]) # batch x X x Y x time_window\n batch_norm = FLAGS.batch_norm\n stim_embed = embed_stimulus(FLAGS.stim_layers.split(','),\n batch_norm, stim_tf, is_training,\n reuse_variables=False)\n\n '''\n ttf_tf = tf.Variable(np.ones(time_window).astype(np.float32)/10, name='stim_ttf')\n filt = tf.expand_dims(tf.expand_dims(tf.expand_dims(ttf_tf, 0), 0), 3)\n stim_time_filt = tf.nn.conv2d(stim_tf, filt,\n strides=[1, 1, 1, 1], padding='SAME') # batch x X x Y x 1\n\n\n ilayer = 0\n stim_time_filt = slim.conv2d(stim_time_filt, 1, [3, 3],\n stride=1,\n scope='stim_layer_wt_%d' % ilayer,\n reuse=False,\n normalizer_fn=slim.batch_norm,\n activation_fn=tf.nn.softplus,\n normalizer_params={'is_training': is_training},\n padding='SAME')\n '''\n\n\n # embed responses.\n num_cell_types = 2\n layers = FLAGS.resp_layers # format: window x filters x stride .. NOTE: final filters=1, stride =1 throughout\n batch_norm = FLAGS.batch_norm\n time_window = 1\n anchor_model = conv.ConvolutionalProsthesisScore(sess, time_window=1,\n layers=layers,\n batch_norm=batch_norm,\n is_training=is_training,\n reuse_variables=False,\n num_cell_types=2,\n dimx=dimx, dimy=dimy)\n\n neg_model = conv.ConvolutionalProsthesisScore(sess, time_window=1,\n layers=layers,\n batch_norm=batch_norm,\n is_training=is_training,\n reuse_variables=True,\n num_cell_types=2,\n dimx=dimx, dimy=dimy)\n\n d_s_r_pos = tf.reduce_sum((stim_embed - anchor_model.responses_embed)**2, [1, 2, 3]) # batch\n d_pairwise_s_rneg = tf.reduce_sum((tf.expand_dims(stim_embed, 1) -\n tf.expand_dims(neg_model.responses_embed, 0))**2, [2, 3, 4]) # batch x batch_neg\n beta = 10\n # if FLAGS.save_suffix == 'lr=0.001':\n loss = tf.reduce_sum(beta * tf.reduce_logsumexp(tf.expand_dims(d_s_r_pos / beta, 1) -\n d_pairwise_s_rneg / beta, 1), 0)\n # else :\n\n # loss = tf.reduce_sum(tf.nn.softplus(1 + tf.expand_dims(d_s_r_pos, 1) - d_pairwise_s_rneg))\n accuracy_tf = tf.reduce_mean(tf.sign(-tf.expand_dims(d_s_r_pos, 1) + d_pairwise_s_rneg))\n\n lr = 0.001\n train_op = tf.train.AdagradOptimizer(lr).minimize(loss)\n\n # set up training and testing data\n training_datasets_all = [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15]\n testing_datasets = [0, 4, 8, 12]\n print('Testing datasets', testing_datasets)\n\n n_training_datasets_log = [1, 3, 5, 7, 9, 11, 12]\n\n if (np.floor(FLAGS.taskid / 4)).astype(np.int) < len(n_training_datasets_log):\n # do randomly sampled training data for 0<= FLAGS.taskid < 28\n prng = RandomState(23)\n n_training_datasets = n_training_datasets_log[(np.floor(FLAGS.taskid / 4)).astype(np.int)]\n for _ in range(10*FLAGS.taskid):\n print(prng.choice(training_datasets_all,\n n_training_datasets, replace=False))\n training_datasets = prng.choice(training_datasets_all,\n n_training_datasets, replace=False)\n\n # training_datasets = [i for i in range(7) if i< 7-FLAGS.taskid] #[0, 1, 2, 3, 4, 5]\n\n\n else:\n # do 1 training data, chosen in order for FLAGS.taskid >= 28\n datasets_all = np.arange(16)\n training_datasets = [datasets_all[FLAGS.taskid % (4 * len(n_training_datasets_log))]]\n\n print('Task ID %d' % FLAGS.taskid)\n print('Training datasets', training_datasets)\n\n # Initialize stuff.\n file_name = ('end_to_end_stim_%s_resp_%s_beta_%d_taskid_%d'\n '_training_%s_testing_%s_%s' % (FLAGS.stim_layers,\n FLAGS.resp_layers, beta, FLAGS.taskid,\n str(training_datasets)[1: -1],\n str(testing_datasets)[1: -1],\n FLAGS.save_suffix))\n saver_var, start_iter = initialize_model(FLAGS.save_folder, file_name, sess)\n\n # print model graph\n PrintModelAnalysis(tf.get_default_graph())\n\n # Add summary ops\n retina_number = tf.placeholder(tf.int16, name='input_retina');\n\n summary_ops = []\n for iret in np.arange(len(responses)):\n print(iret)\n r1 = tf.summary.scalar('loss_%d' % iret , loss)\n r2 = tf.summary.scalar('accuracy_%d' % iret , accuracy_tf)\n summary_ops += [tf.summary.merge([r1, r2])]\n\n # tf.summary.scalar('loss', loss)\n # tf.summary.scalar('accuracy', accuracy_tf)\n # summary_op = tf.summary.merge_all()\n\n # Setup summary writers\n summary_writers = []\n for loc in ['train', 'test']:\n summary_location = os.path.join(FLAGS.save_folder, file_name,\n 'summary_' + loc )\n summary_writer = tf.summary.FileWriter(summary_location, sess.graph)\n summary_writers += [summary_writer]\n\n\n # start training\n batch_neg_train_sz = 100\n batch_train_sz = 100\n\n\n def batch(dataset_id):\n batch_train = get_batch(stimulus, responses[dataset_id]['responses'],\n batch_size=batch_train_sz,\n batch_neg_resp=batch_neg_train_sz,\n stim_history=30, min_window=10)\n stim_batch, resp_batch, resp_batch_neg = batch_train\n feed_dict = {stim_tf: stim_batch,\n anchor_model.responses_tf: np.expand_dims(resp_batch, 2),\n neg_model.responses_tf: np.expand_dims(resp_batch_neg, 2),\n\n anchor_model.map_cell_grid_tf: responses[dataset_id]['map_cell_grid'],\n anchor_model.cell_types_tf: responses[dataset_id]['ctype_1hot'],\n anchor_model.mean_fr_tf: responses[dataset_id]['mean_firing_rate'],\n\n neg_model.map_cell_grid_tf: responses[dataset_id]['map_cell_grid'],\n neg_model.cell_types_tf: responses[dataset_id]['ctype_1hot'],\n neg_model.mean_fr_tf: responses[dataset_id]['mean_firing_rate'],\n retina_number : dataset_id}\n\n return feed_dict\n\n def batch_few_cells(responses):\n batch_train = get_batch(stimulus, responses['responses'],\n batch_size=batch_train_sz,\n batch_neg_resp=batch_neg_train_sz,\n stim_history=30, min_window=10)\n stim_batch, resp_batch, resp_batch_neg = batch_train\n feed_dict = {stim_tf: stim_batch,\n anchor_model.responses_tf: np.expand_dims(resp_batch, 2),\n neg_model.responses_tf: np.expand_dims(resp_batch_neg, 2),\n\n anchor_model.map_cell_grid_tf: responses['map_cell_grid'],\n anchor_model.cell_types_tf: responses['ctype_1hot'],\n anchor_model.mean_fr_tf: responses['mean_firing_rate'],\n\n neg_model.map_cell_grid_tf: responses['map_cell_grid'],\n neg_model.cell_types_tf: responses['ctype_1hot'],\n neg_model.mean_fr_tf: responses['mean_firing_rate'],\n }\n\n return feed_dict\n\n if FLAGS.is_test == 1:\n print('Testing')\n save_dict = {}\n\n from IPython import embed; embed()\n ## Estimate one, fix others\n '''\n grad_resp = tf.gradients(d_s_r_pos, anchor_model.responses_tf)\n\n t_start = 1000\n t_len = 100\n stim_history = 30\n stim_batch = np.zeros((t_len, stimulus.shape[1],\n stimulus.shape[2], stim_history))\n for isample, itime in enumerate(np.arange(t_start, t_start + t_len)):\n stim_batch[isample, :, :, :] = np.transpose(stimulus[itime: itime-stim_history:-1, :, :], [1, 2, 0])\n\n iretina = testing_datasets[0]\n resp_batch = np.expand_dims(np.random.rand(t_len, responses[iretina]['responses'].shape[1]), 2)\n\n step_sz = 0.01\n eps = 1e-2\n dist_prev = np.inf\n for iiter in range(10000):\n feed_dict = {stim_tf: stim_batch,\n anchor_model.map_cell_grid_tf: responses[iretina]['map_cell_grid'],\n anchor_model.cell_types_tf: responses[iretina]['ctype_1hot'],\n anchor_model.mean_fr_tf: responses[iretina]['mean_firing_rate'],\n anchor_model.responses_tf: resp_batch}\n dist_np, resp_grad_np = sess.run([d_s_r_pos, grad_resp], feed_dict=feed_dict)\n if np.sum(np.abs(dist_prev - dist_np)) < eps:\n break\n print(np.sum(dist_np), np.sum(np.abs(dist_prev - dist_np)))\n dist_prev = dist_np\n resp_batch = resp_batch - step_sz * resp_grad_np[0]\n\n resp_batch = resp_batch.squeeze()\n '''\n\n\n # from IPython import embed; embed()\n ## compute distances between s-r pairs for small number of cells\n\n test_retina = []\n for iretina in range(len(testing_datasets)):\n dataset_id = testing_datasets[iretina]\n\n num_cells_total = responses[dataset_id]['responses'].shape[1]\n dataset_center = responses[dataset_id]['centers'].mean(0)\n dataset_cell_distances = np.sqrt(np.sum((responses[dataset_id]['centers'] -\n dataset_center), 1))\n order_cells = np.argsort(dataset_cell_distances)\n\n test_sr_few_cells = {}\n for num_cells_prc in [5, 10, 20, 30, 50, 100]:\n num_cells = np.percentile(np.arange(num_cells_total),\n num_cells_prc).astype(np.int)\n\n choose_cells = order_cells[:num_cells]\n\n resposnes_few_cells = {'responses': responses[dataset_id]['responses'][:, choose_cells],\n 'map_cell_grid': responses[dataset_id]['map_cell_grid'][:, :, choose_cells],\n 'ctype_1hot': responses[dataset_id]['ctype_1hot'][choose_cells, :],\n 'mean_firing_rate': responses[dataset_id]['mean_firing_rate'][choose_cells]}\n # get a batch\n d_pos_log = np.array([])\n d_neg_log = np.array([])\n for test_iter in range(1000):\n print(iretina, num_cells_prc, test_iter)\n feed_dict = batch_few_cells(resposnes_few_cells)\n d_pos, d_neg = sess.run([d_s_r_pos, d_pairwise_s_rneg], feed_dict=feed_dict)\n d_neg = np.diag(d_neg) # np.mean(d_neg, 1) #\n d_pos_log = np.append(d_pos_log, d_pos)\n d_neg_log = np.append(d_neg_log, d_neg)\n\n precision_log, recall_log, F1_log, FPR_log, TPR_log = ROC(d_pos_log, d_neg_log)\n\n print(np.sum(d_pos_log > d_neg_log))\n print(np.sum(d_pos_log < d_neg_log))\n test_sr= {'precision': precision_log, 'recall': recall_log,\n 'F1': F1_log, 'FPR': FPR_log, 'TPR': TPR_log,\n 'd_pos_log': d_pos_log, 'd_neg_log': d_neg_log,\n 'num_cells': num_cells}\n\n test_sr_few_cells.update({'num_cells_prc_%d' % num_cells_prc : test_sr})\n test_retina += [test_sr_few_cells]\n save_dict.update({'few_cell_analysis': test_retina})\n\n ## compute distances between s-r pairs - pos and neg.\n\n test_retina = []\n for iretina in range(len(testing_datasets)):\n # stim-resp log\n d_pos_log = np.array([])\n d_neg_log = np.array([])\n for test_iter in range(1000):\n print(test_iter)\n feed_dict = batch(testing_datasets[iretina])\n d_pos, d_neg = sess.run([d_s_r_pos, d_pairwise_s_rneg], feed_dict=feed_dict)\n d_neg = np.diag(d_neg) # np.mean(d_neg, 1) #\n d_pos_log = np.append(d_pos_log, d_pos)\n d_neg_log = np.append(d_neg_log, d_neg)\n\n precision_log, recall_log, F1_log, FPR_log, TPR_log = ROC(d_pos_log, d_neg_log)\n\n print(np.sum(d_pos_log > d_neg_log))\n print(np.sum(d_pos_log < d_neg_log))\n test_sr = {'precision': precision_log, 'recall': recall_log,\n 'F1': F1_log, 'FPR': FPR_log, 'TPR': TPR_log,\n 'd_pos_log': d_pos_log, 'd_neg_log': d_neg_log}\n\n test_retina += [test_sr]\n\n save_dict.update({'test_sr': test_retina})\n\n\n ## ROC curves of responses from repeats - dataset 1\n repeats_datafile = '/home/bhaishahster/metric_learning/datasets/2015-09-23-7.mat'\n repeats_data = sio.loadmat(gfile.Open(repeats_datafile, 'r'));\n repeats_data['cell_type'] = repeats_data['cell_type'].T\n\n # process repeats data\n process_dataset(repeats_data, dimx, dimy, num_cell_types)\n\n # analyse and store the result\n test_reps = analyse_response_repeats(repeats_data, anchor_model, neg_model, sess)\n save_dict.update({'test_reps_2015-09-23-7': test_reps})\n\n ## ROC curves of responses from repeats - dataset 2\n repeats_datafile = '/home/bhaishahster/metric_learning/examples_pc2005_08_03_0/data005_test.mat'\n repeats_data = sio.loadmat(gfile.Open(repeats_datafile, 'r'));\n process_dataset(repeats_data, dimx, dimy, num_cell_types)\n\n # analyse and store the result\n '''\n test_clustering = analyse_response_repeats_all_trials(repeats_data, anchor_model, neg_model, sess)\n save_dict.update({'test_reps_2005_08_03_0': test_clustering})\n '''\n #\n # get model params\n save_dict.update({'model_pars': sess.run(tf.trainable_variables())})\n\n\n save_analysis_filename = os.path.join(FLAGS.save_folder, file_name + '_analysis.pkl')\n pickle.dump(save_dict, gfile.Open(save_analysis_filename, 'w'))\n print(save_analysis_filename)\n return\n\n test_iiter = 0\n for iiter in range(start_iter, FLAGS.max_iter): # TODO(bhaishahster) :add FLAGS.max_iter\n\n # get a new batch\n # stim_tf, anchor_model.responses_tf, neg_model.responses_tf\n\n # training step\n train_dataset = training_datasets[iiter % len(training_datasets)]\n feed_dict_train = batch(train_dataset)\n _, loss_np_train = sess.run([train_op, loss], feed_dict=feed_dict_train)\n print(train_dataset, loss_np_train)\n\n # write summary\n if iiter % 10 == 0:\n # write train summary\n test_iiter = test_iiter + 1\n\n train_dataset = training_datasets[test_iiter % len(training_datasets)]\n feed_dict_train = batch(train_dataset)\n summary_train = sess.run(summary_ops[train_dataset], feed_dict=feed_dict_train)\n summary_writers[0].add_summary(summary_train, iiter)\n\n # write test summary\n test_dataset = testing_datasets[test_iiter % len(testing_datasets)]\n feed_dict_test = batch(test_dataset)\n l_test, summary_test = sess.run([loss, summary_ops[test_dataset]], feed_dict=feed_dict_test)\n summary_writers[1].add_summary(summary_test, iiter)\n print('Test retina: %d, loss: %.3f' % (test_dataset, l_test))\n\n # save model\n if iiter % 10 == 0:\n save_model(saver_var, FLAGS.save_folder, file_name, sess, iiter)\n\n\n\ndef ROC(distances_pos, distances_neg):\n \"\"\"Compute ROC curve.\"\"\"\n\n all_distances = np.append(distances_pos, distances_neg)\n precision_log = []\n recall_log = []\n F1_log = []\n TPR_log = []\n FPR_log = []\n\n for iprc in np.arange(0,100,1):\n ithr = np.percentile(all_distances, iprc)\n TP = np.sum(distances_pos <= ithr)\n FP = np.sum(distances_neg <= ithr)\n FN = np.sum(distances_pos > ithr)\n TN = np.sum(distances_neg > ithr)\n\n precision = TP / (TP + FP)\n recall = TP / (TP + FN)\n print(precision, recall)\n F1 = 2 * precision * recall / (precision + recall)\n\n TPR = TP / (TP + FN)\n FPR = FP / (FP + TN)\n\n precision_log += [precision]\n recall_log += [recall]\n F1_log += [F1]\n TPR_log += [TPR]\n FPR_log += [FPR]\n\n return precision_log, recall_log, F1_log, FPR_log, TPR_log\n\ndef get_batch(stimulus, responses, batch_size=100, batch_neg_resp=100,\n stim_history=30, min_window=10):\n \"\"\"Get a batch of training data.\"\"\"\n\n stim = stimulus\n resp = responses\n\n t_max = np.minimum(stim.shape[0], resp.shape[0])\n stim_batch = np.zeros((batch_size, stim.shape[1],\n stim.shape[2], stim_history))\n resp_batch = np.zeros((batch_size, resp.shape[1]))\n\n random_times = np.random.randint(stim_history, t_max - 1, batch_size)\n for isample in range(batch_size):\n itime = random_times[isample]\n stim_batch[isample, :, :, :] = np.transpose(stim[itime:\n itime-stim_history:-1,\n :, :],\n [1, 2, 0])\n resp_batch[isample, :] = resp[itime, :]\n\n # get negative responses.\n resp_batch_neg = np.zeros((batch_neg_resp, resp.shape[1]))\n for isample in range(batch_neg_resp):\n itime = np.random.randint(stim_history, t_max - 1, 1)\n while np.min(np.abs(itime - random_times)) < min_window:\n itime = np.random.randint(stim_history, t_max - 1, 1)\n resp_batch_neg[isample, :] = resp[itime, :]\n\n return stim_batch, resp_batch, resp_batch_neg\n\ndef give_cell_grid(centers, resolution, dimx=80, dimy=40):\n \"\"\"Embeds each center on a discrete grid.\n\n Args:\n centers: center location of cells (n_cells x 2).\n resolution: Float specifying the resolution of grid.\n\n Returns:\n centers_grid : Discretized centers (n_cells x 2).\n grid_size : dimensions of the grid (2D integer tuple).\n map_cell_grid : mapping between cells to grid (grid_x x grid_y x n_cells)\n \"\"\"\n\n n_cells = centers.shape[0]\n centers_grid = np.floor(centers -1 / resolution) # subtract 1 because matlab indexing starts from 1.\n # centers_grid -= np.min(centers_grid, 0)\n grid_size =[dimx, dimy]\n\n # map_cell_grid is location of each cell to grid point\n map_cell_grid = np.zeros((grid_size[0], grid_size[1], n_cells))\n for icell in range(n_cells):\n map_cell_grid[centers_grid[icell, 0], centers_grid[icell, 1], icell] = 1\n\n return centers_grid, grid_size, map_cell_grid\n\n## Initialize and do saving, etc\ndef initialize_model(save_folder, file_name, sess):\n \"\"\"Setup model variables and saving information.\n\n Args:\n save_folder (string) : Folder to store model.\n Makes one if it does not exist.\n filename (string) : Prefix of model/checkpoint files.\n sess : Tensorflow session.\n \"\"\"\n\n # Make folder.\n if not gfile.IsDirectory(save_folder):\n gfile.MkDir(save_folder)\n\n # Initialize variables.\n saver_var, start_iter = initialize_variables(sess, save_folder, file_name)\n return saver_var, start_iter\n\ndef initialize_variables(sess, save_folder, short_filename):\n \"\"\"Initialize variables or restore from previous fits.\"\"\"\n\n sess.run(tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer()))\n saver_var = tf.train.Saver(tf.global_variables(),\n keep_checkpoint_every_n_hours=20)\n load_prev = False\n start_iter = 0\n try:\n # Restore previous fits if they are available\n # - useful when programs are preempted frequently on .\n latest_filename = short_filename + '_latest_fn'\n restore_file = tf.train.latest_checkpoint(save_folder,\n latest_filename)\n # Restore previous iteration count and start from there.\n start_iter = int(restore_file.split('/')[-1].split('-')[-1])\n saver_var.restore(sess, restore_file) # restore variables\n load_prev = True\n except:\n tf.logging.info('No previous dataset')\n\n if load_prev:\n tf.logging.info('Previous results loaded from: ' + restore_file)\n else:\n tf.logging.info('Variables initialized')\n\n tf.logging.info('Loaded iteration: %d' % start_iter)\n\n return saver_var, start_iter\n\ndef save_model(saver_var, save_folder, file_name, sess, iiter):\n \"\"\"Save model variables.\"\"\"\n latest_filename = file_name + '_latest_fn'\n long_filename = os.path.join(save_folder, file_name)\n saver_var.save(sess, long_filename, global_step=iiter,\n latest_filename=latest_filename)\n\ndef process_dataset(iresp, dimx, dimy, num_cell_types):\n \"\"\"Process the dataset\"\"\"\n valid_cells0 = np.logical_and(iresp['centers'][:, 0]<=dimx, iresp['centers'][:, 1]<=dimy)\n valid_cells1 = np.logical_and(iresp['centers'][:, 0]>0, iresp['centers'][:, 1]>0)\n valid_cells = np.logical_and(valid_cells0, valid_cells1)\n\n iresp['centers'] = iresp['centers'][valid_cells, :]\n try:\n iresp['sta_params'] = iresp['sta_params'][valid_cells, :]\n except:\n print('No STA params')\n\n try:\n iresp['responses'] = iresp['responses'][:, valid_cells]\n mean_resp = np.mean(iresp['responses'], 0)\n except :\n print('No responses')\n\n try:\n iresp['repeats'] = iresp['repeats'][:, :, valid_cells]\n mean_resp = np.mean(np.mean(iresp['repeats'], 0), 0)\n except :\n print('No repeats')\n\n try:\n iresp['cellID_list'] = iresp['cellID_list'][:, valid_cells]\n except:\n print('No cell ID list')\n\n iresp['cell_type'] = iresp['cell_type'][:, valid_cells]\n print('Valid cells: %d/%d' % (np.sum(valid_cells), valid_cells.shape[0]))\n\n # compute mean firing rate for cells\n n_cells = np.squeeze(iresp['centers']).shape[0]\n\n\n # do embedding of centers on a grid\n # TODO(bhaishahster): compute centers from stim-resp here itself ?\n centers_grid, grid_size, map_cell_grid = give_cell_grid(iresp['centers'],\n resolution=1)\n\n # encode cell type as 1-hot vector\n ctype_1hot = np.zeros((n_cells, num_cell_types))\n for icell_type in np.arange(1, num_cell_types+1):\n ctype_1hot[:, icell_type-1] = np.double(iresp['cell_type'] == icell_type)\n\n iresp.update({'mean_firing_rate': mean_resp,\n 'map_cell_grid': map_cell_grid,\n 'ctype_1hot': ctype_1hot})\n\ndef embed_stimulus(layers, batch_norm, net, is_training, reuse_variables=False):\n n_layers = int(len(layers)/3)\n tf.logging.info('Number of layers: %d' % n_layers)\n # set normalization\n if batch_norm:\n normalizer_fn = slim.batch_norm\n tf.logging.info('Batch normalization')\n else:\n normalizer_fn = None\n\n activation_fn = tf.nn.softplus\n tf.logging.info('Logistic activation')\n\n for ilayer in range(n_layers):\n tf.logging.info('Building layer: %d, %d, %d'\n % (int(layers[ilayer*3 + 1]), int(layers[ilayer*3]),\n int(layers[ilayer*3 + 2])))\n net = slim.conv2d(net, int(layers[ilayer*3 + 1]),\n int(layers[ilayer*3]),\n stride=int(layers[ilayer*3 + 2]),\n scope='stim_layer_wt_%d' % ilayer,\n reuse=reuse_variables,\n normalizer_fn=normalizer_fn,\n activation_fn=activation_fn,\n normalizer_params={'is_training': is_training},\n )\n return net\n\ndef analyse_response_repeats(repeats_data, anchor_model, neg_model, sess):\n # generate positive examples of resposnes - responses at same time, different repeats\n\n def get_feed_dict(responses1, responses2, anchor_model, neg_model, repeats_data):\n feed_dict = {anchor_model.responses_tf: np.expand_dims(responses1, 2),\n neg_model.responses_tf: np.expand_dims(responses2, 2),\n\n anchor_model.map_cell_grid_tf: repeats_data['map_cell_grid'],\n anchor_model.cell_types_tf: repeats_data['ctype_1hot'],\n anchor_model.mean_fr_tf: repeats_data['mean_firing_rate'],\n\n neg_model.map_cell_grid_tf: repeats_data['map_cell_grid'],\n neg_model.cell_types_tf: repeats_data['ctype_1hot'],\n neg_model.mean_fr_tf: repeats_data['mean_firing_rate']}\n return feed_dict\n\n dist_ap_log = np.array([])\n dist_an_log = np.array([])\n for iibatch in range(100):\n print(iibatch)\n pos_batch = 100\n pos_times = np.random.randint(0, repeats_data['repeats'].shape[1], pos_batch)\n\n pos_trials = np.zeros((pos_batch, 2))\n pos_trials[:, 0] = np.random.randint(0, repeats_data['repeats'].shape[0], pos_batch)\n for isample in range(pos_batch):\n irep = np.random.randint(0, repeats_data['repeats'].shape[0], 1)\n while pos_trials[isample, 0] == irep:\n irep = np.random.randint(0, repeats_data['repeats'].shape[0], 1)\n pos_trials[isample, 1] = irep\n\n neg_times = np.random.randint(0, repeats_data['repeats'].shape[1], pos_batch)\n neg_trials = np.random.randint(0, repeats_data['repeats'].shape[0], pos_batch)\n\n # anchor, pos\n responses1 = repeats_data['repeats'][pos_trials[:, 0].astype(np.int), pos_times, :]\n responses2 = repeats_data['repeats'][pos_trials[:, 1].astype(np.int), pos_times, :]\n resp_anch, resp_pos = sess.run([anchor_model.responses_embed,\n neg_model.responses_embed],\n feed_dict=get_feed_dict(responses1, responses2,\n anchor_model, neg_model,\n repeats_data))\n dist_ap = np.sum((resp_anch - resp_pos)**2, (1, 2, 3))\n\n # anchor, neg\n responses1 = repeats_data['repeats'][pos_trials[:, 0].astype(np.int), pos_times, :]\n responses2 = repeats_data['repeats'][neg_trials.astype(np.int), neg_times, :]\n resp_anch2, resp_neg = sess.run([anchor_model.responses_embed,\n neg_model.responses_embed],\n feed_dict=get_feed_dict(responses1, responses2,\n anchor_model, neg_model,\n repeats_data))\n dist_an = np.sum((resp_anch - resp_neg)**2, (1, 2, 3))\n\n dist_ap_log = np.append(dist_ap_log, dist_ap)\n dist_an_log = np.append(dist_an_log, dist_an)\n\n precision_log, recall_log, F1_log, FPR_log, TPR_log = ROC(dist_ap_log, dist_an_log)\n\n print(np.sum(dist_ap_log < dist_an_log))\n print(np.sum(dist_ap_log > dist_an_log))\n print(np.sum(dist_ap_log == dist_an_log))\n test_reps = {'precision': precision_log, 'recall': recall_log,\n 'F1': F1_log, 'FPR': FPR_log, 'TPR': TPR_log,\n 'd_pos_log': dist_ap_log, 'd_neg_log': dist_an_log}\n return test_reps\n\ndef analyse_response_repeats_all_trials(repeats_data, anchor_model, neg_model, sess):\n # generate positive examples of resposnes - responses at same time, different repeats\n\n prng = RandomState(50)\n\n n_trials = repeats_data['repeats'].shape[0]\n n_random_times = 10\n random_times = prng.randint(0, repeats_data['repeats'].shape[1], n_random_times)\n responses = repeats_data['repeats'][:, random_times, :].astype(np.float32)\n responses = np.transpose(responses, [1, 0, 2])\n responses = np.reshape(responses, [n_trials * n_random_times, responses.shape[2]]).astype(np.float32)\n stim_idx = np.repeat(np.arange(n_random_times), n_trials, 0)\n\n # embed a sample response to get dimensions\n feed_dict = {anchor_model.map_cell_grid_tf: repeats_data['map_cell_grid'],\n anchor_model.cell_types_tf: repeats_data['ctype_1hot'],\n anchor_model.mean_fr_tf: repeats_data['mean_firing_rate'],\n anchor_model.responses_tf: np.expand_dims(responses[0:100, :], 2)}\n resp_test = sess.run(anchor_model.responses_embed, feed_dict=feed_dict)\n resp_embed = np.zeros((responses.shape[0],\n resp_test.shape[1],\n resp_test.shape[2], 1))\n\n # embed the responses\n # since we use batch norm in testing, we need to jumble the response to get correct estimate of batch norm statistics\n tms = np.arange(responses.shape[0])\n tms_jumble = np.random.permutation(tms)\n\n batch_sz = 100\n for itm in np.arange(0, tms_jumble.shape[0], batch_sz):\n print(itm)\n feed_dict = {anchor_model.map_cell_grid_tf: repeats_data['map_cell_grid'],\n anchor_model.cell_types_tf: repeats_data['ctype_1hot'],\n anchor_model.mean_fr_tf: repeats_data['mean_firing_rate'],\n anchor_model.responses_tf: np.expand_dims(responses[tms_jumble[itm: itm+batch_sz], :], 2)}\n resp_embed[tms_jumble[itm: itm+batch_sz], :, :, :] = sess.run(anchor_model.responses_embed, feed_dict=feed_dict)\n\n # compute distance between pairs of responses\n distances = np.zeros((responses.shape[0], responses.shape[0]))\n distances_euclidean = np.zeros((responses.shape[0], responses.shape[0]))\n batch_dist = np.int(100)\n for iresp in np.arange(0, distances.shape[0], batch_dist):\n print(iresp)\n for jresp in np.arange(0, distances.shape[1], batch_dist):\n r1 = np.expand_dims(resp_embed[iresp: iresp+batch_dist], 1)\n r2 = np.expand_dims(resp_embed[jresp: jresp+batch_dist], 0)\n distances[iresp: iresp+batch_dist, jresp: jresp+batch_dist] = np.sum((r1-r2)**2, (2, 3, 4))\n\n rr1 = np.expand_dims(responses[iresp: iresp + batch_dist], 1)\n rr2 = np.expand_dims(responses[jresp: jresp + batch_dist], 0)\n distances_euclidean[iresp: iresp+batch_dist, jresp: jresp+batch_dist] = np.sum((rr1 - rr2)**2, 2)\n\n test_clustering = {'distances': distances,\n 'responses': responses,\n 'stim_idx': stim_idx,\n 'resp_embed': resp_embed,\n 'random_times': random_times,\n 'distances_euclidean': distances_euclidean}\n\n return test_clustering\n\nif __name__ == '__main__':\n app.run(main)\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# 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\"\"\"One-line documentation for few_cells_tf_analyse_roc module.\n\nA detailed description of few_cells_tf_analyse_roc.\n\"\"\"\n\n\nimport sys\nimport os.path\nimport tensorflow as tf\nfrom absl import app\nfrom absl import flags\nfrom absl import gfile\nimport cPickle as pickle\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib import pylab\nimport matplotlib.pyplot as plt\n\nimport numpy as np, h5py\nimport scipy.io as sio\nfrom scipy import ndimage\nimport random\nimport re # regular expression matching\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('folder_name', 'experiment4', 'folder where to store all the data')\n\nflags.DEFINE_string('save_location',\n '/home/bhaishahster/',\n 'where to store logs and outputs?');\nflags.DEFINE_string('data_location',\n '/home/bhaishahster/data_breakdown/',\n 'where to take data from?')\nflags.DEFINE_integer('batchsz', 500, 'batch size for training')\nflags.DEFINE_integer('n_chunks', 216, 'number of data chunks') # should be 216\nflags.DEFINE_integer('n_b_in_c', 2, 'number of batches in one chunk of data')\nflags.DEFINE_integer('np_randseed', 23, 'numpy RNG seed')\nflags.DEFINE_integer('randseed', 65, 'python RNG seed')\nflags.DEFINE_integer('ratio_SU', 2, 'ratio of subunits/cells')\nflags.DEFINE_float('step_sz', 1, 'step size for learning algorithm')\nflags.DEFINE_string('model_id', 'poisson', 'which model to fit')\nFLAGS = flags.FLAGS\n\n# global vars\ncells_choose = np.array([])\nchosen_mask = np.array([])\n\ndef get_test_data():\n # stimulus.astype('float32')[216000-1000: 216000-1, :]\n # response.astype('float32')[216000-1000: 216000-1, :]\n # length\n global chosen_mask\n global cells_choose\n stim_part = np.array([]).reshape(0,np.sum(chosen_mask))\n resp_part = np.array([]).reshape(0,np.sum(cells_choose))\n\n test_data_chunks = np.arange(FLAGS.n_chunks-20, FLAGS.n_chunks+1);\n for ichunk in test_data_chunks:\n filename = FLAGS.data_location + 'Off_par_data_' + str(ichunk) + '.mat'\n file_r = gfile.Open(filename, 'r')\n data = sio.loadmat(file_r)\n\n s = data['maskedMovdd_part'].T\n r = data['Y_part'].T\n print(np.shape(s))\n print(np.shape(stim_part))\n stim_part = np.append(stim_part,s[:, chosen_mask] , axis=0)\n resp_part = np.append(resp_part,r[:, cells_choose] , axis=0)\n\n test_len = stim_part.shape[0]\n return stim_part, resp_part, test_len\n\ndef get_latest_file(save_location, short_filename): # get relevant files\n file_list = gfile.ListDirectory(save_location)\n print(save_location, short_filename)\n save_filename = save_location + short_filename\n print('\\nLoading: ', save_filename)\n bin_files = []\n meta_files = []\n for file_n in file_list:\n if re.search(short_filename + '.', file_n):\n if re.search('.meta', file_n):\n meta_files += [file_n]\n else:\n bin_files += [file_n]\n # print(bin_files)\n print(len(meta_files), len(bin_files), len(file_list))\n\n # get iteration numbers\n iterations = np.array([])\n for file_name in bin_files:\n try:\n iterations = np.append(iterations, int(file_name.split('/')[-1].split('-')[-1]))\n except:\n print('Could not load filename: ' + file_name)\n iterations.sort()\n print(iterations)\n\n iter_plot = iterations[-1]\n print(int(iter_plot))\n restore_file = save_filename + '-' + str(int(iter_plot))\n return restore_file\n\ndef main(argv):\n print('\\nCode started')\n\n np.random.seed(FLAGS.np_randseed)\n random.seed(FLAGS.randseed)\n global chosen_mask\n global cells_choose\n\n ## Load data summary\n\n filename = FLAGS.data_location + 'data_details.mat'\n summary_file = gfile.Open(filename, 'r')\n data_summary = sio.loadmat(summary_file)\n cells = np.squeeze(data_summary['cells'])\n cells_choose = (cells ==3287) | (cells ==3318 ) | (cells ==3155) | (cells ==3066)\n n_cells = np.sum(cells_choose)\n\n tot_spks = np.squeeze(data_summary['tot_spks'])\n total_mask = np.squeeze(data_summary['totalMaskAccept_log']).T\n tot_spks_chosen_cells = tot_spks[cells_choose]\n chosen_mask = np.array(np.sum(total_mask[cells_choose,:],0)>0, dtype='bool')\n print(np.shape(chosen_mask))\n print(np.sum(chosen_mask))\n\n stim_dim = np.sum(chosen_mask)\n # get test data\n stim_test,resp_test,test_length = get_test_data()\n\n print('\\ndataset summary loaded')\n # use stim_dim, chosen_mask, cells_choose, tot_spks_chosen_cells, n_cells\n\n # decide the number of subunits to fit\n n_su = FLAGS.ratio_SU*n_cells\n\n # saving details\n #short_filename = 'data_model=ASM_pop_bg'\n # short_filename = ('data_model=ASM_pop_batch_sz='+ str(FLAGS.batchsz) + '_n_b_in_c' + str(FLAGS.n_b_in_c) +\n # '_step_sz'+ str(FLAGS.step_sz)+'_bg')\n\n # saving details\n batchsz = np.array([1000, 1000, 1000], dtype='int')\n n_b_in_c = np.array([1, 1, 1], dtype='int')\n step_sz = np.array([1, 1, 1], dtype='float32')\n folder_names = ['experiment25', 'experiment22', 'experiment23']\n roc_data = [[]] * n_cells\n for icnt, FLAGS.model_id in enumerate(['hinge', 'poisson', 'logistic']):\n # restore file\n FLAGS.batchsz = batchsz[icnt]\n FLAGS.n_b_in_c = n_b_in_c[icnt]\n FLAGS.step_sz = step_sz[icnt]\n folder_name = folder_names[icnt]\n if FLAGS.model_id == 'poisson':\n short_filename = ('data_model=ASM_pop_batch_sz='+ str(FLAGS.batchsz) + '_n_b_in_c' + str(FLAGS.n_b_in_c) +\n '_step_sz'+ str(FLAGS.step_sz)+'_bg')\n\n if FLAGS.model_id == 'poisson_full':\n short_filename = ('data_model=' + str(FLAGS.model_id) + '_batch_sz='+ str(FLAGS.batchsz) + '_n_b_in_c' + str(FLAGS.n_b_in_c) +\n '_step_sz'+ str(FLAGS.step_sz)+'_bg')\n\n if FLAGS.model_id == 'logistic' or FLAGS.model_id == 'hinge':\n short_filename = ('data_model='+ str(FLAGS.model_id) +'_batch_sz='+ str(FLAGS.batchsz) + '_n_b_in_c' + str(FLAGS.n_b_in_c) +\n '_step_sz'+ str(FLAGS.step_sz)+'_bg')\n\n\n print(FLAGS.model_id)\n parent_folder = FLAGS.save_location + folder_name + '/'\n save_location = parent_folder +short_filename + '/'\n restore_file = get_latest_file(save_location, short_filename)\n\n\n tf.reset_default_graph()\n with tf.Session() as sess:\n # Learn population model!\n stim = tf.placeholder(tf.float32, shape=[None, stim_dim], name='stim')\n resp = tf.placeholder(tf.float32, name='resp')\n data_len = tf.placeholder(tf.float32, name='data_len')\n\n\n # define models\n if FLAGS.model_id == 'poisson' or FLAGS.model_id == 'poisson_full':\n w = tf.Variable(np.array(0.01 * np.random.randn(stim_dim, n_su), dtype='float32'))\n a = tf.Variable(np.array(0.01 * np.random.rand(n_cells, 1, n_su), dtype='float32'))\n z = tf.transpose(tf.reduce_sum(tf.exp(tf.matmul(stim, w) + a), 2))\n \n if FLAGS.model_id == 'logistic' or FLAGS.model_id == 'hinge':\n w = tf.Variable(np.array(0.01 * np.random.randn(stim_dim, n_su), dtype='float32'))\n a = tf.Variable(np.array(0.01 * np.random.rand(n_su, n_cells), dtype='float32'))\n b_init = np.random.randn(n_cells) #np.log((np.sum(response,0))/(response.shape[0]-np.sum(response,0)))\n b = tf.Variable(b_init,dtype='float32')\n z = tf.matmul(tf.nn.relu(tf.matmul(stim, w)), a) + b\n\n # restore variables\n # load tensorflow variables\n print(tf.all_variables())\n saver_var = tf.train.Saver(tf.all_variables())\n saver_var.restore(sess, restore_file)\n fd_test = {stim: stim_test,\n resp: resp_test,\n data_len: test_length}\n\n z_eval = sess.run(z, feed_dict=fd_test)\n print(z_eval[0:20, :])\n print(resp_test[0:20, :])\n\n for roc_cell in np.arange(n_cells):\n roc = get_roc(z_eval[:, roc_cell], resp_test[:, roc_cell])\n roc_data[roc_cell] = roc_data[roc_cell] + [roc]\n print(roc_cell)\n\n plt.figure()\n for icell in range(n_cells):\n plt.subplot(1, n_cells, icell+1)\n for icnt in np.arange(3):\n plt.plot(roc_data[icell][icnt][0], roc_data[icell][icnt][1])\n plt.hold(True)\n plt.xlabel('recall')\n plt.ylabel('precision')\n plt.legend(['hinge', 'poisson' ,'logistic'])\n cells_ch = cells[cells_choose]\n plt.title(cells_ch[icell])\n plt.show()\n plt.draw()\n\n\ndef get_roc(fr, resp):\n print(np.shape(fr), np.shape(resp))\n r_curve = np.array([])\n p_curve = np.array([])\n for iprctile in np.arange(0,100, 2):\n thr = np.percentile(fr, iprctile)\n recall = np.sum(np.bitwise_and(fr > thr, resp > 0).astype('double')) / np.sum((resp>0).astype('double'))\n precision = np.sum(np.bitwise_and(fr > thr, resp > 0).astype('double')) / np.sum((fr > thr).astype('double'))\n\n r_curve = np.append(r_curve, recall)\n p_curve = np.append(p_curve, precision)\n\n return [r_curve, p_curve]\n\nif __name__ == '__main__':\n app.run()\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# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nr\"\"\"Jointly embed stimulus, response from multiple retina.\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os.path\nimport numpy as np\nimport random\nimport tensorflow as tf\nfrom tensorflow.python.client.model_analyzer import PrintModelAnalysis\nfrom absl import app\nfrom absl import gfile\nimport retina.response_model.python.metric_learning.end_to_end.bookkeeping as bookkeeping\n# pylint: disable-unused-import\nimport retina.response_model.python.metric_learning.end_to_end.config as config # defines all the flags\n# pylint: enable-unused-import\nimport retina.response_model.python.metric_learning.end_to_end.data_util as data_util\nimport retina.response_model.python.metric_learning.end_to_end.partitions as partitions\nimport retina.response_model.python.metric_learning.end_to_end.prosthesis as prosthesis\nimport retina.response_model.python.metric_learning.end_to_end.sr_embedding_models as sr_models\nimport retina.response_model.python.metric_learning.end_to_end.sr_embedding_models_experimental as sr_models_expt\nimport retina.response_model.python.metric_learning.end_to_end.encoding_models_experimental as encoding_models_expt\nimport retina.response_model.python.metric_learning.end_to_end.sr_embedding_baseline_models as sr_baseline_models\nimport retina.response_model.python.metric_learning.end_to_end.testing as testing\nimport retina.response_model.python.metric_learning.end_to_end.training as training\nimport retina.response_model.python.metric_learning.end_to_end.sample_datasets as sample_datasets\nimport retina.response_model.python.metric_learning.end_to_end.sample_datasets_2 as sample_datasets_2\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef main(unused_argv=()):\n\n np.random.seed(23)\n tf.set_random_seed(1234)\n random.seed(50)\n\n # Load stimulus-response data.\n # Collect population response across retinas in the list 'responses'.\n # Stimulus for each retina is indicated by 'stim_id',\n # which is found in 'stimuli' dictionary.\n datasets = gfile.ListDirectory(FLAGS.src_dir)\n stimuli = {}\n responses = []\n for icnt, idataset in enumerate(datasets):\n fullpath = os.path.join(FLAGS.src_dir, idataset)\n if gfile.IsDirectory(fullpath):\n key = 'stim_%d' % icnt\n op = data_util.get_stimulus_response(FLAGS.src_dir, idataset, key,\n boundary=FLAGS.valid_cells_boundary,\n if_get_stim=True)\n stimulus, resp, dimx, dimy, _ = op\n stimuli.update({key: stimulus})\n responses += resp\n\n # Get training and testing partitions.\n # Generate partitions\n # The partitions for the taskid should be listed in partition_file.\n\n op = partitions.get_partitions(FLAGS.partition_file, FLAGS.taskid)\n training_datasets, testing_datasets = op\n\n with tf.Session() as sess:\n\n # Get stimulus-response embedding.\n if FLAGS.mode == 0:\n is_training = True\n if FLAGS.mode == 1:\n is_training = True\n if FLAGS.mode == 2:\n is_training = True\n print('NOTE: is_training = True in test')\n if FLAGS.mode == 3:\n is_training = True\n print('NOTE: is_training = True in test')\n\n sample_fcn = sample_datasets\n if (FLAGS.sr_model == 'convolutional_embedding'):\n embedding = sr_models.convolutional_embedding(FLAGS.sr_model, sess,\n is_training,\n dimx, dimy)\n\n if (FLAGS.sr_model == 'convolutional_embedding_expt' or\n FLAGS.sr_model == 'convolutional_embedding_margin_expt' or\n FLAGS.sr_model == 'convolutional_embedding_inner_product_expt' or\n FLAGS.sr_model == 'convolutional_embedding_gauss_expt' or\n FLAGS.sr_model == 'convolutional_embedding_kernel_expt'):\n embedding = sr_models_expt.convolutional_embedding_experimental(\n FLAGS.sr_model, sess, is_training, dimx, dimy)\n\n if FLAGS.sr_model == 'convolutional_autoembedder':\n embedding = sr_models_expt.convolutional_autoembedder(sess, is_training,\n dimx, dimy)\n\n if FLAGS.sr_model == 'convolutional_autoembedder_l2':\n embedding = sr_models_expt.convolutional_autoembedder(sess, is_training,\n dimx, dimy,\n loss='log_sum_exp')\n\n if FLAGS.sr_model == 'convolutional_encoder' or FLAGS.sr_model == 'convolutional_encoder_2':\n embedding = encoding_models_expt.convolutional_encoder(sess, is_training,\n dimx, dimy)\n\n if FLAGS.sr_model == 'convolutional_encoder_using_retina_id':\n model = encoding_models_expt.convolutional_encoder_using_retina_id\n embedding = model(sess, is_training, dimx, dimy, len(responses))\n sample_fcn = sample_datasets_2\n\n if (FLAGS.sr_model == 'residual') or (FLAGS.sr_model == 'residual_inner_product') :\n embedding = sr_models_expt.residual_experimental(FLAGS.sr_model,\n sess, is_training,\n dimx, dimy)\n\n\n if FLAGS.sr_model == 'lin_rank1' or FLAGS.sr_model == 'lin_rank1_blind':\n if ((len(training_datasets) != 1) and\n (training_datasets != testing_datasets)):\n raise ValueError('Identical training/testing data'\n ' (exactly 1) supported')\n\n n_cells = responses[training_datasets[0]]['responses'].shape[1]\n cell_locations = responses[training_datasets[0]]['map_cell_grid']\n cell_masks = responses[training_datasets[0]]['mask_cells']\n firing_rates = responses[training_datasets[0]]['mean_firing_rate']\n cell_type = responses[training_datasets[0]]['cell_type'].squeeze()\n\n model_fn = sr_baseline_models.linear_rank1_models\n embedding = model_fn(FLAGS.sr_model, sess, dimx, dimy, n_cells,\n center_locations=cell_locations,\n cell_masks=cell_masks,\n firing_rates=firing_rates,\n cell_type=cell_type, time_window=30)\n\n # print model graph\n PrintModelAnalysis(tf.get_default_graph())\n\n # Get filename, initialize model\n file_name = bookkeeping.get_filename(training_datasets,\n testing_datasets,\n FLAGS.beta, FLAGS.sr_model)\n tf.logging.info('Filename: %s' % file_name)\n saver_var, start_iter = bookkeeping.initialize_model(FLAGS.save_folder,\n file_name, sess)\n\n # Setup summary ops.\n # Save separate summary for each retina (both training/testing).\n summary_ops = []\n for iret in np.arange(len(responses)):\n r_list = []\n r1 = tf.summary.scalar('loss_%d' % iret, embedding.loss)\n r_list += [r1]\n\n if hasattr(embedding, 'accuracy_tf'):\n r2 = tf.summary.scalar('accuracy_%d' % iret, embedding.accuracy_tf)\n r_list += [r2]\n\n if FLAGS.sr_model == 'convolutional_autoembedder' or FLAGS.sr_model =='convolutional_autoembedder_l2':\n r3 = tf.summary.scalar('loss_triplet_%d' % iret, embedding.loss_triplet)\n r4 = tf.summary.scalar('loss_stim_decode_from_resp_%d' % iret,\n embedding.loss_stim_decode_from_resp)\n r5 = tf.summary.scalar('loss_stim_decode_from_stim_%d' % iret,\n embedding.loss_stim_decode_from_stim)\n r6 = tf.summary.scalar('loss_resp_decode_from_resp_%d' % iret,\n embedding.loss_resp_decode_from_resp)\n r7 = tf.summary.scalar('loss_resp_decode_from_stim_%d' % iret,\n embedding.loss_resp_decode_from_stim)\n r_list += [r3, r4, r5, r6, r7]\n \n '''\n chosen_stim = 2\n bound = FLAGS.valid_cells_boundary\n \n r8 = tf.summary.image('stim_decode_from_stim_%d' % iret,\n tf.expand_dims(tf.expand_dims(embedding.stim_decode_from_stim[chosen_stim, bound:80-bound, bound:40-bound, 3], 0), 3))\n\n r9 = tf.summary.image('stim_decode_from_resp_%d' % iret,\n tf.expand_dims(tf.expand_dims(embedding.stim_decode_from_resp[chosen_stim, bound:80-bound, bound:40-bound, 3], 0), 3))\n\n r10 = tf.summary.image('resp_decode_from_stim_chann0_%d' % iret,\n tf.expand_dims(tf.expand_dims(embedding.resp_decode_from_stim[chosen_stim, bound:80-bound, bound:40-bound, 0], 0), 3))\n\n r11 = tf.summary.image('resp_decode_from_resp_chann0_%d' % iret,\n tf.expand_dims(tf.expand_dims(embedding.resp_decode_from_resp[chosen_stim, bound:80-bound, bound:40-bound, 0], 0), 3))\n\n r12 = tf.summary.image('resp_decode_from_stim_chann1_%d' % iret,\n tf.expand_dims(tf.expand_dims(embedding.resp_decode_from_stim[chosen_stim, bound:80-bound, bound:40-bound, 1], 0), 3))\n\n r13 = tf.summary.image('resp_decode_from_resp_chann1_%d' % iret,\n tf.expand_dims(tf.expand_dims(embedding.resp_decode_from_resp[chosen_stim, bound:80-bound, bound:40-bound, 1], 0), 3))\n\n r14 = tf.summary.image('resp_chann0_%d' % iret,\n tf.expand_dims(tf.expand_dims(embedding.anchor_model.responses_embed_1[chosen_stim, bound:80-bound, bound:40-bound, 0], 0), 3))\n\n r15 = tf.summary.image('resp_chann1_%d' % iret,\n tf.expand_dims(tf.expand_dims(embedding.anchor_model.responses_embed_1[chosen_stim, bound:80-bound, bound:40-bound, 1], 0), 3))\n\n r_list += [r8, r9, r10, r11, r12, r13, r14, r15]\n '''\n\n summary_ops += [tf.summary.merge(r_list)]\n\n # Setup summary writers.\n summary_writers = []\n for loc in ['train', 'test']:\n summary_location = os.path.join(FLAGS.save_folder, file_name,\n 'summary_' + loc)\n summary_writer = tf.summary.FileWriter(summary_location, sess.graph)\n summary_writers += [summary_writer]\n\n # Separate tests for encoding or metric learning,\n # prosthesis usage or just neuroscience usage.\n if FLAGS.mode == 3:\n testing.test_encoding(training_datasets, testing_datasets,\n responses, stimuli,\n embedding, sess, file_name, sample_fcn)\n\n elif FLAGS.mode == 2:\n prosthesis.stimulate(embedding, sess, file_name, dimx, dimy)\n\n elif FLAGS.mode == 1:\n testing.test_metric(training_datasets, testing_datasets,\n responses, stimuli,\n embedding, sess, file_name)\n\n else:\n training.training(start_iter, sess, embedding, summary_writers,\n summary_ops, saver_var,\n training_datasets, testing_datasets,\n responses, stimuli, file_name, sample_fcn,\n summary_freq=500, save_freq=500)\n\n\nif __name__ == '__main__':\n app.run(main)\n"
] |
[
[
"numpy.sqrt",
"numpy.squeeze",
"numpy.max",
"numpy.int",
"tensorflow.python.platform.gfile.Exists",
"numpy.mean",
"tensorflow.python.platform.gfile.IsDirectory",
"numpy.where",
"numpy.double",
"numpy.unique",
"numpy.arange",
"scipy.io.loadmat",
"tensorflow.python.platform.gfile.MkDir",
"tensorflow.python.platform.gfile.DeleteRecursively",
"numpy.zeros",
"tensorflow.python.platform.gfile.ListDirectory",
"numpy.min",
"tensorflow.python.platform.gfile.Copy",
"tensorflow.logging.info",
"numpy.floor",
"numpy.logical_and",
"numpy.sum"
],
[
"tensorflow.nn.relu",
"tensorflow.train.AdagradOptimizer",
"tensorflow.contrib.slim.arg_scope",
"tensorflow.reduce_sum",
"tensorflow.minimum",
"tensorflow.reshape",
"tensorflow.placeholder",
"numpy.int",
"tensorflow.logging.info"
],
[
"numpy.diag",
"numpy.expand_dims",
"numpy.minimum",
"tensorflow.reduce_sum",
"numpy.squeeze",
"tensorflow.global_variables",
"numpy.int",
"numpy.max",
"numpy.mean",
"tensorflow.get_default_graph",
"tensorflow.summary.scalar",
"numpy.double",
"numpy.random.randint",
"numpy.reshape",
"numpy.arange",
"scipy.io.loadmat",
"tensorflow.Session",
"tensorflow.trainable_variables",
"numpy.zeros",
"tensorflow.train.AdagradOptimizer",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"numpy.append",
"tensorflow.logging.info",
"numpy.floor",
"numpy.transpose",
"numpy.argsort",
"numpy.array",
"numpy.logical_and",
"numpy.random.RandomState",
"numpy.sum",
"tensorflow.summary.merge",
"tensorflow.train.latest_checkpoint",
"tensorflow.summary.FileWriter",
"tensorflow.local_variables_initializer",
"numpy.abs",
"matplotlib.use",
"tensorflow.expand_dims",
"numpy.percentile",
"numpy.random.permutation"
],
[
"matplotlib.pyplot.legend",
"numpy.squeeze",
"matplotlib.pyplot.hold",
"matplotlib.pyplot.plot",
"numpy.random.randn",
"tensorflow.all_variables",
"tensorflow.Variable",
"numpy.arange",
"scipy.io.loadmat",
"tensorflow.reset_default_graph",
"matplotlib.pyplot.subplot",
"tensorflow.Session",
"matplotlib.pyplot.figure",
"tensorflow.matmul",
"matplotlib.pyplot.title",
"tensorflow.placeholder",
"numpy.append",
"numpy.random.rand",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.sum",
"matplotlib.pyplot.ylabel",
"numpy.random.seed",
"matplotlib.use",
"numpy.percentile",
"matplotlib.pyplot.draw",
"numpy.bitwise_and",
"numpy.shape",
"matplotlib.pyplot.xlabel"
],
[
"tensorflow.summary.FileWriter",
"numpy.random.seed",
"tensorflow.logging.info",
"tensorflow.Session",
"tensorflow.set_random_seed",
"tensorflow.get_default_graph",
"tensorflow.summary.scalar",
"tensorflow.summary.merge"
]
] |
[
{
"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": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"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": [
"1.10"
]
},
{
"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": [
"1.10",
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
agatak8/AAL-GraphTriangles
|
[
"3d738e38bef840abd9a50aa68182db6d4be32ab6"
] |
[
"algorithms/solvers.py"
] |
[
"# Agata Kłoss\n# znalezienie liczby trójkątów w grafie\n\nimport algorithms.graph as graph\nimport numpy as np\n\n\n# O(n^5)\ndef naive(vertices, edges, only_count=False):\n def has_edge(i, j, edges):\n for edge in edges:\n if (edge[0] == i and edge[1] == j) or (edge[0] == j and edge[1] == i):\n return True\n return False\n\n # O(n^5)\n def sub_solve(vertices, edges):\n v = list(vertices) # O(N)\n results = []\n count = 0\n\n # this for loop format guarantees no duplicate triangles\n for i in range(0, len(v)):\n for j in range(i + 1, len(v)):\n for k in range(j + 1, len(v)):\n # has_edge is O(len(edges)), up to O(n^2)\n if has_edge(v[i], v[j], edges) and has_edge(v[i], v[k], edges) and has_edge(v[j], v[k], edges):\n if only_count:\n count += 1\n else:\n results.append({v[i], v[j], v[k]})\n if only_count:\n return count\n else:\n return results\n\n complement_edges = []\n # O(n^4)\n for i in range(len(vertices) - 1):\n for j in range(i + 1, len(vertices)):\n if not has_edge(i, j, edges):\n complement_edges.append((i, j))\n return sub_solve(vertices, edges) + sub_solve(vertices, complement_edges)\n\n\n# O(n^3) because numpy's matrix multiplication, but it is heavily optimized for modern processors\ndef matrix(vertices, edges, dummy_arg=None):\n vertex_dict = {}\n i = 0\n for v in vertices:\n vertex_dict[v] = i\n i += 1\n m1 = np.matrix(np.zeros((i, i), dtype=np.int))\n for edge in edges:\n v1 = edge[0]\n v2 = edge[1]\n m1[vertex_dict[v1], vertex_dict[v2]] = m1[vertex_dict[v2], vertex_dict[v1]] = 1\n m2 = m1 ^ 1\n for i in range(len(vertices)):\n m2[i, i] = 0\n return int(((m1 ** 3).trace() / 6 + (m2 ** 3).trace() / 6)[0, 0])\n\n\n# avg O(n^3), worst O(n^4)\ndef adj_list(vertices, edges, only_count=False):\n def sub_solve(graph):\n count = 0\n results = []\n for v1 in vertices:\n n = list(graph.neighbors(v1))\n # check for each unique neighbor pair if it has an edge\n for v2 in range(0, len(n) - 1):\n for v3 in range(v2 + 1, len(n)):\n # avg O(1) worst O(n)\n if graph.has_edge(n[v2], n[v3]):\n if only_count:\n count += 1\n else:\n results.append((v1, n[v2], n[v3]))\n # remove checked vertex from other vertices's lists\n graph.remove_vertex(v1)\n if only_count:\n return count\n else:\n return results\n\n g1 = graph.AdjacencyList(vertices, edges)\n g2 = g1.get_complement()\n s1 = sub_solve(g1)\n s2 = sub_solve(g2)\n return s1 + s2\n\n\n# avg O(n^3), worst O(n^4)\ndef degree(vertices, edges, only_count=False):\n def sub_solve(graph):\n # O(1)\n # update degrees in list and make sure the list is sorted\n # rather than sort the whole list again, you can just swap at most once if needed\n def update_neighbor(v):\n v[0][1] -= 1\n index = v[1]\n if index > 0 and vd_list[index - 1][1] > v[0][1]:\n vd_list[index], vd_list[index - 1] = vd_list[index - 1], vd_list[index]\n\n results = set()\n # O(n)\n # list of pairs vertex,degree(vertex)\n vd_list = [[v, graph.degree(v)] for v in graph.vertices()]\n # O(nlgn)\n vd_list.sort(key=lambda x: x[1])\n vd_count = len(vd_list)\n # avg O(n^3), worst O(n^4)\n for i in range(vd_count):\n vd = vd_list.pop(0)\n # O(n)\n # keep the vertex's index in the list for faster access\n neighbors = [(vd_list[i], i) for i in range(0, len(vd_list)) if graph.has_edge(vd[0], vd_list[i][0])]\n if vd[1] >= 2:\n # avg O(n^2), worst O(n^3)\n for v2 in neighbors:\n if v2[0][1] == 1:\n continue\n # avg O(min(deg v1, deg v2)) ~= O(n), worst O(deg v1 * deg v2) ~= O(n^2)\n common_neighbors = graph.neighbors(vd[0]) & graph.neighbors(v2[0][0])\n # avg O(n), worst O(n^2)\n for v3 in common_neighbors:\n results.add(frozenset((vd[0], v2[0][0], v3)))\n update_neighbor(v2)\n else:\n for v in neighbors:\n update_neighbor(v)\n graph.remove_vertex(vd[0])\n return results\n\n g1 = graph.AdjacencyList(vertices, edges)\n g2 = g1.get_complement()\n s1 = sub_solve(g1)\n s2 = sub_solve(g2)\n if only_count:\n return len(s1) + len(s2)\n else:\n return s1 | s2\n\n\n# available algorithms\nalgs = {\"naive\": naive, \"matrix\": matrix, \"list\": adj_list, \"degree\": degree}\n\n# their theoretical complexities - all assume average case\ncomplexities = {\"naive\": lambda n: n ** 5, \"matrix\": lambda n: n ** 3,\n \"list\": lambda n: n ** 3, \"degree\": lambda n: n ** 3}\n\n\ndef solve(vertices, edges, alg_choice, only_count=False):\n return algs[alg_choice](vertices, edges, only_count)\n"
] |
[
[
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
thecho7/faster-rcnn.pytorch
|
[
"9cebac3d519f3a1deea4c9d2b2fe9b138cb99f44"
] |
[
"lib/model/rpn/generate_anchors.py"
] |
[
"from __future__ import print_function\n# --------------------------------------------------------\n# Faster R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick and Sean Bell\n# --------------------------------------------------------\n\nimport numpy as np\nimport pdb\n\n# Verify that we compute the same anchors as Shaoqing's matlab implementation:\n#\n# >> load output/rpn_cachedir/faster_rcnn_VOC2007_ZF_stage1_rpn/anchors.mat\n# >> anchors\n#\n# anchors =\n#\n# -83 -39 100 56\n# -175 -87 192 104\n# -359 -183 376 200\n# -55 -55 72 72\n# -119 -119 136 136\n# -247 -247 264 264\n# -35 -79 52 96\n# -79 -167 96 184\n# -167 -343 184 360\n\n#array([[ -83., -39., 100., 56.],\n# [-175., -87., 192., 104.],\n# [-359., -183., 376., 200.],\n# [ -55., -55., 72., 72.],\n# [-119., -119., 136., 136.],\n# [-247., -247., 264., 264.],\n# [ -35., -79., 52., 96.],\n# [ -79., -167., 96., 184.],\n# [-167., -343., 184., 360.]])\n\ntry:\n xrange # Python 2\nexcept NameError:\n xrange = range # Python 3\n\n\ndef generate_anchors(base_size=16,\n scales=2**np.arange(3, 6)):\n \"\"\"\n Generate anchor (reference) windows by enumerating aspect ratios X\n scales wrt a reference (0, 0, 15, 15) window.\n \"\"\"\n\n base_anchor = np.array([1, 1, base_size, base_size]) - 1\n anchors = np.vstack([_scale_enum(base_anchor[i, :], scales)\n for i in xrange(base_anchor.shape[0])])\n return anchors\n\ndef _whctrs(anchor):\n \"\"\"\n Return width, height, x center, and y center for an anchor (window).\n \"\"\"\n\n length = anchor[1] - anchor[0] + 1 # anchor = [start, end]\n ctr = anchor[1] + 0.5 * (length - 1)\n return length, ctr\n\ndef _mkanchors(lengths, ctr):\n \"\"\"\n Given a vector of widths (ws) and heights (hs) around a center\n (x_ctr, y_ctr), output a set of anchors (windows).\n \"\"\"\n\n lengths = lengths[:, np.newaxis]\n anchors = np.hstack((ctr - 0.5 * (lengths - 1),\n ctr + 0.5 * (lengths - 1)))\n return anchors\n\ndef _scale_enum(anchor, scales):\n \"\"\"\n Enumerate a set of anchors for each scale wrt an anchor.\n \"\"\"\n\n length, ctr = _whctrs(anchor)\n lengths = length * scales\n anchors = _mkanchors(lengths, ctr)\n return anchors\n\nif __name__ == '__main__':\n import time\n t = time.time()\n a = generate_anchors()\n print(time.time() - t)\n print(a)\n from IPython import embed; embed()\n"
] |
[
[
"numpy.hstack",
"numpy.array",
"numpy.arange"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bmj-hackathon/hack_sfpd2
|
[
"23fcce244c3f430413811e388a293e87b95a8df2",
"23fcce244c3f430413811e388a293e87b95a8df2"
] |
[
"03 scripts/02 Plotting Kernel Density.py",
"03 scripts/00 Superceded/03 Model Fitting r00.py"
] |
[
"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pickle\nimport matplotlib\n\n#%% SF Map\n# Supplied map bounding box:\n# ll.lon ll.lat ur.lon ur.lat\n# -122.52469 37.69862 -122.33663 37.82986\nPATH_MAP = \"/home/batman/git/hack_sfpd/INPUT/sf_map_copyright_openstreetmap_contributors.txt\"\nmapdata = np.loadtxt(PATH_MAP)\nasp = mapdata.shape[0] * 1.0 / mapdata.shape[1]\n\nlon_lat_box = (-122.5247, -122.3366, 37.699, 37.8299)\nclipsize = [[-122.5247, -122.3366],[ 37.699, 37.8299]]\n\n\n#%% =============================================================================\n# KDE per Category\n# =============================================================================\nfinished = [\n 'BURGLARY',\n 'VANDALISM',\n 'ASSAULT',\n 'ROBBERY',\n 'NON-CRIMINAL',\n ]\ndf_kde_subset = df_sub[~df_sub['Category'].isin(finished)]\n\nfor this_cat in df_kde_subset.Category.unique():\n #print(this_cat)\n \n start_time = datetime.now()\n \n # Get this single category df\n df_1cat = df_kde_subset[df_kde_subset.Category == this_cat]\n \n logging.debug(\"Processing KDE for {}, {} records\".format(this_cat, len(df_1cat)))\n #continue\n \n #df_1cat = df_kde_subset[df_kde_subset.Category == this_cat][0:100] \n \n \n # Make map brighter\n light_jet = cmap_map(lambda x: x*1.1, matplotlib.cm.gray)\n \n # Create figure\n this_cat_fig =plt.figure(figsize=LANDSCAPE_A3)\n ax = sns.kdeplot(df_1cat.X, df_1cat.Y, clip=clipsize, aspect=1/asp, shade=False, color=\"r\",cmap=\"seismic\")\n ax.set_xlabel(\"Longitude [Decimal deg.]\")\n ax.set_ylabel(\"Latitude [Decimal deg.]\")\n ax.imshow(mapdata, cmap=light_jet, \n extent=lon_lat_box, \n aspect=asp)\n \n # Create title\n min_time = df_1cat.dt.min().strftime(\"%Y-%m-%d\")\n max_time = df_1cat.dt.max().strftime(\"%Y-%m-%d\")\n num_recs = len(df_1cat)\n plt.suptitle(\"KDE plot for {} category\".format(this_cat),y=0.95,fontsize=16)\n plt.title(\"{} to {}, {} records\".format(min_time,max_time,num_recs))\n \n # Save figure PNG\n this_sanitized_cat = this_cat.replace(\"/\", \" \")\n \n path_this_cat_out = os.path.join(PATH_OUT_KDE,this_sanitized_cat+\".pdf\")\n plt.savefig(path_this_cat_out,dpi=600)\n elapsed_time = datetime.now() - start_time\n logging.debug(\"Wrote {} category to KDE map over {:0.1f}s\".format(this_cat, elapsed_time.total_seconds()))\n \n # Save contours\n countours = get_contour_verts(ax)\n path_this_contour_out = os.path.join(PATH_OUT_KDE,this_sanitized_cat+\"_contour.pck\")\n with open(path_this_contour_out, 'wb') as f:\n pickle.dump(countours,f)\n logging.debug(\"Wrote {} contours\".format(this_cat))\n\n\n\n#%% =============================================================================\n# KDE ALL\n# =============================================================================\n\n\nstart_time = datetime.now()\n\n# Get this single category df\ndf_1cat = df.sample(frac=0.2)\nthis_cat = \"ALL DATA\"\nlogging.debug(\"Processing KDE for ALL, {} records\".format(len(df_1cat)))\n\n# Make map brighter\nlight_jet = cmap_map(lambda x: x*1.1, matplotlib.cm.gray)\n\n# Create figure\nthis_cat_fig =plt.figure(figsize=LANDSCAPE_A3)\nax = sns.kdeplot(df_1cat.X, df_1cat.Y, clip=clipsize, aspect=1/asp, shade=False, color=\"r\",cmap=\"seismic\")\nax.set_xlabel(\"Longitude [Decimal deg.]\")\nax.set_ylabel(\"Latitude [Decimal deg.]\")\nax.imshow(mapdata, cmap=light_jet, \n extent=lon_lat_box, \n aspect=asp)\n\n# Create title\nmin_time = df_1cat.dt.min().strftime(\"%Y-%m-%d\")\nmax_time = df_1cat.dt.max().strftime(\"%Y-%m-%d\")\nnum_recs = len(df_1cat)\nplt.suptitle(\"KDE plot for {} category\".format(this_cat),y=0.95,fontsize=16)\nplt.title(\"{} to {}, {} records\".format(min_time,max_time,num_recs))\n\n# Save figure PNG\nthis_sanitized_cat = this_cat.replace(\"/\", \" \")\n\npath_this_cat_out = os.path.join(PATH_OUT_KDE,this_sanitized_cat+\".pdf\")\nplt.savefig(path_this_cat_out,dpi=600)\nelapsed_time = datetime.now() - start_time\nlogging.debug(\"Wrote {} category to KDE map over {:0.1f}s\".format(this_cat, elapsed_time.total_seconds()))\n\n# Save contours\ncountours = get_contour_verts(ax)\npath_this_contour_out = os.path.join(PATH_OUT_KDE,this_sanitized_cat+\"_contour2.pck\")\nwith open(path_this_contour_out, 'wb') as f:\n pickle.dump(countours,f)\nlogging.debug(\"Wrote {} contours\".format(this_cat))",
"# =============================================================================\n# Standard imports\n# =============================================================================\nimport os\nimport logging\n#import datetime\n#import gc\n#import zipfile\n\n# =============================================================================\n# External imports - reimported for code completion! \n# =============================================================================\nprint_imports()\n# Import again for code completion!\nimport pandas as pd \nimport numpy as np \nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport sklearn as sk\nimport sklearn\nimport sklearn.linear_model\n\n\n#from sklearn_pandas import DataFrameMapper\n#from sklearn_features.transformers import DataFrameSelector\n#from pandas.tseries.holiday import USFederalHolidayCalendar\n#from sklearn.cross_validation import KFold, cross_val_score\n#from sklearn.ensemble import RandomForestClassifier\n#from sklearn.linear_model import SGDClassifier\n#from sklearn.grid_search import GridSearchCV\n#from sklearn.kernel_approximation import RBFSampler\n#from sklearn.pipeline import make_pipeline\n#from sklearn.preprocessing import StandardScaler, LabelEncoder, LabelBinarizer\n#from sklearn_pandas import DataFrameMapper\n\n# to make this notebook's output stable across runs\nnp.random.seed(42)\n\n# Ignore useless warnings (see SciPy issue #5998)\nimport warnings\nwarnings.filterwarnings(action=\"ignore\", module=\"scipy\", message=\"^internal gelsd\")\n\n\n\ndays_off = USFederalHolidayCalendar().holidays(start='2003-01-01', end='2015-05-31').to_pydatetime()\n\n\n\n\n\n\n\n#%% Analaysis of fit\nif 0:\n importances = clf.feature_importances_\n std = np.std([tree.feature_importances_ for tree in forest_reg.estimators_],\n axis=0)\n indices = np.argsort(importances)[::-1]\n \n # Print the feature ranking\n print(\"Feature ranking:\")\n \n for f in range(train_df_numeric.shape[1]):\n print(\"%d. feature %d (%f)\" % (f + 1, indices[f], importances[indices[f]]))\n print(train_df_numeric.columns[indices[f]])\n # Plot the feature importances of the forest\n plt.figure()\n plt.title(\"Feature importances\")\n plt.bar(range(X.shape[1]), importances[indices],\n color=\"r\", yerr=std[indices], align=\"center\")\n plt.xticks(range(X.shape[1]), indices)\n plt.xlim([-1, X.shape[1]])\n plt.show()\n\n\n#%%**************************************************************************************\n# Gradient Boosting Regression\n#****************************************************************************************\nif 0:\n params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 2,\n 'learning_rate': 0.01, 'loss': 'ls'}\n clf = sk.ensemble.GradientBoostingRegressor(**params)\n clf.fit(train_df_numeric, np.log1p(y_train))\n\n\n#%% Predict\nif 0:\n y_train_predicted = clf.predict(train_df_numeric)\n y_test_predicted = clf.predict(test_df_numeric)\n \n res = pd.DataFrame(y_train_predicted)\n res.describe()\n res.hist(bins=1000)\n\n#%% Evaluate\n# Calculate exp(x) - 1 for all elements in the array.\n#y_train_predicted_cut[y_train_predicted > 100] = 100\nif 0:\n y_train_theor = np.expm1(y_train_predicted)\n y_test_theor = np.expm1(y_test_predicted)\n print()\n print(\"Training set\")\n print(\"RMSLE: \", rmsle(y_train_predicted, y_train_theor))\n \n sk.metrics.mean_squared_error(y_train,y_train_predicted)\n\n\n#%%**************************************************************************************\n# Random Forest \n#****************************************************************************************\nif 0:\n from sklearn import ensemble\n \n forest_reg = sk.ensemble.RandomForestRegressor(n_jobs=-1)\n forest_reg.fit(train_df_numeric, np.log1p(y_train))\n\n#%% Predict\nif 0:\n y_train_predicted = forest_reg.predict(train_df_numeric)\n y_test_predicted = forest_reg.predict(test_df_numeric)\n \n res = pd.DataFrame(y_train_predicted)\n res.describe()\n res.hist(bins=1000)\n\n#%% Evaluate\nif 0:\n y_train_theor = np.expm1(y_train_predicted)\n y_test_theor = np.expm1(y_test_predicted)\n print()\n print(\"Training set\")\n print(\"RMSLE: \", rmsle(y_train_predicted, y_train_theor))\n \n sk.metrics.mean_squared_error(y_train,y_train_predicted)\n\n#%%**************************************************************************************\n# Stochastic Gradient Descent\n#****************************************************************************************\nif 0:\n \n from sklearn import linear_model\n #params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 2,\n # 'learning_rate': 0.01, 'loss': 'ls'}\n #clf = sk.ensemble.GradientBoostingRegressor(**params)\n clf = sk.linear_model.SGDRegressor()\n print(clf)\n clf.fit(train_df_numeric, np.log1p(y_train))\n\n#%% Predict\nif 0:\n y_train_predicted = clf.predict(train_df_numeric)\n y_test_predicted = clf.predict(test_df_numeric)\n \n res = pd.DataFrame(y_train_predicted)\n res.describe()\n res.hist(bins=1000)\n\n#%% Evaluate\nif 0:\n \n # Calculate exp(x) - 1 for all elements in the array.\n #y_train_predicted_cut[y_train_predicted > 100] = 100\n \n y_train_theor = np.expm1(y_train_predicted)\n y_test_theor = np.expm1(y_test_predicted)\n print()\n print(\"Training set\")\n print(\"RMSLE: \", rmsle(y_train_predicted, y_train_theor))\n \n sk.metrics.mean_squared_error(y_train,y_train_predicted)\n\n"
] |
[
[
"matplotlib.pyplot.savefig",
"numpy.loadtxt",
"matplotlib.pyplot.figure"
],
[
"sklearn.ensemble.RandomForestRegressor",
"matplotlib.pyplot.title",
"numpy.random.seed",
"sklearn.linear_model.SGDRegressor",
"pandas.DataFrame",
"sklearn.ensemble.GradientBoostingRegressor",
"numpy.expm1",
"sklearn.metrics.mean_squared_error",
"numpy.std",
"matplotlib.pyplot.xlim",
"numpy.log1p",
"numpy.argsort",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
greenatom21/greenatom
|
[
"089bf1c7f8819dd0d8a151c2006b42f09da93fa1"
] |
[
"app/main/routes.py"
] |
[
"from datetime import datetime\nfrom flask import render_template, flash, redirect, url_for, request, g, \\\n jsonify, current_app\nfrom flask_login import current_user, login_required\nfrom flask_babel import _, get_locale\nfrom guess_language import guess_language\nfrom app import db\nfrom app.main.forms import EditProfileForm, PostForm, SearchForm, MessageForm\nfrom app.models import User, Post, Message, Notification\nfrom app.translate import translate\nfrom app.main import bp\nimport pickle\nimport os\nimport numpy as np\n\[email protected]_app_request\ndef before_request():\n if current_user.is_authenticated:\n current_user.last_seen = datetime.utcnow()\n db.session.commit()\n g.search_form = SearchForm()\n g.locale = str(get_locale())\n\n\[email protected]('/', methods=['GET', 'POST'])\[email protected]('/index', methods=['GET', 'POST'])\n@login_required\ndef index():\n form = PostForm()\n if form.validate_on_submit():\n language = guess_language(form.post.data)\n if language == 'UNKNOWN' or len(language) > 5:\n language = ''\n post = Post(body=form.post.data, author=current_user,\n language=language)\n db.session.add(post)\n db.session.commit()\n flash(_('Форма заполнена'))\n return redirect(url_for('main.index'))\n page = request.args.get('page', 1, type=int)\n posts = current_user.followed_posts().paginate(\n page, current_app.config['POSTS_PER_PAGE'], False)\n next_url = url_for('main.index', page=posts.next_num) \\\n if posts.has_next else None\n prev_url = url_for('main.index', page=posts.prev_num) \\\n if posts.has_prev else None\n return render_template('index.html', title=_('Home'), form=form,\n posts=posts.items, next_url=next_url,\n prev_url=prev_url)\n\n\[email protected]('/explore')\n@login_required\ndef explore():\n page = request.args.get('page', 1, type=int)\n posts = Post.query.order_by(Post.timestamp.desc()).paginate(\n page, current_app.config['POSTS_PER_PAGE'], False)\n next_url = url_for('main.explore', page=posts.next_num) \\\n if posts.has_next else None\n prev_url = url_for('main.explore', page=posts.prev_num) \\\n if posts.has_prev else None\n return render_template('index.html', title=_('Explore'),\n posts=posts.items, next_url=next_url,\n prev_url=prev_url)\n\n\[email protected]('/user/<username>')\n@login_required\ndef user(username):\n user = User.query.filter_by(username=username).first_or_404()\n page = request.args.get('page', 1, type=int)\n posts = user.posts.order_by(Post.timestamp.desc()).paginate(\n page, current_app.config['POSTS_PER_PAGE'], False)\n next_url = url_for('main.user', username=user.username,\n page=posts.next_num) if posts.has_next else None\n prev_url = url_for('main.user', username=user.username,\n page=posts.prev_num) if posts.has_prev else None\n return render_template('user.html', user=user, posts=posts.items,\n next_url=next_url, prev_url=prev_url)\n\n\[email protected]('/user/<username>/popup')\n@login_required\ndef user_popup(username):\n user = User.query.filter_by(username=username).first_or_404()\n return render_template('user_popup.html', user=user)\n\n\[email protected]('/edit_profile', methods=['GET', 'POST'])\n@login_required\ndef edit_profile():\n form = EditProfileForm(current_user.username)\n if form.validate_on_submit():\n current_user.username = form.username.data\n current_user.about_me = form.about_me.data\n db.session.commit()\n flash(_('Изменения сохранены.'))\n return redirect(url_for('main.edit_profile'))\n elif request.method == 'GET':\n form.username.data = current_user.username\n form.about_me.data = current_user.about_me\n return render_template('edit_profile.html', title=_('Edit Profile'),\n form=form)\n\n\[email protected]('/follow/<username>')\n@login_required\ndef follow(username):\n user = User.query.filter_by(username=username).first()\n if user is None:\n flash(_('Пользователь %(username)s не найден.', username=username))\n return redirect(url_for('main.index'))\n if user == current_user:\n flash(_('Нельзя подписаться на себя!'))\n return redirect(url_for('main.user', username=username))\n current_user.follow(user)\n db.session.commit()\n flash(_('Вы подписаны на %(username)s!', username=username))\n return redirect(url_for('main.user', username=username))\n\n\[email protected]('/unfollow/<username>')\n@login_required\ndef unfollow(username):\n user = User.query.filter_by(username=username).first()\n if user is None:\n flash(_('Пользователь %(username)s не найден.', username=username))\n return redirect(url_for('main.index'))\n if user == current_user:\n flash(_('Нельзя отписаться от себя!'))\n return redirect(url_for('main.user', username=username))\n current_user.unfollow(user)\n db.session.commit()\n flash(_('Вы отписались от %(username)s.', username=username))\n return redirect(url_for('main.user', username=username))\n\n\[email protected]('/translate', methods=['POST'])\n@login_required\ndef translate_text():\n return jsonify({'text': translate(request.form['text'],\n request.form['source_language'],\n request.form['dest_language'])})\n\n\[email protected]('/search')\n@login_required\ndef search():\n if not g.search_form.validate():\n return redirect(url_for('main.explore'))\n page = request.args.get('page', 1, type=int)\n posts, total = Post.search(g.search_form.q.data, page,\n current_app.config['POSTS_PER_PAGE'])\n next_url = url_for('main.search', q=g.search_form.q.data, page=page + 1) \\\n if total > page * current_app.config['POSTS_PER_PAGE'] else None\n prev_url = url_for('main.search', q=g.search_form.q.data, page=page - 1) \\\n if page > 1 else None\n return render_template('search.html', title=_('Search'), posts=posts,\n next_url=next_url, prev_url=prev_url)\n\n\[email protected]('/send_message/<recipient>', methods=['GET', 'POST'])\n@login_required\ndef send_message(recipient):\n user = User.query.filter_by(username=recipient).first_or_404()\n form = MessageForm()\n if form.validate_on_submit():\n msg = Message(author=current_user, recipient=user,\n body=form.message.data)\n db.session.add(msg)\n user.add_notification('unread_message_count', user.new_messages())\n db.session.commit()\n flash(_('Сообщение отправлено.'))\n return redirect(url_for('main.user', username=recipient))\n return render_template('send_message.html', title=_('Send Message'),\n form=form, recipient=recipient)\n\n\[email protected]('/messages')\n@login_required\ndef messages():\n current_user.last_message_read_time = datetime.utcnow()\n current_user.add_notification('unread_message_count', 0)\n db.session.commit()\n page = request.args.get('page', 1, type=int)\n messages = current_user.messages_received.order_by(\n Message.timestamp.desc()).paginate(\n page, current_app.config['POSTS_PER_PAGE'], False)\n next_url = url_for('main.messages', page=messages.next_num) \\\n if messages.has_next else None\n prev_url = url_for('main.messages', page=messages.prev_num) \\\n if messages.has_prev else None\n return render_template('messages.html', messages=messages.items,\n next_url=next_url, prev_url=prev_url)\n\n\[email protected]('/export_posts')\n@login_required\ndef export_posts():\n if current_user.get_task_in_progress('export_posts'):\n flash(_('Экспорт уже выполняется'))\n else:\n current_user.launch_task('export_posts', _('Экспорт...'))\n db.session.commit()\n return redirect(url_for('main.user', username=current_user.username))\n\n\[email protected]('/notifications')\n@login_required\ndef notifications():\n since = request.args.get('since', 0.0, type=float)\n notifications = current_user.notifications.filter(\n Notification.timestamp > since).order_by(Notification.timestamp.asc())\n return jsonify([{\n 'name': n.name,\n 'data': n.get_data(),\n 'timestamp': n.timestamp\n } for n in notifications])\n\ndef ValuePredictor(to_predict_list): \n print(to_predict_list)\n to_predict = np.array(to_predict_list).reshape(1, 20)\n print(to_predict)\n loaded_model = pickle.load(open(\"model_noscaler.pkl\", \"rb\")) \n result = loaded_model.predict(to_predict) \n return result[0] \n\[email protected]('/analyse')\n@login_required\ndef analyse():\n return render_template(\"analyse.html\")\n\[email protected]('/analyse_result', methods = ['POST'])\n@login_required\ndef analyse_result():\n if request.method == 'POST': \n to_predict_list = request.form.to_dict() \n to_predict_list = list(to_predict_list.values()) \n to_predict_list = list(map(int, to_predict_list)) \n result = ValuePredictor(to_predict_list) \n if int(result)== 0: \n prediction = 'Не cклонен к уходу'\n else: \n prediction = 'Cклонен к уходу' \n return render_template(\"analyse_result.html\", prediction = prediction)\n\[email protected]('/nlp', methods=['GET', 'POST'])\n@login_required\ndef nlp():\n user = User.query.filter_by(username=current_user.username).first_or_404()\n form = PostForm()\n if form.validate_on_submit():\n language = guess_language(form.post.data)\n if language == 'UNKNOWN' or len(language) > 5:\n language = ''\n post = Post(body=form.post.data, author=current_user,\n language=language)\n db.session.add(post)\n db.session.commit()\n flash(_('Форма заполнена'))\n return redirect(url_for('main.nlp'))\n return render_template(\"nlp.html\", form=form, user=user)\n\[email protected]('/analyse_graph', methods = ['POST'])\n@login_required\ndef analyse_graph():\n if request.method == 'POST':\n user = User.query.filter_by(username=current_user.username).first_or_404()\n flash(_('Успешно добавлено в БД. Граф обновлен')) \n return render_template(\"graph.html\", user=user)\n\[email protected]('/graph', methods=['GET', 'POST'])\n@login_required\ndef graph():\n user = User.query.filter_by(username=current_user.username).first_or_404()\n error = \"Ошибка загрузки БД\"\n return render_template(\"graph.html\", user=user, error=error)\n\[email protected]('/watch_graph', methods=['GET', 'POST'])\n@login_required\ndef watch_graph():\n user = User.query.filter_by(username=current_user.username).first_or_404()\n return render_template(\"watch_graph.html\", user=user)\n\[email protected]('/watch_graph_group', methods=['GET', 'POST'])\n@login_required\ndef watch_graph_group():\n user = User.query.filter_by(username=current_user.username).first_or_404()\n return render_template(\"watch_graph_group.html\", user=user)\n\[email protected]('/watch_graph_toxic', methods=['GET', 'POST'])\n@login_required\ndef watch_graph_toxic():\n user = User.query.filter_by(username=current_user.username).first_or_404()\n return render_template(\"watch_graph_toxic.html\", user=user)\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
MHersche/HDembedding-BCI
|
[
"d815dd75c326114da11f0fc2e0acc6da67d10d74",
"d815dd75c326114da11f0fc2e0acc6da67d10d74"
] |
[
"hd_utils/nn_trainer3.py",
"hd_utils/HD_Kmeans.py"
] |
[
"#!/usr/bin/env python3\n\nfrom __future__ import print_function\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\nfrom sklearn.svm import LinearSVC,SVC\n\nimport sys, os\nfrom model1 import Net\n\n\nclass proj_trainer_end_end:\n\t\n\tdef __init__(self,feat_dim,n_bands,HD_dim,n_classes,N_epoch,device,log_interval=50):\n\t\t\n\t\tself.feat_dim = feat_dim\n\t\tself.HD_dim = HD_dim\n\t\tself.device = device\n\t\t\n\t\tself._target_mem = torch.ShortTensor(n_classes,self.HD_dim).bernoulli_().to(self.device)\n\t\n\t\t# Training settings\n\t\tparser = argparse.ArgumentParser(description='HD projection trainer')\n\t\tparser.add_argument('--batch-size', type=int, default=32, metavar='N',\n\t\t\t\t\t\t\thelp='input batch size for training (default: 64)')\n\t\tparser.add_argument('--test-batch-size', type=int, default=500, metavar='N',\n\t\t\t\t\t\t\thelp='input batch size for testing (default: 1000)')\n\t\tparser.add_argument('--epochs', type=int, default=N_epoch, metavar='N',\n\t\t\t\t\t\t\thelp='number of epochs to train (default: 10)')\n\t\tparser.add_argument('--lr', type=float, default=64., metavar='LR', # 64.\n\t\t\t\t\t\t\thelp='learning rate (default: 0.01)')\n\t\tparser.add_argument('--momentum', type=float, default=0.5, metavar='M',\n\t\t\t\t\t\t\thelp='SGD momentum (default: 0.5)')\n\t\tparser.add_argument('--no-cuda', action='store_true', default=False,\n\t\t\t\t\t\t\thelp='disables CUDA training')\n\t\tparser.add_argument('--seed', type=int, default=1, metavar='S',\n\t\t\t\t\t\t\thelp='random seed (default: 1)')\n\t\tparser.add_argument('--log-interval', type=int, default=log_interval, metavar='N',\n\t\t\t\t\t\t\thelp='how many batches to wait before logging training status')\n\t\tself.args = parser.parse_args()\n\t\t\n\t\ttorch.manual_seed(self.args.seed)\n\n\t\tself.model = Net(feat_dim,n_bands,HD_dim,self.device).to(self.device)\n\n\t\tself.optimizer = optim.SGD(filter(lambda p: p.requires_grad, self.model.parameters()), lr=self.args.lr, momentum = self.args.momentum)\n\t\tself.criterion = F.binary_cross_entropy_with_logits\n\n\n\tdef train(self,data,label):\n\t\t\n\t\t# convert target idx to real target \n\t\ttarget = self._target_mem[label-1,:].float()\n\t\tdata_cuda = torch.from_numpy(data).to(self.device).float()\n\n\t\tb_size = self.args.batch_size\n\n\t\tN_batches = int(np.floor(data.shape[0]/b_size))\n\n\t\tfor epoch in range(self.args.epochs):\n\t\t\tfor b_idx in range(N_batches):\n\t\t\t\tself.model.train()\n\n\t\t\t\tdata_b = data_cuda[b_idx*b_size:(b_idx+1)*b_size]\n\t\t\t\ttarget_b = target[b_idx*b_size:(b_idx+1)*b_size]\n\t\t\t\t\n\t\t\t\tself.optimizer.zero_grad()\n\t\t\t\toutput = self.model(data_b)\n\t\t\t\tloss = self.criterion(output, target_b) # negative log likelyhood loss \n\t\t\t\t\n\t\t\t\tloss.backward()\n\t\t\t\tself.optimizer.step()\n\t\t\n\t\t\n\t\t\t# # testing \n\t\t\tif (epoch % self.args.log_interval==0):\n\t\t\t\t\tself.test(data_cuda,target,epoch,True)\n\n\t\treturn\n\n\tdef test(self,data,target,epoch,do_print=False):\n\t\tself.model.eval()\n\t\ttest_loss = 0\n\t\tcorrect = 0\n\t\twith torch.no_grad():\n\n\t\t\toutput = self.model(data)\n\t\t\ttest_loss = self.criterion(output, target) # negative log likelyhood loss \n\t\t\t\n\t\t\tpred = (output > 0)\n\t\t\taccuracy = torch.mean(((pred.short()-target.short())==0).float())\n\n\t\tif do_print: \n\t\t\tprint('Epoch: {}, \\t Training set: Average loss: {:.4f}, Accuracy: {:.5f}'.format(epoch,\n\t\t\t\ttest_loss, accuracy))\n\t\treturn\n\n\tdef get_params(self):\n\t\tproj_mat = self.model.get_weight()#self.model.fc1.weight.data#\n\n\t\treturn self._target_mem, proj_mat,self.model.enc_vec.transpose(1,0) # self.model.enc_vec#\n",
"#!/usr/bin/env python3\n\n''' \nKmeans clustering \n'''\nimport time, sys \n\nimport numpy as np\nfrom hd_bin_classifier_cuda import hd_classifier\nimport torch\n\n\n__author__ = \"Michael Hersche\"\n__email__ = \"[email protected]\"\n__date__ = \"27.5.2018\"\n\nclass KMeans:\n\n\tdef __init__(self, n_clusters=8, init='k-means++', n_init=10,\n\t\t\t\t max_iter=300, tol=1e-4, precompute_distances='auto',\n\t\t\t\t verbose=0, random_state=None, copy_x=True,\n\t\t\t\t n_jobs=1, algorithm='auto', \n\t\t\t\t cuda_device = 'cuda:0'):\n\t\tself.n_clusters = n_clusters\n\t\tself.init = init\n\t\tself.max_iter = max_iter\n\t\tself.tol = tol\n\t\tself.precompute_distances = precompute_distances\n\t\tself.n_init = n_init\n\t\tself.verbose = verbose\n\t\tself.random_state = random_state\n\t\tself.copy_x = copy_x\n\t\tself.n_jobs = n_jobs\n\t\tself.algorithm = algorithm\n\t\tself._best_cost = 0.\n\n\t\tuse_cuda = torch.cuda.is_available() \n\t\tself.device = torch.device(cuda_device if use_cuda else \"cpu\")\n\t\n\n\tdef fit(self, X):\n\t\t\"\"\"Compute k-means clustering.\n\n\t\tParameters\n\t\t----------\n\t\tX : array-like or sparse matrix, shape=(n_samples, n_features)\n\t\t\tTraining instances to cluster.\n\n\t\t\"\"\"\n\t\t'''\n\t\tcalculate K-means algorithm based on HD arithmetic \n\t\t'''\n\t\tn_samples, HD_dim = X.shape\n\t\t\n\t\tif self.verbose: \n\t\t\t\tprint('Start K-menas calculation for {:d} centroids'.format(self.n_clusters))\n\n\t\tfor i_init in range(self.n_init): \n\n\t\t\tcur_centroids = self._init_centroids(X,self.n_clusters)\n\t\t\t\n\n\t\t\tlabel = np.ones(n_samples,dtype = int)\n\t\t\tnew_label = np.zeros(n_samples,dtype = int)\n\n\t\t\titerr = 0\n\t\t\twhile (not np.array_equal(new_label,label)) and (iterr < self.max_iter):\n\t\t\t\t# init new centroid for adding up all means \n\t\t\t\tnew_centroids = torch.ShortTensor(self.n_clusters,HD_dim).zero_().to(self.device)\n\t\t\t\tclass_cnt = np.zeros(self.n_clusters)\n\t\t\t\tcost = 0\n\n\t\t\t\tlabel = new_label.copy()\n\t\t\t\t\n\t\t\t\t# calculate distance and assign labels to closes point\n\t\t\t\tfor samp_idx in range(n_samples): \n\t\t\t\t\t# assign label to closest point\n\t\t\t\t\tdist = self.get_multi_HD_dist(X[samp_idx],cur_centroids,self.n_clusters)\n\t\t\t\t\tnew_label[samp_idx] = np.argmin(dist)\n\t\t\t\t\t# update cost \n\t\t\t\t\tcost += dist[new_label[samp_idx]]\n\t\t\t\t\t# add to new mean\n\t\t\t\t\tnew_centroids[new_label[samp_idx]].add_(X[samp_idx])\n\t\t\t\t\tclass_cnt[new_label[samp_idx]] += 1 \n\n\t\t\t\t# thresholding of new mean \n\t\t\t\tcur_centroids = self.thresh_item(new_centroids,class_cnt)\t\n\n\t\t\t\titerr +=1 \n\n\t\t\t\n\n\t\t\tif (i_init ==0) or (cost < self._best_cost): # first round or new best partition \n\t\t\t\tself._best_cost = cost\n\t\t\t\tself.cluster_centers_ = cur_centroids\n\t\t\t\tself.labels_ = new_label\n\n\t\t\tif self.verbose: \n\t\t\t\tprint('Iteration {}, Cost: {:.2f}, Best cost: {:.2f}: '.format(i_init,cost,self._best_cost))\n\n\t\t\tself._is_fitted = True\n\n\t\treturn self\n\n\tdef fit_predict(self, X, y=None):\n\t\t\"\"\"Compute cluster centers and predict cluster index for each sample.\n\n\t\tConvenience method; equivalent to calling fit(X) followed by\n\t\tpredict(X).\n\n\t\tParameters\n\t\t----------\n\t\tX : {array-like, sparse matrix}, shape = [n_samples, n_features]\n\t\t\tNew data to transform.\n\n\t\tu : Ignored\n\n\t\tReturns\n\t\t-------\n\t\tlabels : array, shape [n_samples,]\n\t\t\tIndex of the cluster each sample belongs to.\n\t\t\"\"\"\n\n\t\treturn self.fit(X).labels_\n\n\tdef predict(self, X):\n\t\t\"\"\"Predict the closest cluster each sample in X belongs to.\n\n\t\tIn the vector quantization literature, `cluster_centers_` is called\n\t\tthe code book and each value returned by `predict` is the index of\n\t\tthe closest code in the code book.\n\n\t\tParameters\n\t\t----------\n\t\tX : {array-like, sparse matrix}, shape = [n_samples, n_features]\n\t\t\tNew data to predict.\n\n\t\tReturns\n\t\t-------\n\t\tlabels : array, shape [n_samples,]\n\t\t\tIndex of the cluster each sample belongs to.\n\t\t\"\"\"\n\t\t\n\t\tif not self._is_fitted:\n\t\t\traise ValueError(\"Centroids not fitted \")\n\n\t\treturn self._labels_inertia(X)[0]\n\n\n\n\tdef labels_inertia(self,X):\n\n\n\t\tif not self._is_fitted:\n\t\t\traise ValueError(\"Centroids not fitted \")\n\n\t\tn_samples = X.shape[0]\n\n\t\tlabels = np.zeros(n_samples,dtype = int) # esstimated labels \n\t\tdist = np.zeros((n_samples,self.n_clusters))\n\n\t\tlabel_cnt = np.zeros(self.n_clusters,dtype = int)\n\t\tlabeld_dist= np.zeros((self.n_clusters,n_samples))\n\n\n\t\tfor samp_idx in range(n_samples):\n\t\t\tdist[samp_idx] = self.get_multi_HD_dist(X[samp_idx],self.cluster_centers_,n_item= self.n_clusters)\n\t\t\tlabel = np.argmin(dist[samp_idx])\n\t\t\tlabels[samp_idx]= label\n\t\t\t# store best label and distance for statistics \n\t\t\tlabeld_dist[label,label_cnt[label]] = np.min(dist[samp_idx])\n\t\t\tlabel_cnt[label] +=1\n\n\t\tself.var_ = np.zeros(self.n_clusters)\n\t\tself.mean_ = np.zeros(self.n_clusters)\n\n\t\tfor label in range(self.n_clusters): \n\t\t\tself.var_[label]= np.var(labeld_dist[label,:label_cnt[label]])\n\t\t\tself.mean_[label]= np.mean(labeld_dist[label,:label_cnt[label]])\n\n\t\treturn labels,dist\n\n\tdef _init_centroids(self,X, k, init= 'k-means++', random_state=None):\n\t\t\"\"\"Compute the initial centroids\n\n\t\tParameters\n\t\t----------\n\n\t\tX : array, shape (n_samples, n_features)\n\n\t\tk : int\n\t\t\tnumber of centroids\n\n\t\tinit : {'k-means++', 'random' or ndarray or callable} optional\n\t\t\tMethod for initialization\n\n\t\trandom_state : int, RandomState instance or None, optional, default: None\n\t\t\tIf int, random_state is the seed used by the random number generator;\n\t\t\tIf RandomState instance, random_state is the random number generator;\n\t\t\tIf None, the random number generator is the RandomState instance used\n\t\t\tby `np.random`.\n\n\t\tReturns\n\t\t-------\n\t\tcenters : array, shape(k, n_features)\n\t\t\"\"\"\n\t\tn_samples = X.shape[0]\n\n\t\tinit_indices = np.random.choice(n_samples,k,replace = False)\n\t\t\n\t\tcenters = X[init_indices]\n\n\t\treturn centers\n\n\tdef get_multi_HD_dist(self,test_vec,dic,n_item = 4):\n\t\t# calculate HD dist between c and entries of dic\n\t\t\n\n\t\tn_item = dic.shape[0]\n\n\t\tdist = np.zeros(n_item)\n\n\t\tfor i in range(n_item):\n\t\t\tdist[i] = self.ham_dist(test_vec,dic[i])\n\n\t\treturn dist \n\n\n\tdef thresh_item(self,Item,item_count):\n\t\t'''\tThresholding of items, if even number we add random vector for breaking ties \n\t\tParameters\n\t\t----------\n\t\tItem: accumulated HD vector, torch short tensor shape=(NO_item,HD_dim)\n\t\titem_count: number of additions per Item for determining threshold, numpy array shape (NO_item)\n\t\tReturn \n\t\t------\n\t\tItem: Thresholded item \n\t\t'''\t\n\n\t\tNO_item,HD_dim = Item.shape\n\n\t\tfor i in range(NO_item): \n\t\t\tif item_count[i] % 2 == 0: # even number of counts \n\t\t\t\tItem[i].add_(torch.ShortTensor(HD_dim).bernoulli_().to(self.device)) # add random vector \n\t\t\t\titem_count[i] += 1 \n\n\t\t\t# Tresholding \n\t\t\tItem[i] = Item[i] > int(item_count[i]/2)\n\n\t\treturn Item\n\n\tdef ham_dist(self,vec_a,vec_b):\n\t\t''' calculate relative hamming distance \n\t\tParameters\n\t\t----------\n\t\tvec_a: first vector, torch Short Tensor shape (HD_dim,)\n\t\tvec_b: second vector, torch Short Tensor shape (HD_dim,)\n\t\tReturn \n\t\t------\n\t\trel_dist: relative hamming distance \n\t\t'''\t\n\t\tvec_c = self.xor(vec_a,vec_b)\n\n\t\trel_dist = float(torch.sum(vec_c).cpu().numpy()) / float(torch.numel(vec_c))\n\n\t\treturn rel_dist\n\n\tdef xor(self,vec_a,vec_b):\n\t\t''' xor between vec_a and vec_b\n\t\tParameters\n\t\t----------\n\t\tvec_a: first vector, torch Short Tensor shape (HD_dim,)\n\t\tvec_b: second vector, torch Short Tensor shape (HD_dim,)\n\t\tReturn \n\t\t------\n\t\tvec_c: vec_a xor vec_b\n\t\t'''\t\n\t\tvec_c = (torch.add(vec_a,vec_b) == 1).short() # xor \n\n\t\treturn vec_c\n\n\tdef HDmean(X):\n\t\t''' HD mean of X \n\t\tParameters\n\t\t----------\n\t\tX: HD vectors, torch Short Tensor shape (N_samples,HD_dim,)\n\t\tReturn \n\t\t------\n\t\tout: Mean HD vector, torch Short Tensor shape (HD_dim,)\n\t\t'''\t\n\t\tn_samples,HD_dim = X.shape\n\n\t\tsumm = X[0]\n\n\t\tfor samp in range(1,n_samples): \n\t\t\tsumm.add_(X[samp])\n\n\t\tout = summ > int(n_samples/2)\n\n\t\treturn out "
] |
[
[
"torch.manual_seed",
"torch.ShortTensor",
"torch.from_numpy",
"torch.no_grad",
"numpy.floor"
],
[
"torch.add",
"numpy.array_equal",
"numpy.random.choice",
"numpy.min",
"torch.ShortTensor",
"torch.sum",
"numpy.var",
"numpy.ones",
"torch.numel",
"numpy.argmin",
"numpy.mean",
"torch.cuda.is_available",
"torch.device",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ishidaira233/TX-Credit-Assessement
|
[
"289f230a609554db32552670c300f992a3fe068f",
"289f230a609554db32552670c300f992a3fe068f"
] |
[
"variableProcessing/BFSVM_class/LS_FSVM.py",
"variableProcessing/Kernel.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 1 22:46:20 2020\n@author: zinan\n\"\"\"\n\nimport numpy as np\nfrom numpy import linalg as LA\nfrom BFSVM_class import Kernel\nfrom BFSVM_class import precision\nfrom imblearn.over_sampling import SVMSMOTE\nimport math\nfrom sklearn.model_selection import train_test_split\n\n\"\"\"\n Least Square Fuzzy SVM\n linear equation problem Package: NUMPY.LINALG\nParameters\n C: penalty\n kernel_dict : \n 'type': 'LINEAR' / 'RBF' 'sigma' / 'POLY' 'd'\n \n fuzzyvalue:\n membershape value based on the class of center\n 'type': 'Cen' \n 'function' : 'Lin' / 'Exp'\n \n membershape value based on the actuale hyper-plane\n 'type': 'Hyp' \n 'function' : 'Lin' / 'Exp'\n \n r_max : radio between 0 and 1\n r_min : radio between 0 and 1 for balancing data\n \n usually for the majority class r = len(y_minority)/len(y_majority) \n and for the minority class r = 1\nMethods\n _mvalue(self, X, y)\n Calculate fuzzy membership value\n \n fit(self, X, Y)\n Fit the model according to the given training data.\n \n predict(self, X)\n Predict class labels for samples in X.\n \n Platt_Probabilistic(self,deci,label,prior1,prior0)\n For posterior class probability Pr(y = 1|x) = 1/(1+exp(Af+B)) calculate \n Position parameter (B) and scale parameter (A)\n \n predict_prob(self,X)\n Posterior class probability Pr(y = 1|x)\n \n \n decision_function(self, X)\n Predict confidence scores for samples.\n The confidence score for a sample is the signed distance of that sample to the hyperplane.\n\"\"\"\n\n\nclass LSFSVM:\n def __init__(\n self,\n C=3,\n kernel_dict={\"type\": \"LINEAR\"},\n fuzzyvalue={\"type\": \"Cen\", \"function\": \"Lin\"},\n databalance=\"origine\",\n r_max=1,\n r_min=1,\n ):\n\n self.C = C\n self.kernel_dict = kernel_dict\n self.fuzzyvalue = fuzzyvalue\n self.r_max = r_max\n self.r_min = r_min\n self.databalance = databalance\n\n # self.m_value = None\n # self.alpha = None\n # self.b = None\n # self.K = None\n\n def _mvalue(self, X, y):\n # print('fuzzy value:', self.fuzzyvalue )\n train_data = np.append(X, y.reshape(len(y), 1), axis=1)\n\n if self.databalance == \"LowSampling\":\n data_maj = train_data[y == 1] # 将多数\n data_min = train_data[y != 1]\n index = np.random.randint(len(data_maj), size=len(data_min))\n lower_data_maj = data_maj[list(index)]\n train_data = np.append(lower_data_maj, data_min, axis=0)\n X = train_data[:, :-1]\n y = train_data[:, -1]\n\n elif self.databalance == \"UpSampling\":\n X, y = SVMSMOTE(random_state=42).fit_sample(\n train_data[:, :-1], np.asarray(train_data[:, -1])\n )\n\n else:\n X = X\n y = y\n\n if self.fuzzyvalue[\"type\"] == \"Cen\":\n\n x_1 = X[y == 1]\n x_0 = X[y == -1]\n x_centre_1 = np.mean(x_1, axis=0)\n x_centre_0 = np.mean(x_0, axis=0)\n max_distance_1 = 0\n max_distance_0 = 0\n for i in range(len(x_1)):\n distance = LA.norm(x_centre_1 - x_1[i, :])\n if max_distance_1 < distance:\n max_distance_1 = distance\n for i in range(len(x_0)):\n distance = LA.norm(x_centre_0 - x_0[i, :])\n if max_distance_0 < distance:\n max_distance_0 = distance\n\n memership = []\n if self.fuzzyvalue[\"function\"] == \"Lin\":\n for i in range(len(y)):\n if y[i] == 1:\n memership.append(\n (1 - LA.norm(X[i] - x_centre_1) / (max_distance_1 + 0.0001))\n * self.r_max\n )\n if y[i] == -1:\n memership.append(\n (1 - LA.norm(X[i] - x_centre_0) / (max_distance_0 + 0.0001))\n * self.r_min\n )\n\n elif self.fuzzyvalue[\"function\"] == \"Exp\":\n for i in range(len(y)):\n if y[i] == 1:\n memership.append(\n (2 / (1 + np.exp(LA.norm(X[i] - x_centre_1)))) * self.r_max\n )\n if y[i] == -1:\n memership.append(\n (2 / (1 + np.exp(LA.norm(X[i] - x_centre_0)))) * self.r_min\n )\n\n elif self.fuzzyvalue[\"type\"] == \"Hyp\":\n m = y.shape[0]\n C = 3\n gamma = 1\n # Kernel\n\n K = Kernel.RBF(m, gamma)\n K.calculate(X)\n\n H = np.multiply(np.dot(np.matrix(y).T, np.matrix(y)), K.kernelMat)\n M_BR = H + np.eye(m) / C\n # Concatenate\n L_L = np.concatenate((np.matrix(0), np.matrix(y).T), axis=0)\n L_R = np.concatenate((np.matrix(y), M_BR), axis=0)\n L = np.concatenate((L_L, L_R), axis=1)\n R = np.ones(m + 1)\n R[0] = 0\n # solve\n b_a = LA.solve(L, R)\n b = b_a[0]\n alpha = b_a[1:]\n\n K.expand(X)\n A = np.multiply(alpha, y)\n\n f = b + np.dot(K.testMat, A)\n\n d_hyp = abs(f * y)\n\n memership = []\n if self.fuzzyvalue[\"function\"] == \"Lin\":\n for i in range(len(y)):\n if y[i] == 1:\n memership.append(\n (1 - d_hyp[i] / (max(d_hyp) + 0.0001)) * self.r_max\n )\n if y[i] == -1:\n memership.append(\n (1 - d_hyp[i] / (max(d_hyp) + 0.0001)) * self.r_min\n )\n\n elif self.fuzzyvalue[\"function\"] == \"Exp\":\n for i in range(len(y)):\n if y[i] == 1:\n memership.append((2 / (1 + np.exp(d_hyp[i]))) * self.r_max)\n if y[i] == -1:\n memership.append((2 / (1 + np.exp(d_hyp[i]))) * self.r_min)\n\n self.m_value = np.array(memership)\n return self.m_value\n\n def fit(self, X, Y):\n # print('Kernel:', self.kernel_dict)\n train_data = np.append(X, Y.reshape(len(Y), 1), axis=1)\n\n if self.databalance == \"LowSampling\":\n data_maj = train_data[Y == 1] # 将多数\n data_min = train_data[Y != 1]\n index = np.random.randint(len(data_maj), size=len(data_min))\n lower_data_maj = data_maj[list(index)]\n train_data = np.append(lower_data_maj, data_min, axis=0)\n X = train_data[:, :-1]\n Y = train_data[:, -1]\n self.Y = Y\n\n elif self.databalance == \"UpSampling\":\n X, Y = SVMSMOTE(random_state=42).fit_sample(\n train_data[:, :-1], np.asarray(train_data[:, -1])\n )\n self.Y = Y\n\n else:\n X = X\n Y = Y\n self.Y = Y\n\n m = len(Y)\n\n # Kernel\n if self.kernel_dict[\"type\"] == \"RBF\":\n K = Kernel.RBF(m, self.kernel_dict[\"sigma\"])\n K.calculate(X)\n elif self.kernel_dict[\"type\"] == \"LINEAR\":\n K = Kernel.LINEAR(m)\n K.calculate(X)\n elif self.kernel_dict[\"type\"] == \"POLY\":\n K = Kernel.POLY(m, self.kernel_dict[\"d\"])\n K.calculate(X)\n\n H = np.multiply(np.dot(np.matrix(Y).T, np.matrix(Y)), K.kernelMat)\n M_BR = H + np.eye(m) / (self.C * (self.m_value[:, None]))\n # Concatenate\n L_L = np.concatenate((np.matrix(0), np.matrix(Y).T), axis=0)\n L_R = np.concatenate((np.matrix(Y), M_BR), axis=0)\n L = np.concatenate((L_L, L_R), axis=1)\n R = np.ones(m + 1)\n R[0] = 0\n # solve\n b_a = LA.solve(L, R)\n b = b_a[0]\n alpha = b_a[1:]\n\n self.alpha = alpha\n self.b = b\n self.K = K\n self.kernelMat = K.kernelMat\n\n def predict(self, X):\n\n self.K.expand(X)\n A = np.multiply(self.alpha, self.Y)\n y_predict = self.b + np.dot(self.K.testMat, A)\n self.y_predict = y_predict\n y_pred = y_predict.copy()\n y_pred[y_pred >= 0] = 1\n y_pred[y_pred < 0] = -1\n self.y_pred = y_pred\n return y_pred\n\n def Platt_Probabilistic(self, deci, label, prior1, prior0):\n maxiter = 100\n minstep = 1e-10\n sigma = 1e-12\n\n hiTarget = (prior1 + 1.0) / (prior1 + 2.0)\n loTarget = 1 / (prior0 + 2.0)\n leng = prior1 + prior0\n t = np.zeros(leng)\n for i in range(leng):\n if label[i] > 0:\n t[i] = hiTarget\n else:\n t[i] = loTarget\n\n A = 0.0\n B = math.log((prior0 + 1.0) / (prior1 + 1.0))\n fval = 0.0\n\n for i in range(leng):\n fApB = deci[i] * A + B\n if fApB >= 0:\n fval += t[i] * fApB + math.log(1 + np.exp(-fApB))\n else:\n fval += (t[i] - 1) * fApB + math.log(1 + np.exp(fApB))\n\n for it in range(maxiter):\n # Update Gradient and Hessian (use H’ = H + sigma I)\n h11 = h22 = sigma\n h21 = g1 = g2 = 0.0\n\n for i in range(leng):\n fApB = deci[i] * A + B\n if fApB >= 0:\n p = np.exp(-fApB) / (1.0 + np.exp(-fApB))\n q = 1.0 / (1.0 + np.exp(-fApB))\n else:\n p = 1.0 / (1.0 + np.exp(fApB))\n q = np.exp(fApB) / (1.0 + np.exp(fApB))\n\n d2 = p * q\n h11 += deci[i] * deci[i] * d2\n h22 += d2\n h21 += deci[i] * d2\n\n d1 = t[i] - p\n g1 += deci[i] * d1\n g2 += d1\n\n if abs(g1) < 1e-5 and abs(g2) < 1e-5: # Stopping criteria\n break\n # Compute modified Newton directions\n\n det = h11 * h22 - h21 * h21\n dA = -(h22 * g1 - h21 * g2) / det\n dB = -(-h21 * g1 + h11 * g2) / det\n gd = g1 * dA + g2 * dB\n stepsize = 1\n\n while stepsize >= minstep:\n # Line search\n newA = A + stepsize * dA\n newB = B + stepsize * dB\n newf = 0.0\n for i in range(leng):\n fApB = deci[i] * newA + newB\n if fApB >= 0:\n newf += t[i] * fApB + math.log(1 + np.exp(-fApB))\n else:\n newf += (t[i] - 1) * fApB + math.log(1 + np.exp(fApB))\n\n if newf < fval + 0.0001 * stepsize * gd:\n A = newA\n B = newB\n fval = newf\n break # Sufficient decrease satisfied\n else:\n stepsize /= 2.0\n\n if stepsize < minstep:\n print(\"Line search fails\")\n break\n\n if it >= maxiter:\n print(\"Reaching maximum iterations\")\n\n return A, B\n\n def predict_prob(self, X):\n A = np.multiply(self.alpha, self.Y)\n y_hat = self.b + np.dot(self.kernelMat, A)\n\n deci = y_hat\n label = self.Y\n prior1 = len(self.Y[self.Y == 1])\n prior0 = len(self.Y[self.Y == -1])\n A, B = self.Platt_Probabilistic(deci, label, prior1, prior0)\n\n y_prob = 1 / (1 + np.exp(A * self.y_predict + B))\n for i in range(len(y_prob)):\n y_prob[i] = round(y_prob[i], 3)\n\n return y_prob\n\n def decision_function(self, X):\n return self.y_predict\n\n\n# Test Code for _LSSVMtrain\n\nif __name__ == \"__main__\":\n\n data = DataDeal.get_data(\"german_numerical.csv\")\n precisionArray = []\n\n # Train_data,test = train_test_split(data, test_size=0.2)\n # x_test = test[:,:-1]\n # y_test = test[:,-1]\n # x_train = Train_data[:,:-1]\n # y_train = Train_data[:,-1]\n #\n #\n # kernel_dict = {'type': 'RBF','sigma':0.717}\n # fuzzyvalue = {'type':'Cen','function':'Lin'}\n #\n # clf = LSFSVM(10,kernel_dict, fuzzyvalue,'o',3/4)\n # m = clf._mvalue(x_train, y_train)\n # clf.fit(x_train, y_train)\n # y_pred = clf.predict(x_test)\n # y_prob = clf.predict_prob(x_test)\n # decision_function = clf.decision_function(x_test)\n #\n # print('y_prob',y_prob)\n # print(y_pred[y_prob<0.5])\n # print(y_pred[y_prob>0.5])\n # print(decision_function)\n # Precision.precision(y_pred,y_test)\n\n for i in range(10):\n Train_data, test = train_test_split(data, test_size=0.2)\n x_test = test[:, :-1]\n y_test = test[:, -1]\n x_train = Train_data[:, :-1]\n y_train = Train_data[:, -1]\n\n kernel_dict = {\"type\": \"RBF\", \"sigma\": 0.717}\n fuzzyvalue = {\"type\": \"Cen\", \"function\": \"Lin\"}\n\n clf = LSFSVM(10, kernel_dict, fuzzyvalue, \"o\", 3 / 4)\n m = clf._mvalue(x_train, y_train)\n print(m)\n clf.fit(x_train, y_train)\n y_pred = clf.predict(x_test)\n y_prob = clf.predict_prob(x_test)\n decision_function = clf.decision_function(x_test)\n\n print(\"y_prob\", y_prob)\n print(y_pred[y_prob < 0.5])\n print(y_pred[y_prob > 0.5])\n print(decision_function)\n precisionArray.append(Precision.precision(y_pred, y_test))\n\n folder_path = \"result/\"\n # mkdir(folder_path)\n np.savetxt(folder_path + \"predictions.txt\", precisionArray)\n precisionArray = np.round(np.mean(np.array(precisionArray), axis=0), 3)\n\n print(\n \"bad precision\",\n precisionArray[0],\n \"good precision\",\n precisionArray[1],\n \"type1\",\n precisionArray[2],\n \"type2\",\n precisionArray[3],\n \"total accuracy\",\n precisionArray[4],\n \"AUC\",\n precisionArray[5],\n )\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 21 10:42:19 2017\nMaybe not used for now.\n@author: Dyt\n\"\"\"\n\n# linear kernel 有没有用到gammal参数?\n\nimport math\nimport numpy as np\nfrom numpy import linalg as LA\n\n'''\ndef kernel_cal(x1,x2,k_type,gammaVal):\n #x1,x2 numpy.array\n\t\n\tnum = x1.shape[0]\n\tfor i in range(num):\n diff = x1[i, :] - x2\n K = exp(numpy.dot(diff,diff) / (-gammaVal)) \n \n\tif k_type == 'rbf': \n K = numpy.dot(x1,x2)\n\t\t\n return K\n'''\n\n\nclass kernel:\n # samples is the number of samples\n def __init__(self, samples):\n '''\n Two Mat must be converted into np.array\n '''\n self.samples = samples\n self.kernelMat = np.zeros((samples, samples))\n self.testMat = None\n\n def call(self, i, j):\n return self.kernelMat[i][j]\n\n def _call_test(self, idx_test, idx_train):\n return self.testMat[idx_test][idx_train]\n\n\nclass RBF(kernel):\n def __init__(self, samples, sigma):\n kernel.__init__(self, samples)\n self.sigma = sigma;\n\n def calculate(self, X):\n X2 = np.sum(np.multiply(X, X), 1) # sum colums of the matrix\n K0 = np.matrix(X2) + np.matrix(X2).T - 2 * np.dot(X, X.T)\n self.kernelMat = np.array(np.power(np.exp(-1.0 / (2*self.sigma ** 2)), K0))\n self.X = X\n '''\n Calculate the kernel for test data\n '''\n def expand(self, Xtest):\n X2_train = np.sum(np.multiply(self.X, self.X), 1)\n X2_test = np.sum(np.multiply(Xtest, Xtest), 1)\n tmp = np.matrix(X2_train) + np.matrix(X2_test).T\n if tmp.shape[0] != X2_test.shape[0]:\n tmp = tmp.T\n K0 = tmp - 2 * np.dot(Xtest, self.X.T)\n # K0 = np.matrix(X2_train).T + np.matrix(X2_test) -2 * np.dot(Xtest,self.X.T)\n self.testMat = np.array(np.power(np.exp(-1.0 / (2*self.sigma ** 2)), K0))\n\n\nclass LINEAR(kernel):\n def __init__(self, samples):\n kernel.__init__(self, samples)\n\n def calculate(self, X):\n self.kernelMat = np.dot(X, X.T)\n self.X = X\n\n def expand(self, Xtest):\n self.testMat = np.dot(Xtest, self.X.T)\n\n\nclass POLY(kernel):\n # c>=0 d in N+\n def __init__(self, samples, d=2):\n kernel.__init__(self, samples)\n self.d = d\n\n def calculate(self, X):\n self.kernelMat = np.power((np.dot(X, X.T) + 1), self.d)\n self.X = X\n\n def expand(self, Xtest):\n self.testMat = np.power((np.dot(Xtest, self.X.T) + 1), self.d)"
] |
[
[
"numpy.matrix",
"numpy.dot",
"numpy.linalg.solve",
"numpy.multiply",
"numpy.asarray",
"numpy.eye",
"sklearn.model_selection.train_test_split",
"numpy.linalg.norm",
"numpy.ones",
"numpy.concatenate",
"numpy.exp",
"numpy.append",
"numpy.mean",
"numpy.savetxt",
"numpy.array",
"numpy.zeros"
],
[
"numpy.matrix",
"numpy.dot",
"numpy.multiply",
"numpy.exp",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Jf-Chen/FRN-main
|
[
"5b57b9e0d7368058a8e3ba41a53c460b54ab9b91",
"5b57b9e0d7368058a8e3ba41a53c460b54ab9b91"
] |
[
"models/Proto.py",
"experiments/CUB_fewshot_cropped/Proto/Conv-4_1-shot/test.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision.models as torch_models\nimport numpy as np\nfrom .backbones import Conv_4,ResNet\n\ndef pdist(x,y):\n '''\n Input: x is a Nxd matrix\n y is an optional Mxd matirx\n Output: dist is a NxM matrix where dist[i,j] is the square norm between x[i,:] and y[j,:]\n if y is not given then use 'y=x'.\n i.e. dist[i,j] = ||x[i,:]-y[j,:]||^2\n '''\n x_norm = (x**2).sum(1).view(-1, 1)\n y_t = torch.transpose(y, 0, 1)\n y_norm = (y**2).sum(1).view(1, -1)\n dist = x_norm + y_norm - 2.0 * torch.mm(x, y_t)\n\n return dist\n\nclass Proto(nn.Module):\n \n def __init__(self,way=None,shots=None,resnet=False):\n \n super().__init__()\n \n if resnet:\n self.dim = 640\n self.feature_extractor = ResNet.resnet12()\n else:\n num_channel = 64\n self.feature_extractor = Conv_4.BackBone(num_channel) \n self.dim = num_channel*5*5\n\n self.shots = shots\n self.way = way\n self.resnet = resnet\n\n # temperature scaling, correspond to gamma in the paper\n self.scale = nn.Parameter(torch.FloatTensor([1.0]),requires_grad=True)\n \n\n def get_feature_vector(self,inp):\n \n batch_size = inp.size(0)\n feature_map = self.feature_extractor(inp)\n if self.resnet:\n feature_map = F.avg_pool2d(input=feature_map,kernel_size=feature_map.size(-1))\n feature_vector = feature_map.view(batch_size,self.dim)\n else:\n feature_vector = feature_map.view(batch_size,self.dim)\n \n return feature_vector\n \n\n def get_neg_l2_dist(self,inp,way,shot,query_shot):\n \n feature_vector = self.get_feature_vector(inp) \n\n support = feature_vector[:way*shot].view(way,shot,self.dim)\n centroid = torch.mean(support,1) # way,dim\n\n query = feature_vector[way*shot:] # way*query_shot,dim\n neg_l2_dist = pdist(query,centroid).neg().view(way*query_shot,way) #way*query_shot,way\n \n return neg_l2_dist\n\n\n\n \n def meta_test(self,inp,way,shot,query_shot):\n\n neg_l2_dist = self.get_neg_l2_dist(inp=inp,\n way=way,\n shot=shot,\n query_shot=query_shot)\n\n _,max_index = torch.max(neg_l2_dist,1)\n\n return max_index\n\n\n def forward(self,inp):\n\n neg_l2_dist = self.get_neg_l2_dist(inp=inp,\n way=self.way,\n shot=self.shots[0],\n query_shot=self.shots[1])\n \n logits = neg_l2_dist/self.dim*self.scale\n log_prediction = F.log_softmax(logits,dim=1)\n\n return log_prediction",
"import sys\nimport os\nimport torch\nimport yaml\nsys.path.append('../../../../')\nfrom models.Proto import Proto\nfrom utils import util\nfrom trainers.eval import meta_test\n\n\nwith open('../../../../config.yml', 'r') as f:\n temp = yaml.safe_load(f)\ndata_path = os.path.abspath(temp['data_path'])\n\ntest_path = os.path.join(data_path,'CUB_fewshot_cropped/test_pre')\nmodel_path = './model_Conv-4.pth'\n\ngpu = 0\ntorch.cuda.set_device(gpu)\n\nmodel = Proto(resnet=False)\nmodel.cuda()\nmodel.load_state_dict(torch.load(model_path,map_location=util.get_device_map(gpu)),strict=True)\nmodel.eval()\n\nwith torch.no_grad():\n way = 5\n for shot in [1]:\n mean,interval = meta_test(data_path=test_path,\n model=model,\n way=way,\n shot=shot,\n pre=True,\n transform_type=None,\n trial=10000)\n print('%d-way-%d-shot acc: %.3f\\t%.3f'%(way,shot,mean,interval))"
] |
[
[
"torch.mean",
"torch.transpose",
"torch.mm",
"torch.max",
"torch.nn.functional.log_softmax",
"torch.FloatTensor"
],
[
"torch.no_grad",
"torch.cuda.set_device"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tanelk/spark
|
[
"544865db77d942fbbeabde96e644c98a892d5045"
] |
[
"python/pyspark/pandas/tests/test_dataframe_spark_io.py"
] |
[
"#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport unittest\nimport glob\nimport os\n\nimport numpy as np\nimport pandas as pd\n\nfrom pyspark import pandas as ps\nfrom pyspark.testing.pandasutils import PandasOnSparkTestCase, TestUtils\n\n\nclass DataFrameSparkIOTest(PandasOnSparkTestCase, TestUtils):\n \"\"\"Test cases for big data I/O using Spark.\"\"\"\n\n @property\n def test_column_order(self):\n return [\"i32\", \"i64\", \"f\", \"bhello\"]\n\n @property\n def test_pdf(self):\n pdf = pd.DataFrame(\n {\n \"i32\": np.arange(20, dtype=np.int32) % 3,\n \"i64\": np.arange(20, dtype=np.int64) % 5,\n \"f\": np.arange(20, dtype=np.float64),\n \"bhello\": np.random.choice([\"hello\", \"yo\", \"people\"], size=20).astype(\"O\"),\n },\n columns=self.test_column_order,\n index=np.random.rand(20),\n )\n return pdf\n\n def test_parquet_read(self):\n with self.temp_dir() as tmp:\n data = self.test_pdf\n self.spark.createDataFrame(data, \"i32 int, i64 long, f double, bhello string\").coalesce(\n 1\n ).write.parquet(tmp, mode=\"overwrite\")\n\n def check(columns):\n expected = pd.read_parquet(tmp, columns=columns)\n actual = ps.read_parquet(tmp, columns=columns)\n self.assertPandasEqual(expected, actual.to_pandas())\n\n check(None)\n check([\"i32\", \"i64\"])\n check([\"i64\", \"i32\"])\n\n # check with pyspark patch.\n expected = pd.read_parquet(tmp)\n actual = ps.read_parquet(tmp)\n self.assertPandasEqual(expected, actual.to_pandas())\n\n # When index columns are known\n pdf = self.test_pdf\n expected = ps.DataFrame(pdf)\n\n expected_idx = expected.set_index(\"bhello\")[[\"f\", \"i32\", \"i64\"]]\n actual_idx = ps.read_parquet(tmp, index_col=\"bhello\")[[\"f\", \"i32\", \"i64\"]]\n self.assert_eq(\n actual_idx.sort_values(by=\"f\").to_spark().toPandas(),\n expected_idx.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n def test_parquet_read_with_pandas_metadata(self):\n with self.temp_dir() as tmp:\n expected1 = self.test_pdf\n\n path1 = \"{}/file1.parquet\".format(tmp)\n expected1.to_parquet(path1)\n\n self.assert_eq(ps.read_parquet(path1, pandas_metadata=True), expected1)\n\n expected2 = expected1.reset_index()\n\n path2 = \"{}/file2.parquet\".format(tmp)\n expected2.to_parquet(path2)\n\n self.assert_eq(ps.read_parquet(path2, pandas_metadata=True), expected2)\n\n expected3 = expected2.set_index(\"index\", append=True)\n\n path3 = \"{}/file3.parquet\".format(tmp)\n expected3.to_parquet(path3)\n\n self.assert_eq(ps.read_parquet(path3, pandas_metadata=True), expected3)\n\n def test_parquet_write(self):\n with self.temp_dir() as tmp:\n pdf = self.test_pdf\n expected = ps.DataFrame(pdf)\n\n # Write out partitioned by one column\n expected.to_parquet(tmp, mode=\"overwrite\", partition_cols=\"i32\")\n # Reset column order, as once the data is written out, Spark rearranges partition\n # columns to appear first.\n actual = ps.read_parquet(tmp)\n self.assertFalse((actual.columns == self.test_column_order).all())\n actual = actual[self.test_column_order]\n self.assert_eq(\n actual.sort_values(by=\"f\").to_spark().toPandas(),\n expected.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n # Write out partitioned by two columns\n expected.to_parquet(tmp, mode=\"overwrite\", partition_cols=[\"i32\", \"bhello\"])\n # Reset column order, as once the data is written out, Spark rearranges partition\n # columns to appear first.\n actual = ps.read_parquet(tmp)\n self.assertFalse((actual.columns == self.test_column_order).all())\n actual = actual[self.test_column_order]\n self.assert_eq(\n actual.sort_values(by=\"f\").to_spark().toPandas(),\n expected.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n def test_table(self):\n with self.table(\"test_table\"):\n pdf = self.test_pdf\n expected = ps.DataFrame(pdf)\n\n # Write out partitioned by one column\n expected.spark.to_table(\"test_table\", mode=\"overwrite\", partition_cols=\"i32\")\n # Reset column order, as once the data is written out, Spark rearranges partition\n # columns to appear first.\n actual = ps.read_table(\"test_table\")\n self.assertFalse((actual.columns == self.test_column_order).all())\n actual = actual[self.test_column_order]\n self.assert_eq(\n actual.sort_values(by=\"f\").to_spark().toPandas(),\n expected.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n # Write out partitioned by two columns\n expected.to_table(\"test_table\", mode=\"overwrite\", partition_cols=[\"i32\", \"bhello\"])\n # Reset column order, as once the data is written out, Spark rearranges partition\n # columns to appear first.\n actual = ps.read_table(\"test_table\")\n self.assertFalse((actual.columns == self.test_column_order).all())\n actual = actual[self.test_column_order]\n self.assert_eq(\n actual.sort_values(by=\"f\").to_spark().toPandas(),\n expected.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n # When index columns are known\n expected_idx = expected.set_index(\"bhello\")[[\"f\", \"i32\", \"i64\"]]\n actual_idx = ps.read_table(\"test_table\", index_col=\"bhello\")[[\"f\", \"i32\", \"i64\"]]\n self.assert_eq(\n actual_idx.sort_values(by=\"f\").to_spark().toPandas(),\n expected_idx.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n expected_idx = expected.set_index([\"bhello\"])[[\"f\", \"i32\", \"i64\"]]\n actual_idx = ps.read_table(\"test_table\", index_col=[\"bhello\"])[[\"f\", \"i32\", \"i64\"]]\n self.assert_eq(\n actual_idx.sort_values(by=\"f\").to_spark().toPandas(),\n expected_idx.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n expected_idx = expected.set_index([\"i32\", \"bhello\"])[[\"f\", \"i64\"]]\n actual_idx = ps.read_table(\"test_table\", index_col=[\"i32\", \"bhello\"])[[\"f\", \"i64\"]]\n self.assert_eq(\n actual_idx.sort_values(by=\"f\").to_spark().toPandas(),\n expected_idx.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n def test_spark_io(self):\n with self.temp_dir() as tmp:\n pdf = self.test_pdf\n expected = ps.DataFrame(pdf)\n\n # Write out partitioned by one column\n expected.to_spark_io(tmp, format=\"json\", mode=\"overwrite\", partition_cols=\"i32\")\n # Reset column order, as once the data is written out, Spark rearranges partition\n # columns to appear first.\n actual = ps.read_spark_io(tmp, format=\"json\")\n self.assertFalse((actual.columns == self.test_column_order).all())\n actual = actual[self.test_column_order]\n self.assert_eq(\n actual.sort_values(by=\"f\").to_spark().toPandas(),\n expected.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n # Write out partitioned by two columns\n expected.to_spark_io(\n tmp, format=\"json\", mode=\"overwrite\", partition_cols=[\"i32\", \"bhello\"]\n )\n # Reset column order, as once the data is written out, Spark rearranges partition\n # columns to appear first.\n actual = ps.read_spark_io(path=tmp, format=\"json\")\n self.assertFalse((actual.columns == self.test_column_order).all())\n actual = actual[self.test_column_order]\n self.assert_eq(\n actual.sort_values(by=\"f\").to_spark().toPandas(),\n expected.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n # When index columns are known\n pdf = self.test_pdf\n expected = ps.DataFrame(pdf)\n col_order = [\"f\", \"i32\", \"i64\"]\n\n expected_idx = expected.set_index(\"bhello\")[col_order]\n actual_idx = ps.read_spark_io(tmp, format=\"json\", index_col=\"bhello\")[col_order]\n self.assert_eq(\n actual_idx.sort_values(by=\"f\").to_spark().toPandas(),\n expected_idx.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n @unittest.skip(\"openpyxl\")\n def test_read_excel(self):\n with self.temp_dir() as tmp:\n\n path1 = \"{}/file1.xlsx\".format(tmp)\n self.test_pdf[[\"i32\"]].to_excel(path1)\n\n self.assert_eq(ps.read_excel(open(path1, \"rb\")), pd.read_excel(open(path1, \"rb\")))\n self.assert_eq(\n ps.read_excel(open(path1, \"rb\"), index_col=0),\n pd.read_excel(open(path1, \"rb\"), index_col=0),\n )\n self.assert_eq(\n ps.read_excel(open(path1, \"rb\"), index_col=0, squeeze=True),\n pd.read_excel(open(path1, \"rb\"), index_col=0, squeeze=True),\n )\n\n self.assert_eq(ps.read_excel(path1), pd.read_excel(path1))\n self.assert_eq(ps.read_excel(path1, index_col=0), pd.read_excel(path1, index_col=0))\n self.assert_eq(\n ps.read_excel(path1, index_col=0, squeeze=True),\n pd.read_excel(path1, index_col=0, squeeze=True),\n )\n\n self.assert_eq(ps.read_excel(tmp), pd.read_excel(path1))\n\n path2 = \"{}/file2.xlsx\".format(tmp)\n self.test_pdf[[\"i32\"]].to_excel(path2)\n self.assert_eq(\n ps.read_excel(tmp, index_col=0).sort_index(),\n pd.concat(\n [pd.read_excel(path1, index_col=0), pd.read_excel(path2, index_col=0)]\n ).sort_index(),\n )\n self.assert_eq(\n ps.read_excel(tmp, index_col=0, squeeze=True).sort_index(),\n pd.concat(\n [\n pd.read_excel(path1, index_col=0, squeeze=True),\n pd.read_excel(path2, index_col=0, squeeze=True),\n ]\n ).sort_index(),\n )\n\n with self.temp_dir() as tmp:\n path1 = \"{}/file1.xlsx\".format(tmp)\n with pd.ExcelWriter(path1) as writer:\n self.test_pdf.to_excel(writer, sheet_name=\"Sheet_name_1\")\n self.test_pdf[[\"i32\"]].to_excel(writer, sheet_name=\"Sheet_name_2\")\n\n sheet_names = [[\"Sheet_name_1\", \"Sheet_name_2\"], None]\n\n pdfs1 = pd.read_excel(open(path1, \"rb\"), sheet_name=None, index_col=0)\n pdfs1_squeezed = pd.read_excel(\n open(path1, \"rb\"), sheet_name=None, index_col=0, squeeze=True\n )\n\n for sheet_name in sheet_names:\n psdfs = ps.read_excel(open(path1, \"rb\"), sheet_name=sheet_name, index_col=0)\n self.assert_eq(psdfs[\"Sheet_name_1\"], pdfs1[\"Sheet_name_1\"])\n self.assert_eq(psdfs[\"Sheet_name_2\"], pdfs1[\"Sheet_name_2\"])\n\n psdfs = ps.read_excel(\n open(path1, \"rb\"), sheet_name=sheet_name, index_col=0, squeeze=True\n )\n self.assert_eq(psdfs[\"Sheet_name_1\"], pdfs1_squeezed[\"Sheet_name_1\"])\n self.assert_eq(psdfs[\"Sheet_name_2\"], pdfs1_squeezed[\"Sheet_name_2\"])\n\n self.assert_eq(\n ps.read_excel(tmp, index_col=0, sheet_name=\"Sheet_name_2\"),\n pdfs1[\"Sheet_name_2\"],\n )\n\n for sheet_name in sheet_names:\n psdfs = ps.read_excel(tmp, sheet_name=sheet_name, index_col=0)\n self.assert_eq(psdfs[\"Sheet_name_1\"], pdfs1[\"Sheet_name_1\"])\n self.assert_eq(psdfs[\"Sheet_name_2\"], pdfs1[\"Sheet_name_2\"])\n\n psdfs = ps.read_excel(tmp, sheet_name=sheet_name, index_col=0, squeeze=True)\n self.assert_eq(psdfs[\"Sheet_name_1\"], pdfs1_squeezed[\"Sheet_name_1\"])\n self.assert_eq(psdfs[\"Sheet_name_2\"], pdfs1_squeezed[\"Sheet_name_2\"])\n\n path2 = \"{}/file2.xlsx\".format(tmp)\n with pd.ExcelWriter(path2) as writer:\n self.test_pdf.to_excel(writer, sheet_name=\"Sheet_name_1\")\n self.test_pdf[[\"i32\"]].to_excel(writer, sheet_name=\"Sheet_name_2\")\n\n pdfs2 = pd.read_excel(path2, sheet_name=None, index_col=0)\n pdfs2_squeezed = pd.read_excel(path2, sheet_name=None, index_col=0, squeeze=True)\n\n self.assert_eq(\n ps.read_excel(tmp, sheet_name=\"Sheet_name_2\", index_col=0).sort_index(),\n pd.concat([pdfs1[\"Sheet_name_2\"], pdfs2[\"Sheet_name_2\"]]).sort_index(),\n )\n self.assert_eq(\n ps.read_excel(\n tmp, sheet_name=\"Sheet_name_2\", index_col=0, squeeze=True\n ).sort_index(),\n pd.concat(\n [pdfs1_squeezed[\"Sheet_name_2\"], pdfs2_squeezed[\"Sheet_name_2\"]]\n ).sort_index(),\n )\n\n for sheet_name in sheet_names:\n psdfs = ps.read_excel(tmp, sheet_name=sheet_name, index_col=0)\n self.assert_eq(\n psdfs[\"Sheet_name_1\"].sort_index(),\n pd.concat([pdfs1[\"Sheet_name_1\"], pdfs2[\"Sheet_name_1\"]]).sort_index(),\n )\n self.assert_eq(\n psdfs[\"Sheet_name_2\"].sort_index(),\n pd.concat([pdfs1[\"Sheet_name_2\"], pdfs2[\"Sheet_name_2\"]]).sort_index(),\n )\n\n psdfs = ps.read_excel(tmp, sheet_name=sheet_name, index_col=0, squeeze=True)\n self.assert_eq(\n psdfs[\"Sheet_name_1\"].sort_index(),\n pd.concat(\n [pdfs1_squeezed[\"Sheet_name_1\"], pdfs2_squeezed[\"Sheet_name_1\"]]\n ).sort_index(),\n )\n self.assert_eq(\n psdfs[\"Sheet_name_2\"].sort_index(),\n pd.concat(\n [pdfs1_squeezed[\"Sheet_name_2\"], pdfs2_squeezed[\"Sheet_name_2\"]]\n ).sort_index(),\n )\n\n def test_read_orc(self):\n with self.temp_dir() as tmp:\n path = \"{}/file1.orc\".format(tmp)\n data = self.test_pdf\n self.spark.createDataFrame(data, \"i32 int, i64 long, f double, bhello string\").coalesce(\n 1\n ).write.orc(path, mode=\"overwrite\")\n\n # `spark.write.orc` create a directory contains distributed orc files.\n # But pandas only can read from file, not directory. Therefore, we need orc file path.\n orc_file_path = glob.glob(os.path.join(path, \"*.orc\"))[0]\n\n expected = data.reset_index()[data.columns]\n actual = ps.read_orc(path)\n self.assertPandasEqual(expected, actual.to_pandas())\n\n # columns\n columns = [\"i32\", \"i64\"]\n expected = data.reset_index()[columns]\n actual = ps.read_orc(path, columns=columns)\n self.assertPandasEqual(expected, actual.to_pandas())\n\n # index_col\n expected = data.set_index(\"i32\")\n actual = ps.read_orc(path, index_col=\"i32\")\n self.assert_eq(actual, expected)\n\n expected = data.set_index([\"i32\", \"f\"])\n actual = ps.read_orc(path, index_col=[\"i32\", \"f\"])\n self.assert_eq(actual, expected)\n\n # index_col with columns\n expected = data.set_index(\"i32\")[[\"i64\", \"bhello\"]]\n actual = ps.read_orc(path, index_col=[\"i32\"], columns=[\"i64\", \"bhello\"])\n self.assert_eq(actual, expected)\n\n expected = data.set_index([\"i32\", \"f\"])[[\"bhello\", \"i64\"]]\n actual = ps.read_orc(path, index_col=[\"i32\", \"f\"], columns=[\"bhello\", \"i64\"])\n self.assert_eq(actual, expected)\n\n msg = \"Unknown column name 'i'\"\n with self.assertRaises(ValueError, msg=msg):\n ps.read_orc(path, columns=\"i32\")\n msg = \"Unknown column name 'i34'\"\n with self.assertRaises(ValueError, msg=msg):\n ps.read_orc(path, columns=[\"i34\", \"i64\"])\n\n def test_orc_write(self):\n with self.temp_dir() as tmp:\n pdf = self.test_pdf\n expected = ps.DataFrame(pdf)\n\n # Write out partitioned by one column\n expected.to_orc(tmp, mode=\"overwrite\", partition_cols=\"i32\")\n # Reset column order, as once the data is written out, Spark rearranges partition\n # columns to appear first.\n actual = ps.read_orc(tmp)\n self.assertFalse((actual.columns == self.test_column_order).all())\n actual = actual[self.test_column_order]\n self.assert_eq(\n actual.sort_values(by=\"f\").to_spark().toPandas(),\n expected.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n # Write out partitioned by two columns\n expected.to_orc(tmp, mode=\"overwrite\", partition_cols=[\"i32\", \"bhello\"])\n # Reset column order, as once the data is written out, Spark rearranges partition\n # columns to appear first.\n actual = ps.read_orc(tmp)\n self.assertFalse((actual.columns == self.test_column_order).all())\n actual = actual[self.test_column_order]\n self.assert_eq(\n actual.sort_values(by=\"f\").to_spark().toPandas(),\n expected.sort_values(by=\"f\").to_spark().toPandas(),\n )\n\n\nif __name__ == \"__main__\":\n from pyspark.pandas.tests.test_dataframe_spark_io import * # noqa: F401\n\n try:\n import xmlrunner # type: ignore[import]\n\n testRunner = xmlrunner.XMLTestRunner(output=\"target/test-reports\", verbosity=2)\n except ImportError:\n testRunner = None\n unittest.main(testRunner=testRunner, verbosity=2)\n"
] |
[
[
"pandas.concat",
"pandas.read_excel",
"numpy.random.choice",
"numpy.arange",
"pandas.read_parquet",
"numpy.random.rand",
"pandas.ExcelWriter"
]
] |
[
{
"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": []
}
] |
robertofratello/keras-tensorflow2.0compat
|
[
"09cf58de0b64b347fcbd06f30096528350dd47e6"
] |
[
"keras/backend/tensorflow_backend.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow.compat.v1 as tf\ntf.disable_eager_execution()\nfrom tensorflow.python.framework import ops as tf_ops\nfrom tensorflow.python.training import moving_averages\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import functional_ops\nfrom tensorflow.python.ops import ctc_ops as ctc\nfrom tensorflow.python.client import device_lib\nfrom tensorflow.core.protobuf import config_pb2\n\nfrom collections import defaultdict\n\nimport numpy as np\nfrom distutils.version import StrictVersion\nimport os\n\nfrom .common import floatx\nfrom .common import epsilon\nfrom .common import normalize_data_format\nfrom ..utils.generic_utils import transpose_shape\nfrom ..utils.generic_utils import has_arg\n\n# Legacy functions\nfrom .common import set_image_dim_ordering\nfrom .common import image_dim_ordering\n\npy_all = all\npy_any = any\npy_sum = sum\npy_slice = slice\n\n# INTERNAL UTILS\n\n# This is the default internal TF session used by Keras.\n# It can be set manually via `set_session(sess)`.\n_SESSION = None\n\n# This dictionary holds a mapping {graph: learning_phase}.\n# A learning phase is a bool tensor used to run Keras models in\n# either train mode (learning_phase == 1) or test mode (learning_phase == 0).\n_GRAPH_LEARNING_PHASES = {}\n\n# This dictionary holds a mapping {graph: UID_DICT}.\n# each UID_DICT is a dictionary mapping name prefixes to a current index,\n# used for generating graph-specific string UIDs\n# for various names (e.g. layer names).\n_GRAPH_UID_DICTS = {}\n\n# This boolean flag can be set to True to leave variable initialization\n# up to the user.\n# Change its value via `manual_variable_initialization(value)`.\n_MANUAL_VAR_INIT = False\n\n# This list holds the available devices.\n# It is populated when `_get_available_gpus()` is called for the first time.\n# We assume our devices don't change during our lifetime.\n_LOCAL_DEVICES = None\n\n\ndef get_uid(prefix=''):\n \"\"\"Get the uid for the default graph.\n\n # Arguments\n prefix: An optional prefix of the graph.\n\n # Returns\n A unique identifier for the graph.\n \"\"\"\n global _GRAPH_UID_DICTS\n graph = tf.get_default_graph()\n if graph not in _GRAPH_UID_DICTS:\n _GRAPH_UID_DICTS[graph] = defaultdict(int)\n _GRAPH_UID_DICTS[graph][prefix] += 1\n return _GRAPH_UID_DICTS[graph][prefix]\n\n\ndef reset_uids():\n \"\"\"Resets graph identifiers.\n \"\"\"\n global _GRAPH_UID_DICTS\n _GRAPH_UID_DICTS = {}\n\n\ndef clear_session():\n \"\"\"Destroys the current TF graph and creates a new one.\n\n Useful to avoid clutter from old models / layers.\n \"\"\"\n global _SESSION\n global _GRAPH_LEARNING_PHASES\n tf.reset_default_graph()\n reset_uids()\n _SESSION = None\n with tf.name_scope(''):\n phase = tf.placeholder_with_default(\n False,\n shape=(),\n name='keras_learning_phase')\n _GRAPH_LEARNING_PHASES = {}\n _GRAPH_LEARNING_PHASES[tf.get_default_graph()] = phase\n\n\ndef manual_variable_initialization(value):\n \"\"\"Sets the manual variable initialization flag.\n\n This boolean flag determines whether\n variables should be initialized\n as they are instantiated (default), or if\n the user should handle the initialization\n (e.g. via `tf.initialize_all_variables()`).\n\n # Arguments\n value: Python boolean.\n \"\"\"\n global _MANUAL_VAR_INIT\n _MANUAL_VAR_INIT = value\n\n\ndef learning_phase():\n \"\"\"Returns the learning phase flag.\n\n The learning phase flag is a bool tensor (0 = test, 1 = train)\n to be passed as input to any Keras function\n that uses a different behavior at train time and test time.\n\n # Returns\n Learning phase (scalar integer tensor or Python integer).\n \"\"\"\n graph = tf.get_default_graph()\n if graph not in _GRAPH_LEARNING_PHASES:\n with tf.name_scope(''):\n phase = tf.placeholder_with_default(\n False,\n shape=(),\n name='keras_learning_phase')\n _GRAPH_LEARNING_PHASES[graph] = phase\n return _GRAPH_LEARNING_PHASES[graph]\n\n\ndef set_learning_phase(value):\n \"\"\"Sets the learning phase to a fixed value.\n\n # Arguments\n value: Learning phase value, either 0 or 1 (integers).\n\n # Raises\n ValueError: if `value` is neither `0` nor `1`.\n \"\"\"\n global _GRAPH_LEARNING_PHASES\n if value not in {0, 1}:\n raise ValueError('Expected learning phase to be '\n '0 or 1.')\n _GRAPH_LEARNING_PHASES[tf.get_default_graph()] = value\n\n\ndef get_session():\n \"\"\"Returns the TF session to be used by the backend.\n\n If a default TensorFlow session is available, we will return it.\n\n Else, we will return the global Keras session.\n\n If no global Keras session exists at this point:\n we will create a new global session.\n\n Note that you can manually set the global session\n via `K.set_session(sess)`.\n\n # Returns\n A TensorFlow session.\n \"\"\"\n global _SESSION\n\n default_session = tf.get_default_session()\n\n if default_session is not None:\n session = default_session\n else:\n if _SESSION is None:\n if not os.environ.get('OMP_NUM_THREADS'):\n config = tf.ConfigProto(allow_soft_placement=True)\n else:\n num_thread = int(os.environ.get('OMP_NUM_THREADS'))\n config = tf.ConfigProto(intra_op_parallelism_threads=num_thread,\n inter_op_parallelism_threads=num_thread,\n allow_soft_placement=True)\n _SESSION = tf.Session(config=config)\n session = _SESSION\n if not _MANUAL_VAR_INIT:\n with session.graph.as_default():\n variables = tf.global_variables()\n candidate_vars = []\n for v in variables:\n if not getattr(v, '_keras_initialized', False):\n candidate_vars.append(v)\n if candidate_vars:\n # This step is expensive, so we only run it on variables\n # not already marked as initialized.\n is_initialized = session.run(\n [tf.is_variable_initialized(v) for v in candidate_vars])\n uninitialized_vars = []\n for flag, v in zip(is_initialized, candidate_vars):\n if not flag:\n uninitialized_vars.append(v)\n v._keras_initialized = True\n if uninitialized_vars:\n session.run(tf.variables_initializer(uninitialized_vars))\n # hack for list_devices() function.\n # list_devices() function is not available under tensorflow r1.3.\n if not hasattr(session, 'list_devices'):\n session.list_devices = lambda: device_lib.list_local_devices()\n return session\n\n\ndef set_session(session):\n \"\"\"Sets the global TensorFlow session.\n\n # Arguments\n session: A TF Session.\n \"\"\"\n global _SESSION\n _SESSION = session\n\n\n# DEVICE MANIPULATION AND PROBING\n\nclass _TfDeviceCaptureOp(object):\n \"\"\"Class for capturing the TF device scope.\"\"\"\n\n def __init__(self):\n self.device = None\n\n def _set_device(self, device):\n \"\"\"This method captures TF's explicit device scope setting.\"\"\"\n self.device = device\n\n\ndef _get_current_tf_device():\n \"\"\"Return explicit device of current context, otherwise returns `None`.\n\n # Returns\n If the current device scope is explicitly set, it returns a string with\n the device (`CPU` or `GPU`). If the scope is not explicitly set, it will\n return `None`.\n \"\"\"\n g = tf.get_default_graph()\n op = _TfDeviceCaptureOp()\n g._apply_device_functions(op)\n return op.device\n\n\ndef _is_current_explicit_device(device_type):\n \"\"\"Check if the current device is explicitly set on the device type specified.\n\n # Arguments\n device_type: A string containing `GPU` or `CPU` (case-insensitive).\n\n # Returns\n A boolean indicating if the current device\n scope is explicitly set on the device type.\n\n # Raises\n ValueError: If the `device_type` string indicates an unsupported device.\n \"\"\"\n device_type = device_type.upper()\n if device_type not in ['CPU', 'GPU']:\n raise ValueError('`device_type` should be either \"CPU\" or \"GPU\".')\n device = _get_current_tf_device()\n return (device is not None and device.device_type == device_type.upper())\n\n\ndef _get_available_gpus():\n \"\"\"Get a list of available gpu devices (formatted as strings).\n\n # Returns\n A list of available GPU devices.\n \"\"\"\n global _LOCAL_DEVICES\n if _LOCAL_DEVICES is None:\n _LOCAL_DEVICES = get_session().list_devices()\n return [x.name for x in _LOCAL_DEVICES if x.device_type == 'GPU']\n\n\ndef _has_nchw_support():\n \"\"\"Check whether the current scope supports NCHW ops.\n\n TensorFlow does not support NCHW on CPU.\n Therefore we check if we are not explicitly put on\n CPU, and have GPUs available.\n In this case there will be soft-placing on the GPU device.\n\n # Returns\n bool: if the current scope device placement would support nchw\n \"\"\"\n explicitly_on_cpu = _is_current_explicit_device('CPU')\n gpus_available = len(_get_available_gpus()) > 0\n return (not explicitly_on_cpu and gpus_available)\n\n\n# VARIABLE MANIPULATION\n\ndef _to_tensor(x, dtype):\n \"\"\"Convert the input `x` to a tensor of type `dtype`.\n\n # Arguments\n x: An object to be converted (numpy array, list, tensors).\n dtype: The destination type.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.convert_to_tensor(x, dtype=dtype)\n\n\ndef is_sparse(tensor):\n \"\"\"Returns whether a tensor is a sparse tensor.\n\n # Arguments\n tensor: A tensor instance.\n\n # Returns\n A boolean.\n\n # Example\n ```python\n >>> from keras import backend as K\n >>> a = K.placeholder((2, 2), sparse=False)\n >>> print(K.is_sparse(a))\n False\n >>> b = K.placeholder((2, 2), sparse=True)\n >>> print(K.is_sparse(b))\n True\n ```\n \"\"\"\n return isinstance(tensor, tf.SparseTensor)\n\n\ndef to_dense(tensor):\n \"\"\"Converts a sparse tensor into a dense tensor and returns it.\n\n # Arguments\n tensor: A tensor instance (potentially sparse).\n\n # Returns\n A dense tensor.\n\n # Examples\n ```python\n >>> from keras import backend as K\n >>> b = K.placeholder((2, 2), sparse=True)\n >>> print(K.is_sparse(b))\n True\n >>> c = K.to_dense(b)\n >>> print(K.is_sparse(c))\n False\n ```\n \"\"\"\n if is_sparse(tensor):\n return tf.sparse_tensor_to_dense(tensor)\n else:\n return tensor\n\n\nname_scope = tf.name_scope\n\n\ndef variable(value, dtype=None, name=None, constraint=None):\n \"\"\"Instantiates a variable and returns it.\n\n # Arguments\n value: Numpy array, initial value of the tensor.\n dtype: Tensor type.\n name: Optional name string for the tensor.\n constraint: Optional projection function to be\n applied to the variable after an optimizer update.\n\n # Returns\n A variable instance (with Keras metadata included).\n\n # Examples\n ```python\n >>> from keras import backend as K\n >>> val = np.array([[1, 2], [3, 4]])\n >>> kvar = K.variable(value=val, dtype='float64', name='example_var')\n >>> K.dtype(kvar)\n 'float64'\n >>> print(kvar)\n example_var\n >>> K.eval(kvar)\n array([[ 1., 2.],\n [ 3., 4.]])\n ```\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if hasattr(value, 'tocoo'):\n sparse_coo = value.tocoo()\n indices = np.concatenate((np.expand_dims(sparse_coo.row, 1),\n np.expand_dims(sparse_coo.col, 1)), 1)\n v = tf.SparseTensor(indices=indices,\n values=sparse_coo.data,\n dense_shape=sparse_coo.shape)\n v._keras_shape = sparse_coo.shape\n v._uses_learning_phase = False\n return v\n v = tf.Variable(value, dtype=tf.as_dtype(dtype), name=name)\n if isinstance(value, np.ndarray):\n v._keras_shape = value.shape\n elif hasattr(value, 'get_shape'):\n v._keras_shape = int_shape(value)\n v._uses_learning_phase = False\n # TODO: move to Variable constructor when supported in public release.\n try:\n v.constraint = constraint\n except AttributeError:\n v._constraint = constraint\n return v\n\n\ndef constant(value, dtype=None, shape=None, name=None):\n \"\"\"Creates a constant tensor.\n\n # Arguments\n value: A constant value (or list)\n dtype: The type of the elements of the resulting tensor.\n shape: Optional dimensions of resulting tensor.\n name: Optional name for the tensor.\n\n # Returns\n A Constant Tensor.\n \"\"\"\n if dtype is None:\n dtype = floatx()\n return tf.constant(value, dtype=dtype, shape=shape, name=name)\n\n\ndef is_keras_tensor(x):\n \"\"\"Returns whether `x` is a Keras tensor.\n\n A \"Keras tensor\" is a tensor that was returned by a Keras layer,\n (`Layer` class) or by `Input`.\n\n # Arguments\n x: A candidate tensor.\n\n # Returns\n A boolean: Whether the argument is a Keras tensor.\n\n # Raises\n ValueError: In case `x` is not a symbolic tensor.\n\n # Examples\n ```python\n >>> from keras import backend as K\n >>> from keras.layers import Input, Dense\n >>> np_var = numpy.array([1, 2])\n >>> K.is_keras_tensor(np_var) # A numpy array is not a symbolic tensor.\n ValueError\n >>> k_var = tf.placeholder('float32', shape=(1,1))\n >>> # A variable indirectly created outside of keras is not a Keras tensor.\n >>> K.is_keras_tensor(k_var)\n False\n >>> keras_var = K.variable(np_var)\n >>> # A variable created with the keras backend is not a Keras tensor.\n >>> K.is_keras_tensor(keras_var)\n False\n >>> keras_placeholder = K.placeholder(shape=(2, 4, 5))\n >>> # A placeholder is not a Keras tensor.\n >>> K.is_keras_tensor(keras_placeholder)\n False\n >>> keras_input = Input([10])\n >>> K.is_keras_tensor(keras_input) # An Input is a Keras tensor.\n True\n >>> keras_layer_output = Dense(10)(keras_input)\n >>> # Any Keras layer output is a Keras tensor.\n >>> K.is_keras_tensor(keras_layer_output)\n True\n ```\n \"\"\"\n if not is_tensor(x):\n raise ValueError('Unexpectedly found an instance of type `' +\n str(type(x)) + '`. '\n 'Expected a symbolic tensor instance.')\n return hasattr(x, '_keras_history')\n\n\ndef is_tensor(x):\n return isinstance(x, tf_ops._TensorLike) or tf_ops.is_dense_tensor_like(x)\n\n\ndef placeholder(shape=None, ndim=None, dtype=None, sparse=False, name=None):\n \"\"\"Instantiates a placeholder tensor and returns it.\n\n # Arguments\n shape: Shape of the placeholder\n (integer tuple, may include `None` entries).\n ndim: Number of axes of the tensor.\n At least one of {`shape`, `ndim`} must be specified.\n If both are specified, `shape` is used.\n dtype: Placeholder type.\n sparse: Boolean, whether the placeholder should have a sparse type.\n name: Optional name string for the placeholder.\n\n # Returns\n Tensor instance (with Keras metadata included).\n\n # Examples\n ```python\n >>> from keras import backend as K\n >>> input_ph = K.placeholder(shape=(2, 4, 5))\n >>> input_ph._keras_shape\n (2, 4, 5)\n >>> input_ph\n <tf.Tensor 'Placeholder_4:0' shape=(2, 4, 5) dtype=float32>\n ```\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if not shape:\n if ndim:\n shape = tuple([None for _ in range(ndim)])\n if sparse:\n x = tf.sparse_placeholder(dtype, shape=shape, name=name)\n else:\n x = tf.placeholder(dtype, shape=shape, name=name)\n x._keras_shape = shape\n x._uses_learning_phase = False\n return x\n\n\ndef is_placeholder(x):\n \"\"\"Returns whether `x` is a placeholder.\n\n # Arguments\n x: A candidate placeholder.\n\n # Returns\n Boolean.\n \"\"\"\n try:\n return x.op.type == 'Placeholder'\n except AttributeError:\n return False\n\n\ndef shape(x):\n \"\"\"Returns the symbolic shape of a tensor or variable.\n\n # Arguments\n x: A tensor or variable.\n\n # Returns\n A symbolic shape (which is itself a tensor).\n\n # Examples\n ```python\n # TensorFlow example\n >>> from keras import backend as K\n >>> tf_session = K.get_session()\n >>> val = np.array([[1, 2], [3, 4]])\n >>> kvar = K.variable(value=val)\n >>> inputs = keras.backend.placeholder(shape=(2, 4, 5))\n >>> K.shape(kvar)\n <tf.Tensor 'Shape_8:0' shape=(2,) dtype=int32>\n >>> K.shape(inputs)\n <tf.Tensor 'Shape_9:0' shape=(3,) dtype=int32>\n # To get integer shape (Instead, you can use K.int_shape(x))\n >>> K.shape(kvar).eval(session=tf_session)\n array([2, 2], dtype=int32)\n >>> K.shape(inputs).eval(session=tf_session)\n array([2, 4, 5], dtype=int32)\n ```\n \"\"\"\n return tf.shape(x)\n\n\ndef int_shape(x):\n \"\"\"Returns the shape of tensor or variable as a tuple of int or None entries.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tuple of integers (or None entries).\n\n # Examples\n ```python\n >>> from keras import backend as K\n >>> inputs = K.placeholder(shape=(2, 4, 5))\n >>> K.int_shape(inputs)\n (2, 4, 5)\n >>> val = np.array([[1, 2], [3, 4]])\n >>> kvar = K.variable(value=val)\n >>> K.int_shape(kvar)\n (2, 2)\n ```\n\n {{np_implementation}}\n \"\"\"\n if hasattr(x, '_keras_shape'):\n return x._keras_shape\n try:\n return tuple(x.get_shape().as_list())\n except ValueError:\n return None\n\n\ndef ndim(x):\n \"\"\"Returns the number of axes in a tensor, as an integer.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n Integer (scalar), number of axes.\n\n # Examples\n ```python\n >>> from keras import backend as K\n >>> inputs = K.placeholder(shape=(2, 4, 5))\n >>> val = np.array([[1, 2], [3, 4]])\n >>> kvar = K.variable(value=val)\n >>> K.ndim(inputs)\n 3\n >>> K.ndim(kvar)\n 2\n ```\n\n {{np_implementation}}\n \"\"\"\n dims = x.get_shape()._dims\n if dims is not None:\n return len(dims)\n return None\n\n\ndef dtype(x):\n \"\"\"Returns the dtype of a Keras tensor or variable, as a string.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n String, dtype of `x`.\n\n # Examples\n ```python\n >>> from keras import backend as K\n >>> K.dtype(K.placeholder(shape=(2,4,5)))\n 'float32'\n >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float32'))\n 'float32'\n >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float64'))\n 'float64'\n # Keras variable\n >>> kvar = K.variable(np.array([[1, 2], [3, 4]]))\n >>> K.dtype(kvar)\n 'float32_ref'\n >>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')\n >>> K.dtype(kvar)\n 'float32_ref'\n ```\n {{np_implementation}}\n \"\"\"\n return x.dtype.base_dtype.name\n\n\ndef eval(x):\n \"\"\"Evaluates the value of a variable.\n\n # Arguments\n x: A variable.\n\n # Returns\n A Numpy array.\n\n # Examples\n ```python\n >>> from keras import backend as K\n >>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')\n >>> K.eval(kvar)\n array([[ 1., 2.],\n [ 3., 4.]], dtype=float32)\n ```\n {{np_implementation}}\n \"\"\"\n return to_dense(x).eval(session=get_session())\n\n\ndef zeros(shape, dtype=None, name=None):\n \"\"\"Instantiates an all-zeros variable and returns it.\n\n # Arguments\n shape: Tuple of integers, shape of returned Keras variable\n dtype: String, data type of returned Keras variable\n name: String, name of returned Keras variable\n\n # Returns\n A variable (including Keras metadata), filled with `0.0`.\n Note that if `shape` was symbolic, we cannot return a variable,\n and will return a dynamically-shaped tensor instead.\n\n # Example\n ```python\n >>> from keras import backend as K\n >>> kvar = K.zeros((3,4))\n >>> K.eval(kvar)\n array([[ 0., 0., 0., 0.],\n [ 0., 0., 0., 0.],\n [ 0., 0., 0., 0.]], dtype=float32)\n ```\n {{np_implementation}}\n \"\"\"\n if dtype is None:\n dtype = floatx()\n tf_dtype = tf.as_dtype(dtype)\n v = tf.zeros(shape=shape, dtype=tf_dtype, name=name)\n if py_all(v.get_shape().as_list()):\n return variable(v, dtype=dtype, name=name)\n return v\n\n\ndef ones(shape, dtype=None, name=None):\n \"\"\"Instantiates an all-ones variable and returns it.\n\n # Arguments\n shape: Tuple of integers, shape of returned Keras variable.\n dtype: String, data type of returned Keras variable.\n name: String, name of returned Keras variable.\n\n # Returns\n A Keras variable, filled with `1.0`.\n Note that if `shape` was symbolic, we cannot return a variable,\n and will return a dynamically-shaped tensor instead.\n\n # Example\n ```python\n >>> from keras import backend as K\n >>> kvar = K.ones((3,4))\n >>> K.eval(kvar)\n array([[ 1., 1., 1., 1.],\n [ 1., 1., 1., 1.],\n [ 1., 1., 1., 1.]], dtype=float32)\n ```\n {{np_implementation}}\n \"\"\"\n if dtype is None:\n dtype = floatx()\n tf_dtype = tf.as_dtype(dtype)\n v = tf.ones(shape=shape, dtype=tf_dtype, name=name)\n if py_all(v.get_shape().as_list()):\n return variable(v, dtype=dtype, name=name)\n return v\n\n\ndef eye(size, dtype=None, name=None):\n \"\"\"Instantiate an identity matrix and returns it.\n\n # Arguments\n size: Tuple, number of rows and columns. If Integer, number of rows.\n dtype: String, data type of returned Keras variable.\n name: String, name of returned Keras variable.\n\n # Returns\n A Keras variable, an identity matrix.\n\n # Example\n ```python\n >>> from keras import backend as K\n >>> K.eval(K.eye(3))\n array([[ 1., 0., 0.],\n [ 0., 1., 0.],\n [ 0., 0., 1.]], dtype=float32)\n >>> K.eval(K.eye((2, 3)))\n array([[1., 0., 0.],\n [0., 1., 0.]], dtype=float32)\n ```\n {{np_implementation}}\n \"\"\"\n if dtype is None:\n dtype = floatx()\n tf_dtype = tf.as_dtype(dtype)\n if isinstance(size, (list, tuple)):\n n, m = size\n else:\n n, m = size, size\n return variable(tf.eye(n, m, dtype=tf_dtype), dtype, name)\n\n\ndef zeros_like(x, dtype=None, name=None):\n \"\"\"Instantiates an all-zeros variable of the same shape as another tensor.\n\n # Arguments\n x: Keras variable or Keras tensor.\n dtype: String, dtype of returned Keras variable.\n None uses the dtype of x.\n name: String, name for the variable to create.\n\n # Returns\n A Keras variable with the shape of x filled with zeros.\n\n # Example\n ```python\n >>> from keras import backend as K\n >>> kvar = K.variable(np.random.random((2,3)))\n >>> kvar_zeros = K.zeros_like(kvar)\n >>> K.eval(kvar_zeros)\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n ```\n {{np_implementation}}\n \"\"\"\n return tf.zeros_like(x, dtype=dtype, name=name)\n\n\ndef ones_like(x, dtype=None, name=None):\n \"\"\"Instantiates an all-ones variable of the same shape as another tensor.\n\n # Arguments\n x: Keras variable or tensor.\n dtype: String, dtype of returned Keras variable.\n None uses the dtype of x.\n name: String, name for the variable to create.\n\n # Returns\n A Keras variable with the shape of x filled with ones.\n\n # Example\n ```python\n >>> from keras import backend as K\n >>> kvar = K.variable(np.random.random((2,3)))\n >>> kvar_ones = K.ones_like(kvar)\n >>> K.eval(kvar_ones)\n array([[ 1., 1., 1.],\n [ 1., 1., 1.]], dtype=float32)\n ```\n {{np_implementation}}\n \"\"\"\n return tf.ones_like(x, dtype=dtype, name=name)\n\n\ndef identity(x, name=None):\n \"\"\"Returns a tensor with the same content as the input tensor.\n\n # Arguments\n x: The input tensor.\n name: String, name for the variable to create.\n\n # Returns\n A tensor of the same shape, type and content.\n \"\"\"\n return tf.identity(x, name)\n\n\ndef random_uniform_variable(shape, low, high, dtype=None,\n name=None, seed=None):\n \"\"\"Instantiates a variable with values drawn from a uniform distribution.\n\n # Arguments\n shape: Tuple of integers, shape of returned Keras variable.\n low: Float, lower boundary of the output interval.\n high: Float, upper boundary of the output interval.\n dtype: String, dtype of returned Keras variable.\n name: String, name of returned Keras variable.\n seed: Integer, random seed.\n\n # Returns\n A Keras variable, filled with drawn samples.\n\n # Example\n ```python\n # TensorFlow example\n >>> kvar = K.random_uniform_variable((2,3), 0, 1)\n >>> kvar\n <tensorflow.python.ops.variables.Variable object at 0x10ab40b10>\n >>> K.eval(kvar)\n array([[ 0.10940075, 0.10047495, 0.476143 ],\n [ 0.66137183, 0.00869417, 0.89220798]], dtype=float32)\n ```\n {{np_implementation}}\n \"\"\"\n if dtype is None:\n dtype = floatx()\n tf_dtype = tf.as_dtype(dtype)\n if seed is None:\n # ensure that randomness is conditioned by the Numpy RNG\n seed = np.random.randint(10e8)\n value = tf.random_uniform_initializer(\n low, high, dtype=tf_dtype, seed=seed)(shape)\n return variable(value, dtype=dtype, name=name)\n\n\ndef random_normal_variable(shape, mean, scale, dtype=None,\n name=None, seed=None):\n \"\"\"Instantiates a variable with values drawn from a normal distribution.\n\n # Arguments\n shape: Tuple of integers, shape of returned Keras variable.\n mean: Float, mean of the normal distribution.\n scale: Float, standard deviation of the normal distribution.\n dtype: String, dtype of returned Keras variable.\n name: String, name of returned Keras variable.\n seed: Integer, random seed.\n\n # Returns\n A Keras variable, filled with drawn samples.\n\n # Example\n ```python\n # TensorFlow example\n >>> kvar = K.random_normal_variable((2,3), 0, 1)\n >>> kvar\n <tensorflow.python.ops.variables.Variable object at 0x10ab12dd0>\n >>> K.eval(kvar)\n array([[ 1.19591331, 0.68685907, -0.63814116],\n [ 0.92629528, 0.28055015, 1.70484698]], dtype=float32)\n ```\n {{np_implementation}}\n \"\"\"\n if dtype is None:\n dtype = floatx()\n tf_dtype = tf.as_dtype(dtype)\n if seed is None:\n # ensure that randomness is conditioned by the Numpy RNG\n seed = np.random.randint(10e8)\n value = tf.random_normal_initializer(\n mean, scale, dtype=tf_dtype, seed=seed)(shape)\n return variable(value, dtype=dtype, name=name)\n\n\ndef count_params(x):\n \"\"\"Returns the static number of elements in a Keras variable or tensor.\n\n # Arguments\n x: Keras variable or tensor.\n\n # Returns\n Integer, the number of elements in `x`, i.e., the product of the\n array's static dimensions.\n\n # Example\n ```python\n >>> kvar = K.zeros((2,3))\n >>> K.count_params(kvar)\n 6\n >>> K.eval(kvar)\n array([[ 0., 0., 0.],\n [ 0., 0., 0.]], dtype=float32)\n ```\n {{np_implementation}}\n \"\"\"\n return np.prod(int_shape(x))\n\n\ndef cast(x, dtype):\n \"\"\"Casts a tensor to a different dtype and returns it.\n\n You can cast a Keras variable but it still returns a Keras tensor.\n\n # Arguments\n x: Keras tensor (or variable).\n dtype: String, either (`'float16'`, `'float32'`, or `'float64'`).\n\n # Returns\n Keras tensor with dtype `dtype`.\n\n # Example\n ```python\n >>> from keras import backend as K\n >>> input = K.placeholder((2, 3), dtype='float32')\n >>> input\n <tf.Tensor 'Placeholder_2:0' shape=(2, 3) dtype=float32>\n # It doesn't work in-place as below.\n >>> K.cast(input, dtype='float16')\n <tf.Tensor 'Cast_1:0' shape=(2, 3) dtype=float16>\n >>> input\n <tf.Tensor 'Placeholder_2:0' shape=(2, 3) dtype=float32>\n # you need to assign it.\n >>> input = K.cast(input, dtype='float16')\n >>> input\n <tf.Tensor 'Cast_2:0' shape=(2, 3) dtype=float16>\n ```\n \"\"\"\n return tf.cast(x, dtype)\n\n\n# UPDATES OPS\n\n\ndef update(x, new_x):\n \"\"\"Update the value of `x` to `new_x`.\n\n # Arguments\n x: A `Variable`.\n new_x: A tensor of same shape as `x`.\n\n # Returns\n The variable `x` updated.\n \"\"\"\n return tf.assign(x, new_x)\n\n\ndef update_add(x, increment):\n \"\"\"Update the value of `x` by adding `increment`.\n\n # Arguments\n x: A `Variable`.\n increment: A tensor of same shape as `x`.\n\n # Returns\n The variable `x` updated.\n \"\"\"\n return tf.assign_add(x, increment)\n\n\ndef update_sub(x, decrement):\n \"\"\"Update the value of `x` by subtracting `decrement`.\n\n # Arguments\n x: A `Variable`.\n decrement: A tensor of same shape as `x`.\n\n # Returns\n The variable `x` updated.\n \"\"\"\n return tf.assign_sub(x, decrement)\n\n\ndef moving_average_update(x, value, momentum):\n \"\"\"Compute the moving average of a variable.\n\n # Arguments\n x: A `Variable`.\n value: A tensor with the same shape as `x`.\n momentum: The moving average momentum.\n\n # Returns\n An operation to update the variable.\n \"\"\"\n if value.dtype != x.dtype:\n value = tf.cast(value, x.dtype)\n return moving_averages.assign_moving_average(\n x, value, momentum, zero_debias=True)\n\n\n# LINEAR ALGEBRA\n\ndef dot(x, y):\n \"\"\"Multiplies 2 tensors (and/or variables) and returns a *tensor*.\n\n When attempting to multiply a nD tensor\n with a nD tensor, it reproduces the Theano behavior.\n (e.g. `(2, 3) * (4, 3, 5) -> (2, 4, 5)`)\n\n # Arguments\n x: Tensor or variable.\n y: Tensor or variable.\n\n # Returns\n A tensor, dot product of `x` and `y`.\n\n # Examples\n ```python\n # dot product between tensors\n >>> x = K.placeholder(shape=(2, 3))\n >>> y = K.placeholder(shape=(3, 4))\n >>> xy = K.dot(x, y)\n >>> xy\n <tf.Tensor 'MatMul_9:0' shape=(2, 4) dtype=float32>\n ```\n\n ```python\n # dot product between tensors\n >>> x = K.placeholder(shape=(32, 28, 3))\n >>> y = K.placeholder(shape=(3, 4))\n >>> xy = K.dot(x, y)\n >>> xy\n <tf.Tensor 'MatMul_9:0' shape=(32, 28, 4) dtype=float32>\n ```\n\n ```python\n # Theano-like behavior example\n >>> x = K.random_uniform_variable(shape=(2, 3), low=0, high=1)\n >>> y = K.ones((4, 3, 5))\n >>> xy = K.dot(x, y)\n >>> K.int_shape(xy)\n (2, 4, 5)\n ```\n {{np_implementation}}\n \"\"\"\n if ndim(x) is not None and (ndim(x) > 2 or ndim(y) > 2):\n x_shape = []\n for i, s in zip(int_shape(x), tf.unstack(tf.shape(x))):\n if i is not None:\n x_shape.append(i)\n else:\n x_shape.append(s)\n x_shape = tuple(x_shape)\n y_shape = []\n for i, s in zip(int_shape(y), tf.unstack(tf.shape(y))):\n if i is not None:\n y_shape.append(i)\n else:\n y_shape.append(s)\n y_shape = tuple(y_shape)\n y_permute_dim = list(range(ndim(y)))\n y_permute_dim = [y_permute_dim.pop(-2)] + y_permute_dim\n xt = tf.reshape(x, [-1, x_shape[-1]])\n yt = tf.reshape(tf.transpose(y, perm=y_permute_dim), [y_shape[-2], -1])\n return tf.reshape(tf.matmul(xt, yt),\n x_shape[:-1] + y_shape[:-2] + y_shape[-1:])\n if is_sparse(x):\n out = tf.sparse_tensor_dense_matmul(x, y)\n else:\n out = tf.matmul(x, y)\n return out\n\n\ndef batch_dot(x, y, axes=None):\n \"\"\"Batchwise dot product.\n\n `batch_dot` is used to compute dot product of `x` and `y` when\n `x` and `y` are data in batches, i.e. in a shape of\n `(batch_size, :)`.\n `batch_dot` results in a tensor or variable with less dimensions\n than the input. If the number of dimensions is reduced to 1,\n we use `expand_dims` to make sure that ndim is at least 2.\n\n # Arguments\n x: Keras tensor or variable with `ndim >= 2`.\n y: Keras tensor or variable with `ndim >= 2`.\n axes: int or tuple(int, int). Target dimensions to be reduced.\n\n # Returns\n A tensor with shape equal to the concatenation of `x`'s shape\n (less the dimension that was summed over) and `y`'s shape\n (less the batch dimension and the dimension that was summed over).\n If the final rank is 1, we reshape it to `(batch_size, 1)`.\n\n # Examples\n Assume `x = [[1, 2], [3, 4]]` and `y = [[5, 6], [7, 8]]`\n `batch_dot(x, y, axes=1) = [[17], [53]]` which is the main diagonal\n of `x.dot(y.T)`, although we never have to calculate the off-diagonal\n elements.\n\n Pseudocode:\n ```\n inner_products = []\n for xi, yi in zip(x, y):\n inner_products.append(xi.dot(yi))\n result = stack(inner_products)\n ```\n\n Shape inference:\n Let `x`'s shape be `(100, 20)` and `y`'s shape be `(100, 30, 20)`.\n If `axes` is (1, 2), to find the output shape of resultant tensor,\n loop through each dimension in `x`'s shape and `y`'s shape:\n\n * `x.shape[0]` : 100 : append to output shape\n * `x.shape[1]` : 20 : do not append to output shape,\n dimension 1 of `x` has been summed over. (`dot_axes[0]` = 1)\n * `y.shape[0]` : 100 : do not append to output shape,\n always ignore first dimension of `y`\n * `y.shape[1]` : 30 : append to output shape\n * `y.shape[2]` : 20 : do not append to output shape,\n dimension 2 of `y` has been summed over. (`dot_axes[1]` = 2)\n `output_shape` = `(100, 30)`\n\n ```python\n >>> x_batch = K.ones(shape=(32, 20, 1))\n >>> y_batch = K.ones(shape=(32, 30, 20))\n >>> xy_batch_dot = K.batch_dot(x_batch, y_batch, axes=(1, 2))\n >>> K.int_shape(xy_batch_dot)\n (32, 1, 30)\n ```\n\n {{np_implementation}}\n \"\"\"\n x_shape = int_shape(x)\n y_shape = int_shape(y)\n\n x_ndim = len(x_shape)\n y_ndim = len(y_shape)\n\n if x_ndim < 2 or y_ndim < 2:\n raise ValueError('Can not do batch_dot on inputs '\n 'with rank < 2. '\n 'Received inputs with shapes ' +\n str(x_shape) + ' and ' +\n str(y_shape) + '.')\n\n x_batch_size = x_shape[0]\n y_batch_size = y_shape[0]\n\n if x_batch_size is not None and y_batch_size is not None:\n if x_batch_size != y_batch_size:\n raise ValueError('Can not do batch_dot on inputs '\n 'with different batch sizes. '\n 'Received inputs with shapes ' +\n str(x_shape) + ' and ' +\n str(y_shape) + '.')\n\n if isinstance(axes, int):\n axes = [axes, axes]\n\n if axes is None:\n if y_ndim == 2:\n axes = [x_ndim - 1, y_ndim - 1]\n else:\n axes = [x_ndim - 1, y_ndim - 2]\n\n if py_any([isinstance(a, (list, tuple)) for a in axes]):\n raise ValueError('Multiple target dimensions are not supported. ' +\n 'Expected: None, int, (int, int), ' +\n 'Provided: ' + str(axes))\n\n # if tuple, convert to list.\n axes = list(axes)\n\n # convert negative indices.\n if axes[0] < 0:\n axes[0] += x_ndim\n if axes[1] < 0:\n axes[1] += y_ndim\n\n # sanity checks\n if 0 in axes:\n raise ValueError('Can not perform batch_dot over axis 0.'\n 'If your inputs are not batched,'\n ' add a dummy batch dimension to your '\n 'inputs using K.expand_dims(x, 0)')\n\n a0, a1 = axes\n d1 = x_shape[a0]\n d2 = y_shape[a1]\n\n if d1 is not None and d2 is not None and d1 != d2:\n raise ValueError('Can not do batch_dot on inputs with shapes ' +\n str(x_shape) + ' and ' + str(y_shape) +\n ' with axes=' + str(axes) + '. x.shape[%d] != '\n 'y.shape[%d] (%d != %d).' % (axes[0], axes[1], d1, d2))\n\n # backup ndims. Need them later.\n orig_x_ndim = x_ndim\n orig_y_ndim = y_ndim\n\n # if rank is 2, expand to 3.\n if x_ndim == 2:\n x = tf.expand_dims(x, 1)\n a0 += 1\n x_ndim += 1\n if y_ndim == 2:\n y = tf.expand_dims(y, 2)\n y_ndim += 1\n\n # bring x's dimension to be reduced to last axis.\n if a0 != x_ndim - 1:\n pattern = list(range(x_ndim))\n for i in range(a0, x_ndim - 1):\n pattern[i] = pattern[i + 1]\n pattern[-1] = a0\n x = tf.transpose(x, pattern)\n\n # bring y's dimension to be reduced to axis 1.\n if a1 != 1:\n pattern = list(range(y_ndim))\n for i in range(a1, 1, -1):\n pattern[i] = pattern[i - 1]\n pattern[1] = a1\n y = tf.transpose(y, pattern)\n\n # normalize both inputs to rank 3.\n if x_ndim > 3:\n # squash middle dimensions of x.\n x_shape = shape(x)\n x_mid_dims = x_shape[1:-1]\n x_squashed_dim = tf.reduce_prod(x_mid_dims)\n x_squashed_shape = tf.stack([x_shape[0], x_squashed_dim, x_shape[-1]])\n x = tf.reshape(x, x_squashed_shape)\n x_squashed = True\n else:\n x_squashed = False\n\n if y_ndim > 3:\n # squash trailing dimensions of y.\n y_shape = shape(y)\n y_trail_dims = y_shape[2:]\n y_squashed_dim = tf.reduce_prod(y_trail_dims)\n y_squashed_shape = tf.stack([y_shape[0], y_shape[1], y_squashed_dim])\n y = tf.reshape(y, y_squashed_shape)\n y_squashed = True\n else:\n y_squashed = False\n\n result = tf.matmul(x, y)\n\n # if inputs were squashed, we have to reshape the matmul output.\n output_shape = tf.shape(result)\n do_reshape = False\n\n if x_squashed:\n output_shape = tf.concat([output_shape[:1],\n x_mid_dims,\n output_shape[-1:]], 0)\n do_reshape = True\n\n if y_squashed:\n output_shape = tf.concat([output_shape[:-1], y_trail_dims], 0)\n do_reshape = True\n\n if do_reshape:\n result = tf.reshape(result, output_shape)\n\n # if the inputs were originally rank 2, we remove the added 1 dim.\n if orig_x_ndim == 2:\n result = tf.squeeze(result, 1)\n elif orig_y_ndim == 2:\n result = tf.squeeze(result, -1)\n\n return result\n\n\ndef transpose(x):\n \"\"\"Transposes a tensor and returns it.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tensor.\n\n # Examples\n ```python\n >>> var = K.variable([[1, 2, 3], [4, 5, 6]])\n >>> K.eval(var)\n array([[ 1., 2., 3.],\n [ 4., 5., 6.]], dtype=float32)\n >>> var_transposed = K.transpose(var)\n >>> K.eval(var_transposed)\n array([[ 1., 4.],\n [ 2., 5.],\n [ 3., 6.]], dtype=float32)\n ```\n\n ```python\n >>> inputs = K.placeholder((2, 3))\n >>> inputs\n <tf.Tensor 'Placeholder_11:0' shape=(2, 3) dtype=float32>\n >>> input_transposed = K.transpose(inputs)\n >>> input_transposed\n <tf.Tensor 'transpose_4:0' shape=(3, 2) dtype=float32>\n\n ```\n {{np_implementation}}\n \"\"\"\n return tf.transpose(x)\n\n\ndef gather(reference, indices):\n \"\"\"Retrieves the elements of indices `indices` in the tensor `reference`.\n\n # Arguments\n reference: A tensor.\n indices: An integer tensor of indices.\n\n # Returns\n A tensor of same type as `reference`.\n\n {{np_implementation}}\n \"\"\"\n return tf.nn.embedding_lookup(reference, indices)\n\n\n# ELEMENT-WISE OPERATIONS\n\n\ndef max(x, axis=None, keepdims=False):\n \"\"\"Maximum value in a tensor.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer or list of integers in [-rank(x), rank(x)),\n the axes to find maximum values. If `None` (default), finds the\n maximum over all dimensions.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with maximum values of `x`.\n\n {{np_implementation}}\n \"\"\"\n return tf.reduce_max(x, axis, keepdims)\n\n\ndef min(x, axis=None, keepdims=False):\n \"\"\"Minimum value in a tensor.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer or list of integers in [-rank(x), rank(x)),\n the axes to find minimum values. If `None` (default), finds the\n minimum over all dimensions.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with miminum values of `x`.\n\n {{np_implementation}}\n \"\"\"\n return tf.reduce_min(x, axis, keepdims)\n\n\ndef sum(x, axis=None, keepdims=False):\n \"\"\"Sum of the values in a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer or list of integers in [-rank(x), rank(x)),\n the axes to sum over. If `None` (default), sums over all\n dimensions.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with sum of `x`.\n\n {{np_implementation}}\n \"\"\"\n return tf.reduce_sum(x, axis, keepdims)\n\n\ndef prod(x, axis=None, keepdims=False):\n \"\"\"Multiplies the values in a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer or list of integers in [-rank(x), rank(x)),\n the axes to compute the product. If `None` (default), computes\n the product over all dimensions.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with the product of elements of `x`.\n\n {{np_implementation}}\n \"\"\"\n return tf.reduce_prod(x, axis, keepdims)\n\n\ndef cumsum(x, axis=0):\n \"\"\"Cumulative sum of the values in a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer, the axis to compute the sum.\n\n # Returns\n A tensor of the cumulative sum of values of `x` along `axis`.\n {{np_implementation}}\n \"\"\"\n return tf.cumsum(x, axis=axis)\n\n\ndef cumprod(x, axis=0):\n \"\"\"Cumulative product of the values in a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer, the axis to compute the product.\n\n # Returns\n A tensor of the cumulative product of values of `x` along `axis`.\n {{np_implementation}}\n \"\"\"\n return tf.cumprod(x, axis=axis)\n\n\ndef var(x, axis=None, keepdims=False):\n \"\"\"Variance of a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer or list of integers in [-rank(x), rank(x)),\n the axes to compute the variance. If `None` (default), computes\n the variance over all dimensions.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with the variance of elements of `x`.\n {{np_implementation}}\n \"\"\"\n if x.dtype.base_dtype == tf.bool:\n x = tf.cast(x, floatx())\n m = tf.reduce_mean(x, axis, True)\n devs_squared = tf.square(x - m)\n return tf.reduce_mean(devs_squared,\n axis,\n keepdims)\n\n\ndef std(x, axis=None, keepdims=False):\n \"\"\"Standard deviation of a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer or list of integers in [-rank(x), rank(x)),\n the axes to compute the standard deviation. If `None` (default),\n computes the standard deviation over all dimensions.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n\n # Returns\n A tensor with the standard deviation of elements of `x`.\n {{np_implementation}}\n \"\"\"\n return tf.sqrt(var(x, axis=axis, keepdims=keepdims))\n\n\ndef mean(x, axis=None, keepdims=False):\n \"\"\"Mean of a tensor, alongside the specified axis.\n\n # Arguments\n x: A tensor or variable.\n axis: An integer or list of integers in [-rank(x), rank(x)),\n the axes to compute the mean. If `None` (default), computes\n the mean over all dimensions.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1 for each entry in `axis`. If `keepdims` is `True`,\n the reduced dimensions are retained with length 1.\n\n # Returns\n A tensor with the mean of elements of `x`.\n {{np_implementation}}\n \"\"\"\n if x.dtype.base_dtype == tf.bool:\n x = tf.cast(x, floatx())\n return tf.reduce_mean(x, axis, keepdims)\n\n\ndef any(x, axis=None, keepdims=False):\n \"\"\"Bitwise reduction (logical OR).\n\n # Arguments\n x: Tensor or variable.\n axis: An integer or list of integers in [-rank(x), rank(x)),\n the axes to compute the logical or. If `None` (default), computes\n the logical or over all dimensions.\n keepdims: whether the drop or broadcast the reduction axes.\n\n # Returns\n A uint8 tensor (0s and 1s).\n {{np_implementation}}\n \"\"\"\n x = tf.cast(x, tf.bool)\n return tf.reduce_any(x, axis, keepdims)\n\n\ndef all(x, axis=None, keepdims=False):\n \"\"\"Bitwise reduction (logical AND).\n\n # Arguments\n x: Tensor or variable.\n axis: An integer or list of integers in [-rank(x), rank(x)),\n the axes to compute the logical and. If `None` (default), computes\n the logical and over all dimensions.\n keepdims: whether the drop or broadcast the reduction axes.\n\n # Returns\n A uint8 tensor (0s and 1s).\n {{np_implementation}}\n \"\"\"\n x = tf.cast(x, tf.bool)\n return tf.reduce_all(x, axis, keepdims)\n\n\ndef argmax(x, axis=-1):\n \"\"\"Returns the index of the maximum value along an axis.\n\n # Arguments\n x: Tensor or variable.\n axis: axis along which to perform the reduction.\n\n # Returns\n A tensor.\n {{np_implementation}}\n \"\"\"\n return tf.argmax(x, axis)\n\n\ndef argmin(x, axis=-1):\n \"\"\"Returns the index of the minimum value along an axis.\n\n # Arguments\n x: Tensor or variable.\n axis: axis along which to perform the reduction.\n\n # Returns\n A tensor.\n {{np_implementation}}\n \"\"\"\n return tf.argmin(x, axis)\n\n\ndef square(x):\n \"\"\"Element-wise square.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.square(x)\n\n\ndef abs(x):\n \"\"\"Element-wise absolute value.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.abs(x)\n\n\ndef sqrt(x):\n \"\"\"Element-wise square root.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tensor.\n {{np_implementation}}\n \"\"\"\n zero = _to_tensor(0., x.dtype.base_dtype)\n inf = _to_tensor(np.inf, x.dtype.base_dtype)\n x = tf.clip_by_value(x, zero, inf)\n return tf.sqrt(x)\n\n\ndef exp(x):\n \"\"\"Element-wise exponential.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.exp(x)\n\n\ndef log(x):\n \"\"\"Element-wise log.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.log(x)\n\n\ndef logsumexp(x, axis=None, keepdims=False):\n \"\"\"Computes log(sum(exp(elements across dimensions of a tensor))).\n\n This function is more numerically stable than log(sum(exp(x))).\n It avoids overflows caused by taking the exp of large inputs and\n underflows caused by taking the log of small inputs.\n\n # Arguments\n x: A tensor or variable.\n axis: axis: An integer or list of integers in [-rank(x), rank(x)),\n the axes to compute the logsumexp. If `None` (default), computes\n the logsumexp over all dimensions.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`, the reduced dimension is\n retained with length 1.\n\n # Returns\n The reduced tensor.\n {{np_implementation}}\n \"\"\"\n return tf.reduce_logsumexp(x, axis, keepdims)\n\n\ndef round(x):\n \"\"\"Element-wise rounding to the closest integer.\n\n In case of tie, the rounding mode used is \"half to even\".\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.round(x)\n\n\ndef sign(x):\n \"\"\"Element-wise sign.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.sign(x)\n\n\ndef pow(x, a):\n \"\"\"Element-wise exponentiation.\n\n # Arguments\n x: Tensor or variable.\n a: Python integer.\n\n # Returns\n A tensor.\n {{np_implementation}}\n \"\"\"\n return tf.pow(x, a)\n\n\ndef clip(x, min_value, max_value):\n \"\"\"Element-wise value clipping.\n\n # Arguments\n x: Tensor or variable.\n min_value: Python float, integer or tensor.\n max_value: Python float, integer or tensor.\n\n # Returns\n A tensor.\n {{np_implementation}}\n \"\"\"\n if (isinstance(min_value, (int, float)) and\n isinstance(max_value, (int, float))):\n if max_value < min_value:\n max_value = min_value\n if min_value is None:\n min_value = -np.inf\n if max_value is None:\n max_value = np.inf\n return tf.clip_by_value(x, min_value, max_value)\n\n\ndef equal(x, y):\n \"\"\"Element-wise equality between two tensors.\n\n # Arguments\n x: Tensor or variable.\n y: Tensor or variable.\n\n # Returns\n A bool tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.equal(x, y)\n\n\ndef not_equal(x, y):\n \"\"\"Element-wise inequality between two tensors.\n\n # Arguments\n x: Tensor or variable.\n y: Tensor or variable.\n\n # Returns\n A bool tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.not_equal(x, y)\n\n\ndef greater(x, y):\n \"\"\"Element-wise truth value of (x > y).\n\n # Arguments\n x: Tensor or variable.\n y: Tensor or variable.\n\n # Returns\n A bool tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.greater(x, y)\n\n\ndef greater_equal(x, y):\n \"\"\"Element-wise truth value of (x >= y).\n\n # Arguments\n x: Tensor or variable.\n y: Tensor or variable.\n\n # Returns\n A bool tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.greater_equal(x, y)\n\n\ndef less(x, y):\n \"\"\"Element-wise truth value of (x < y).\n\n # Arguments\n x: Tensor or variable.\n y: Tensor or variable.\n\n # Returns\n A bool tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.less(x, y)\n\n\ndef less_equal(x, y):\n \"\"\"Element-wise truth value of (x <= y).\n\n # Arguments\n x: Tensor or variable.\n y: Tensor or variable.\n\n # Returns\n A bool tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.less_equal(x, y)\n\n\ndef maximum(x, y):\n \"\"\"Element-wise maximum of two tensors.\n\n # Arguments\n x: Tensor or variable.\n y: Tensor or variable.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.maximum(x, y)\n\n\ndef minimum(x, y):\n \"\"\"Element-wise minimum of two tensors.\n\n # Arguments\n x: Tensor or variable.\n y: Tensor or variable.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.minimum(x, y)\n\n\ndef sin(x):\n \"\"\"Computes sin of x element-wise.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.sin(x)\n\n\ndef cos(x):\n \"\"\"Computes cos of x element-wise.\n\n # Arguments\n x: Tensor or variable.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.cos(x)\n\n\ndef _regular_normalize_batch_in_training(x, gamma, beta,\n reduction_axes, epsilon=1e-3):\n \"\"\"Non-fused version of `normalize_batch_in_training`.\n\n # Arguments\n x: Input tensor or variable.\n gamma: Tensor by which to scale the input.\n beta: Tensor with which to center the input.\n reduction_axes: iterable of integers,\n axes over which to normalize.\n epsilon: Fuzz factor.\n\n # Returns\n A tuple length of 3, `(normalized_tensor, mean, variance)`.\n \"\"\"\n mean, var = tf.nn.moments(x, reduction_axes,\n None, None, False)\n normed = tf.nn.batch_normalization(x, mean, var,\n beta, gamma,\n epsilon)\n return normed, mean, var\n\n\ndef _broadcast_normalize_batch_in_training(x, gamma, beta,\n reduction_axes, epsilon=1e-3):\n \"\"\"Non-fused, broadcast version of `normalize_batch_in_training`.\n\n # Arguments\n x: Input tensor or variable.\n gamma: Tensor by which to scale the input.\n beta: Tensor with which to center the input.\n reduction_axes: iterable of integers,\n axes over which to normalize.\n epsilon: Fuzz factor.\n\n # Returns\n A tuple length of 3, `(normalized_tensor, mean, variance)`.\n \"\"\"\n mean, var = tf.nn.moments(x, reduction_axes,\n None, None, False)\n target_shape = []\n for axis in range(ndim(x)):\n if axis in reduction_axes:\n target_shape.append(1)\n else:\n target_shape.append(tf.shape(x)[axis])\n target_shape = tf.stack(target_shape)\n\n broadcast_mean = tf.reshape(mean, target_shape)\n broadcast_var = tf.reshape(var, target_shape)\n if gamma is None:\n broadcast_gamma = None\n else:\n broadcast_gamma = tf.reshape(gamma, target_shape)\n if beta is None:\n broadcast_beta = None\n else:\n broadcast_beta = tf.reshape(beta, target_shape)\n\n normed = tf.nn.batch_normalization(\n x,\n broadcast_mean,\n broadcast_var,\n broadcast_beta,\n broadcast_gamma,\n epsilon)\n return normed, mean, var\n\n\ndef _fused_normalize_batch_in_training(x, gamma, beta, reduction_axes,\n epsilon=1e-3):\n \"\"\"Fused version of `normalize_batch_in_training`.\n\n # Arguments\n x: Input tensor or variable.\n gamma: Tensor by which to scale the input.\n beta: Tensor with which to center the input.\n reduction_axes: iterable of integers,\n axes over which to normalize.\n epsilon: Fuzz factor.\n\n # Returns\n A tuple length of 3, `(normalized_tensor, mean, variance)`.\n \"\"\"\n if list(reduction_axes) == [0, 1, 2]:\n normalization_axis = 3\n tf_data_format = 'NHWC'\n else:\n normalization_axis = 1\n tf_data_format = 'NCHW'\n\n if gamma is None:\n gamma = tf.constant(1.0,\n dtype=x.dtype,\n shape=[x.get_shape()[normalization_axis]])\n if beta is None:\n beta = tf.constant(0.0,\n dtype=x.dtype,\n shape=[x.get_shape()[normalization_axis]])\n\n if gamma.dtype != tf.float32:\n gamma = tf.cast(gamma, tf.float32)\n if beta.dtype != tf.float32:\n beta = tf.cast(beta, tf.float32)\n\n return tf.nn.fused_batch_norm(\n x,\n gamma,\n beta,\n epsilon=epsilon,\n data_format=tf_data_format)\n\n\ndef normalize_batch_in_training(x, gamma, beta,\n reduction_axes, epsilon=1e-3):\n \"\"\"Computes mean and std for batch then apply batch_normalization on batch.\n\n # Arguments\n x: Input tensor or variable.\n gamma: Tensor by which to scale the input.\n beta: Tensor with which to center the input.\n reduction_axes: iterable of integers,\n axes over which to normalize.\n epsilon: Fuzz factor.\n\n # Returns\n A tuple length of 3, `(normalized_tensor, mean, variance)`.\n \"\"\"\n if ndim(x) == 4 and list(reduction_axes) in [[0, 1, 2], [0, 2, 3]]:\n if not _has_nchw_support() and list(reduction_axes) == [0, 2, 3]:\n return _broadcast_normalize_batch_in_training(x, gamma, beta,\n reduction_axes,\n epsilon=epsilon)\n return _fused_normalize_batch_in_training(\n x, gamma, beta, reduction_axes,\n epsilon=epsilon)\n else:\n if sorted(reduction_axes) == list(range(ndim(x)))[:-1]:\n return _regular_normalize_batch_in_training(x, gamma, beta,\n reduction_axes,\n epsilon=epsilon)\n else:\n return _broadcast_normalize_batch_in_training(x, gamma, beta,\n reduction_axes,\n epsilon=epsilon)\n\n\ndef batch_normalization(x, mean, var, beta, gamma, axis=-1, epsilon=1e-3):\n \"\"\"Applies batch normalization on x given mean, var, beta and gamma.\n\n I.e. returns:\n `output = (x - mean) / sqrt(var + epsilon) * gamma + beta`\n\n # Arguments\n x: Input tensor or variable.\n mean: Mean of batch.\n var: Variance of batch.\n beta: Tensor with which to center the input.\n gamma: Tensor by which to scale the input.\n axis: Integer, the axis that should be normalized.\n (typically the features axis).\n epsilon: Fuzz factor.\n\n # Returns\n A tensor.\n \"\"\"\n if ndim(x) == 4:\n # The CPU implementation of FusedBatchNorm only support NHWC\n if axis == 1 or axis == -3:\n tf_data_format = 'NCHW'\n elif axis == 3 or axis == -1:\n tf_data_format = 'NHWC'\n else:\n tf_data_format = None\n\n if (tf_data_format == 'NHWC'\n or tf_data_format == 'NCHW'\n and _has_nchw_support()):\n # The mean / var / beta / gamma may be processed by broadcast\n # so it may have extra axes with 1,\n # it is not needed and should be removed\n if ndim(mean) > 1:\n mean = tf.reshape(mean, [-1])\n if ndim(var) > 1:\n var = tf.reshape(var, [-1])\n if beta is None:\n beta = zeros_like(mean)\n elif ndim(beta) > 1:\n beta = tf.reshape(beta, [-1])\n if gamma is None:\n gamma = ones_like(mean)\n elif ndim(gamma) > 1:\n gamma = tf.reshape(gamma, [-1])\n\n if gamma.dtype != tf.float32:\n gamma = tf.cast(gamma, tf.float32)\n if beta.dtype != tf.float32:\n beta = tf.cast(beta, tf.float32)\n if mean.dtype != tf.float32:\n mean = tf.cast(mean, tf.float32)\n if var.dtype != tf.float32:\n var = tf.cast(var, tf.float32)\n\n y, _, _ = tf.nn.fused_batch_norm(\n x,\n gamma,\n beta,\n epsilon=epsilon,\n mean=mean,\n variance=var,\n data_format=tf_data_format,\n is_training=False\n )\n return y\n # default\n return tf.nn.batch_normalization(x, mean, var, beta, gamma, epsilon)\n\n\n# SHAPE OPERATIONS\n\ndef concatenate(tensors, axis=-1):\n \"\"\"Concatenates a list of tensors alongside the specified axis.\n\n # Arguments\n tensors: list of tensors to concatenate.\n axis: concatenation axis.\n\n # Returns\n A tensor.\n \"\"\"\n if axis < 0:\n rank = ndim(tensors[0])\n if rank:\n axis %= rank\n else:\n axis = 0\n\n if py_all([is_sparse(x) for x in tensors]):\n return tf.sparse_concat(axis, tensors)\n else:\n return tf.concat([to_dense(x) for x in tensors], axis)\n\n\ndef reshape(x, shape):\n \"\"\"Reshapes a tensor to the specified shape.\n\n # Arguments\n x: Tensor or variable.\n shape: Target shape tuple.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.reshape(x, shape)\n\n\ndef permute_dimensions(x, pattern):\n \"\"\"Permutes axes in a tensor.\n\n # Arguments\n x: Tensor or variable.\n pattern: A tuple of\n dimension indices, e.g. `(0, 2, 1)`.\n\n # Returns\n A tensor.\n \"\"\"\n return tf.transpose(x, perm=pattern)\n\n\ndef resize_images(x,\n height_factor,\n width_factor,\n data_format,\n interpolation='nearest'):\n \"\"\"Resizes the images contained in a 4D tensor.\n\n # Arguments\n x: Tensor or variable to resize.\n height_factor: Positive integer.\n width_factor: Positive integer.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n interpolation: A string, one of `nearest` or `bilinear`.\n\n # Returns\n A tensor.\n\n # Raises\n ValueError: if `data_format` is\n neither `\"channels_last\"` or `\"channels_first\"`.\n \"\"\"\n if data_format == 'channels_first':\n rows, cols = 2, 3\n else:\n rows, cols = 1, 2\n\n original_shape = int_shape(x)\n new_shape = tf.shape(x)[rows:cols + 1]\n new_shape *= tf.constant(np.array([height_factor, width_factor], dtype='int32'))\n\n if data_format == 'channels_first':\n x = permute_dimensions(x, [0, 2, 3, 1])\n if interpolation == 'nearest':\n x = tf.image.resize_nearest_neighbor(x, new_shape)\n elif interpolation == 'bilinear':\n x = tf.image.resize_bilinear(x, new_shape)\n else:\n raise ValueError('interpolation should be one '\n 'of \"nearest\" or \"bilinear\".')\n if data_format == 'channels_first':\n x = permute_dimensions(x, [0, 3, 1, 2])\n\n if original_shape[rows] is None:\n new_height = None\n else:\n new_height = original_shape[rows] * height_factor\n\n if original_shape[cols] is None:\n new_width = None\n else:\n new_width = original_shape[cols] * width_factor\n\n output_shape = (None, new_height, new_width, None)\n x.set_shape(transpose_shape(output_shape, data_format, spatial_axes=(1, 2)))\n return x\n\n\ndef resize_volumes(x, depth_factor, height_factor, width_factor, data_format):\n \"\"\"Resizes the volume contained in a 5D tensor.\n\n # Arguments\n x: Tensor or variable to resize.\n depth_factor: Positive integer.\n height_factor: Positive integer.\n width_factor: Positive integer.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n\n # Returns\n A tensor.\n\n # Raises\n ValueError: if `data_format` is\n neither `\"channels_last\"` or `\"channels_first\"`.\n \"\"\"\n if data_format == 'channels_first':\n output = repeat_elements(x, depth_factor, axis=2)\n output = repeat_elements(output, height_factor, axis=3)\n output = repeat_elements(output, width_factor, axis=4)\n return output\n elif data_format == 'channels_last':\n output = repeat_elements(x, depth_factor, axis=1)\n output = repeat_elements(output, height_factor, axis=2)\n output = repeat_elements(output, width_factor, axis=3)\n return output\n else:\n raise ValueError('Unknown data_format: ' + str(data_format))\n\n\ndef repeat_elements(x, rep, axis):\n \"\"\"Repeats the elements of a tensor along an axis, like `np.repeat`.\n\n If `x` has shape `(s1, s2, s3)` and `axis` is `1`, the output\n will have shape `(s1, s2 * rep, s3)`.\n\n # Arguments\n x: Tensor or variable.\n rep: Python integer, number of times to repeat.\n axis: Axis along which to repeat.\n\n # Returns\n A tensor.\n \"\"\"\n x_shape = x.get_shape().as_list()\n # For static axis\n if x_shape[axis] is not None:\n # slices along the repeat axis\n splits = tf.split(value=x, num_or_size_splits=x_shape[axis], axis=axis)\n # repeat each slice the given number of reps\n x_rep = [s for s in splits for _ in range(rep)]\n return concatenate(x_rep, axis)\n\n # Here we use tf.tile to mimic behavior of np.repeat so that\n # we can handle dynamic shapes (that include None).\n # To do that, we need an auxiliary axis to repeat elements along\n # it and then merge them along the desired axis.\n\n # Repeating\n auxiliary_axis = axis + 1\n x_shape = tf.shape(x)\n x_rep = tf.expand_dims(x, axis=auxiliary_axis)\n reps = np.ones(len(x.get_shape()) + 1)\n reps[auxiliary_axis] = rep\n x_rep = tf.tile(x_rep, reps)\n\n # Merging\n reps = np.delete(reps, auxiliary_axis)\n reps[axis] = rep\n reps = tf.constant(reps, dtype='int32')\n x_shape = x_shape * reps\n x_rep = tf.reshape(x_rep, x_shape)\n\n # Fix shape representation\n x_shape = x.get_shape().as_list()\n x_rep.set_shape(x_shape)\n x_rep._keras_shape = tuple(x_shape)\n return x_rep\n\n\ndef repeat(x, n):\n \"\"\"Repeats a 2D tensor.\n\n if `x` has shape (samples, dim) and `n` is `2`,\n the output will have shape `(samples, 2, dim)`.\n\n # Arguments\n x: Tensor or variable.\n n: Python integer, number of times to repeat.\n\n # Returns\n A tensor.\n \"\"\"\n assert ndim(x) == 2\n x = tf.expand_dims(x, 1)\n pattern = tf.stack([1, n, 1])\n return tf.tile(x, pattern)\n\n\ndef arange(start, stop=None, step=1, dtype='int32'):\n \"\"\"Creates a 1D tensor containing a sequence of integers.\n\n The function arguments use the same convention as\n Theano's arange: if only one argument is provided,\n it is in fact the \"stop\" argument and \"start\" is 0.\n\n The default type of the returned tensor is `'int32'` to\n match TensorFlow's default.\n\n # Arguments\n start: Start value.\n stop: Stop value.\n step: Difference between two successive values.\n dtype: Integer dtype to use.\n\n # Returns\n An integer tensor.\n\n \"\"\"\n # Match the behavior of numpy and Theano by returning an empty sequence.\n if stop is None:\n try:\n if start < 0:\n start = 0\n except TypeError:\n # Handle case where start is a tensor\n start = tf.cond(start < 0,\n true_fn=lambda: tf.constant(0, dtype=start.dtype),\n false_fn=lambda: start)\n\n result = tf.range(start, limit=stop, delta=step, name='arange')\n if dtype != 'int32':\n result = cast(result, dtype)\n return result\n\n\ndef tile(x, n):\n \"\"\"Creates a tensor by tiling `x` by `n`.\n\n # Arguments\n x: A tensor or variable\n n: A list of integer. The length must be the same as the number of\n dimensions in `x`.\n\n # Returns\n A tiled tensor.\n\n # Example\n ```python\n >>> from keras import backend as K\n >>> kvar = K.variable(np.random.random((2, 3)))\n >>> kvar_tile = K.tile(K.eye(2), (2, 3))\n >>> K.eval(kvar_tile)\n array([[1., 0., 1., 0., 1., 0.],\n [0., 1., 0., 1., 0., 1.],\n [1., 0., 1., 0., 1., 0.],\n [0., 1., 0., 1., 0., 1.]], dtype=float32)\n ```\n {{np_implementation}}\n \"\"\"\n if isinstance(n, int):\n n = (n,)\n elif isinstance(n, list):\n n = tuple(n)\n\n shape = int_shape(x)\n if len(n) < len(shape): # Padding the axis\n n = tuple([1 for _ in range(len(shape) - len(n))]) + n\n elif len(n) != len(shape):\n raise NotImplementedError\n\n return tf.tile(x, n)\n\n\ndef flatten(x):\n \"\"\"Flatten a tensor.\n\n # Arguments\n x: A tensor or variable.\n\n # Returns\n A tensor, reshaped into 1-D\n \"\"\"\n return tf.reshape(x, [-1])\n\n\ndef batch_flatten(x):\n \"\"\"Turn a nD tensor into a 2D tensor with same 0th dimension.\n\n In other words, it flattens each data samples of a batch.\n\n # Arguments\n x: A tensor or variable.\n\n # Returns\n A tensor.\n \"\"\"\n x = tf.reshape(x, tf.stack([-1, prod(shape(x)[1:])]))\n return x\n\n\ndef expand_dims(x, axis=-1):\n \"\"\"Adds a 1-sized dimension at index \"axis\".\n\n # Arguments\n x: A tensor or variable.\n axis: Position where to add a new axis.\n\n # Returns\n A tensor with expanded dimensions.\n \"\"\"\n return tf.expand_dims(x, axis)\n\n\ndef squeeze(x, axis):\n \"\"\"Removes a 1-dimension from the tensor at index \"axis\".\n\n # Arguments\n x: A tensor or variable.\n axis: Axis to drop.\n\n # Returns\n A tensor with the same data as `x` but reduced dimensions.\n \"\"\"\n return tf.squeeze(x, [axis])\n\n\ndef temporal_padding(x, padding=(1, 1)):\n \"\"\"Pads the middle dimension of a 3D tensor.\n\n # Arguments\n x: Tensor or variable.\n padding: Tuple of 2 integers, how many zeros to\n add at the start and end of dim 1.\n\n # Returns\n A padded 3D tensor.\n \"\"\"\n assert len(padding) == 2\n pattern = [[0, 0], [padding[0], padding[1]], [0, 0]]\n return tf.pad(x, pattern)\n\n\ndef spatial_2d_padding(x, padding=((1, 1), (1, 1)), data_format=None):\n \"\"\"Pads the 2nd and 3rd dimensions of a 4D tensor.\n\n # Arguments\n x: Tensor or variable.\n padding: Tuple of 2 tuples, padding pattern.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n\n # Returns\n A padded 4D tensor.\n\n # Raises\n ValueError: if `data_format` is\n neither `\"channels_last\"` or `\"channels_first\"`.\n \"\"\"\n assert len(padding) == 2\n assert len(padding[0]) == 2\n assert len(padding[1]) == 2\n data_format = normalize_data_format(data_format)\n\n pattern = [[0, 0],\n list(padding[0]),\n list(padding[1]),\n [0, 0]]\n pattern = transpose_shape(pattern, data_format, spatial_axes=(1, 2))\n return tf.pad(x, pattern)\n\n\ndef spatial_3d_padding(x, padding=((1, 1), (1, 1), (1, 1)), data_format=None):\n \"\"\"Pads 5D tensor with zeros along the depth, height, width dimensions.\n\n Pads these dimensions with respectively\n \"padding[0]\", \"padding[1]\" and \"padding[2]\" zeros left and right.\n\n For 'channels_last' data_format,\n the 2nd, 3rd and 4th dimension will be padded.\n For 'channels_first' data_format,\n the 3rd, 4th and 5th dimension will be padded.\n\n # Arguments\n x: Tensor or variable.\n padding: Tuple of 3 tuples, padding pattern.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n\n # Returns\n A padded 5D tensor.\n\n # Raises\n ValueError: if `data_format` is\n neither `\"channels_last\"` or `\"channels_first\"`.\n\n \"\"\"\n assert len(padding) == 3\n assert len(padding[0]) == 2\n assert len(padding[1]) == 2\n assert len(padding[2]) == 2\n data_format = normalize_data_format(data_format)\n\n pattern = [\n [0, 0],\n [padding[0][0], padding[0][1]],\n [padding[1][0], padding[1][1]],\n [padding[2][0], padding[2][1]],\n [0, 0]\n ]\n pattern = transpose_shape(pattern, data_format, spatial_axes=(1, 2, 3))\n\n return tf.pad(x, pattern)\n\n\ndef stack(x, axis=0):\n \"\"\"Stacks a list of rank `R` tensors into a rank `R+1` tensor.\n\n # Arguments\n x: List of tensors.\n axis: Axis along which to perform stacking.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.stack(x, axis=axis)\n\n\ndef one_hot(indices, num_classes):\n \"\"\"Computes the one-hot representation of an integer tensor.\n\n # Arguments\n indices: nD integer tensor of shape\n `(batch_size, dim1, dim2, ... dim(n-1))`\n num_classes: Integer, number of classes to consider.\n\n # Returns\n (n + 1)D one hot representation of the input\n with shape `(batch_size, dim1, dim2, ... dim(n-1), num_classes)`\n \"\"\"\n return tf.one_hot(indices, depth=num_classes, axis=-1)\n\n\ndef reverse(x, axes):\n \"\"\"Reverses a tensor along the specified axes.\n\n # Arguments\n x: Tensor to reverse.\n axes: Integer or iterable of integers.\n Axes to reverse.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n if isinstance(axes, int):\n axes = [axes]\n return tf.reverse(x, axes)\n\n\ndef slice(x, start, size):\n \"\"\"Extracts a slice from a tensor.\n\n # Arguments\n x: Input tensor.\n start: Integer list/tuple or tensor\n indicating the start indices of the slice\n along each axis.\n size: Integer list/tuple or tensor\n indicating how many dimensions to slice\n along each axis.\n\n # Returns\n A sliced tensor:\n ```python\n new_x = x[start[0]: start[0] + size[0], ..., start[-1]: start[-1] + size[-1]]\n ```\n\n # Raises\n ValueError: if the dimension and the size of indices mismatches.\n\n {{np_implementation}}\n \"\"\"\n x_shape = int_shape(x)\n if (x_shape is not None) and (x_shape[0] is not None):\n len_start = int_shape(start)[0] if is_tensor(start) else len(start)\n len_size = int_shape(size)[0] if is_tensor(size) else len(size)\n if not (len(int_shape(x)) == len_start == len_size):\n raise ValueError('The dimension and the size of indices should match.')\n return tf.slice(x, start, size)\n\n\n# VALUE MANIPULATION\n\n\ndef get_value(x):\n \"\"\"Returns the value of a variable.\n\n # Arguments\n x: input variable.\n\n # Returns\n A Numpy array.\n \"\"\"\n return x.eval(session=get_session())\n\n\ndef batch_get_value(ops):\n \"\"\"Returns the value of more than one tensor variable.\n\n # Arguments\n ops: list of ops to run.\n\n # Returns\n A list of Numpy arrays.\n \"\"\"\n if ops:\n return get_session().run(ops)\n else:\n return []\n\n\ndef set_value(x, value):\n \"\"\"Sets the value of a variable, from a Numpy array.\n\n # Arguments\n x: Tensor to set to a new value.\n value: Value to set the tensor to, as a Numpy array\n (of the same shape).\n \"\"\"\n value = np.asarray(value, dtype=dtype(x))\n tf_dtype = tf.as_dtype(x.dtype.name.split('_')[0])\n if hasattr(x, '_assign_placeholder'):\n assign_placeholder = x._assign_placeholder\n assign_op = x._assign_op\n else:\n assign_placeholder = tf.placeholder(tf_dtype, shape=value.shape)\n assign_op = x.assign(assign_placeholder)\n x._assign_placeholder = assign_placeholder\n x._assign_op = assign_op\n get_session().run(assign_op, feed_dict={assign_placeholder: value})\n\n\ndef batch_set_value(tuples):\n \"\"\"Sets the values of many tensor variables at once.\n\n # Arguments\n tuples: a list of tuples `(tensor, value)`.\n `value` should be a Numpy array.\n \"\"\"\n if tuples:\n assign_ops = []\n feed_dict = {}\n for x, value in tuples:\n value = np.asarray(value, dtype=dtype(x))\n tf_dtype = tf.as_dtype(x.dtype.name.split('_')[0])\n if hasattr(x, '_assign_placeholder'):\n assign_placeholder = x._assign_placeholder\n assign_op = x._assign_op\n else:\n assign_placeholder = tf.placeholder(tf_dtype,\n shape=value.shape)\n assign_op = x.assign(assign_placeholder)\n x._assign_placeholder = assign_placeholder\n x._assign_op = assign_op\n assign_ops.append(assign_op)\n feed_dict[assign_placeholder] = value\n get_session().run(assign_ops, feed_dict=feed_dict)\n\n\ndef get_variable_shape(x):\n \"\"\"Returns the shape of a variable.\n\n # Arguments\n x: A variable.\n\n # Returns\n A tuple of integers.\n \"\"\"\n return int_shape(x)\n\n\ndef print_tensor(x, message=''):\n \"\"\"Prints `message` and the tensor value when evaluated.\n\n Note that `print_tensor` returns a new tensor identical to `x`\n which should be used in the following code. Otherwise the\n print operation is not taken into account during evaluation.\n\n # Example\n ```python\n >>> x = K.print_tensor(x, message=\"x is: \")\n ```\n\n # Arguments\n x: Tensor to print.\n message: Message to print jointly with the tensor.\n\n # Returns\n The same tensor `x`, unchanged.\n \"\"\"\n return tf.Print(x, [x], message)\n\n\n# GRAPH MANIPULATION\n\nclass Function(object):\n \"\"\"Runs a computation graph.\n\n It's possible to pass arguments to `tf.Session.run()` via `session_kwargs`.\n In particular additional operations via `fetches` argument and additional\n tensor substitutions via `feed_dict` arguments. Note that given\n substitutions are merged with substitutions from `inputs`. Even though\n `feed_dict` is passed once in the constructor (called in `model.compile()`)\n we can modify the values in the dictionary. Through this feed_dict we can\n provide additional substitutions besides Keras inputs.\n\n # Arguments\n inputs: Feed placeholders to the computation graph.\n outputs: Output tensors to fetch.\n updates: Additional update ops to be run at function call.\n name: a name to help users identify what this function does.\n session_kwargs: arguments to `tf.Session.run()`:\n `fetches`, `feed_dict`,\n `options`, `run_metadata`\n \"\"\"\n\n def __init__(self, inputs, outputs,\n updates=None,\n name=None,\n **session_kwargs):\n updates = updates or []\n if not isinstance(inputs, (list, tuple)):\n raise TypeError('`inputs` to a TensorFlow backend function '\n 'should be a list or tuple.')\n if not isinstance(outputs, (list, tuple)):\n raise TypeError('`outputs` of a TensorFlow backend function '\n 'should be a list or tuple.')\n if not isinstance(updates, (list, tuple)):\n raise TypeError('`updates` in a TensorFlow backend function '\n 'should be a list or tuple.')\n self.inputs = list(inputs)\n self.outputs = list(outputs)\n with tf.control_dependencies(self.outputs):\n updates_ops = []\n for update in updates:\n if isinstance(update, tuple):\n p, new_p = update\n updates_ops.append(tf.assign(p, new_p))\n else:\n # assumed already an op\n updates_ops.append(update)\n self.updates_op = tf.group(*updates_ops)\n self.name = name\n # additional tensor substitutions\n self.feed_dict = session_kwargs.pop('feed_dict', {})\n # additional operations\n self.fetches = session_kwargs.pop('fetches', [])\n if not isinstance(self.fetches, list):\n self.fetches = [self.fetches]\n # The main use case of `fetches` being passed to a model is the ability\n # to run custom updates\n # (since the outputs of fetches are never returned).\n # This requires us to wrap fetches in `identity` ops.\n self.fetches = [tf.identity(x) for x in self.fetches]\n # self.session_kwargs is used for _legacy_call\n self.session_kwargs = session_kwargs.copy()\n self.run_options = session_kwargs.pop('options', None)\n self.run_metadata = session_kwargs.pop('run_metadata', None)\n if session_kwargs:\n raise ValueError('Some keys in session_kwargs are not '\n 'supported at this '\n 'time: %s', session_kwargs.keys())\n self._callable_fn = None\n self._feed_arrays = None\n self._feed_symbols = None\n self._symbol_vals = None\n self._session = None\n\n def _make_callable(self, feed_arrays, feed_symbols, symbol_vals, session):\n \"\"\"Generates a callable that runs the graph.\n\n # Arguments\n feed_arrays: List of input tensors to be fed\n Numpy arrays at runtime.\n feed_symbols: List of input tensors to be fed\n symbolic tensors at runtime.\n symbol_vals: List of symbolic tensors to be fed to `feed_symbols`.\n session: Session to use to generate the callable.\n\n # Returns\n Function that runs the graph according to the above options.\n \"\"\"\n # Prepare callable options.\n callable_opts = config_pb2.CallableOptions()\n # Handle external-data feed.\n for x in feed_arrays:\n callable_opts.feed.append(x.name)\n if self.feed_dict:\n for key in sorted(self.feed_dict.keys()):\n callable_opts.feed.append(key.name)\n # Handle symbolic feed.\n for x, y in zip(feed_symbols, symbol_vals):\n connection = callable_opts.tensor_connection.add()\n if x.dtype != y.dtype:\n y = tf.cast(y, dtype=x.dtype)\n from_tensor = tf_ops._as_graph_element(y)\n if from_tensor is None:\n from_tensor = y\n connection.from_tensor = from_tensor.name # Data tensor\n connection.to_tensor = x.name # Placeholder\n # Handle fetches.\n for x in self.outputs + self.fetches:\n callable_opts.fetch.append(x.name)\n # Handle updates.\n callable_opts.target.append(self.updates_op.name)\n # Handle run_options.\n if self.run_options:\n callable_opts.run_options.CopyFrom(self.run_options)\n # Create callable.\n callable_fn = session._make_callable_from_options(callable_opts)\n # Cache parameters corresponding to the generated callable, so that\n # we can detect future mismatches and refresh the callable.\n self._callable_fn = callable_fn\n self._feed_arrays = feed_arrays\n self._feed_symbols = feed_symbols\n self._symbol_vals = symbol_vals\n self._session = session\n\n def _call(self, inputs):\n if not isinstance(inputs, (list, tuple)):\n raise TypeError('`inputs` should be a list or tuple.')\n\n session = get_session()\n feed_arrays = []\n array_vals = []\n feed_symbols = []\n symbol_vals = []\n for tensor, value in zip(self.inputs, inputs):\n if value is None:\n continue\n if is_tensor(value):\n # Case: feeding symbolic tensor.\n feed_symbols.append(tensor)\n symbol_vals.append(value)\n else:\n feed_arrays.append(tensor)\n # We need to do array conversion and type casting\n # at this level, since\n # `callable_fn` only supports exact matches.\n array_vals.append(\n np.asarray(value,\n dtype=tf.as_dtype(tensor.dtype).as_numpy_dtype))\n if self.feed_dict:\n for key in sorted(self.feed_dict.keys()):\n array_vals.append(\n np.asarray(self.feed_dict[key],\n dtype=tf.as_dtype(key.dtype).as_numpy_dtype))\n\n # Refresh callable if anything has changed.\n if (self._callable_fn is None or\n feed_arrays != self._feed_arrays or\n symbol_vals != self._symbol_vals or\n feed_symbols != self._feed_symbols or\n session != self._session):\n self._make_callable(feed_arrays,\n feed_symbols,\n symbol_vals,\n session)\n if self.run_metadata:\n fetched = self._callable_fn(*array_vals, run_metadata=self.run_metadata)\n else:\n fetched = self._callable_fn(*array_vals)\n return fetched[:len(self.outputs)]\n\n def _legacy_call(self, inputs):\n if not isinstance(inputs, (list, tuple)):\n raise TypeError('`inputs` should be a list or tuple.')\n feed_dict = self.feed_dict.copy()\n for tensor, value in zip(self.inputs, inputs):\n if is_sparse(tensor):\n sparse_coo = value.tocoo()\n indices = np.concatenate(\n (np.expand_dims(sparse_coo.row, 1),\n np.expand_dims(sparse_coo.col, 1)), 1)\n value = (indices, sparse_coo.data, sparse_coo.shape)\n feed_dict[tensor] = value\n fetches = self.outputs + [self.updates_op] + self.fetches\n session = get_session()\n updated = session.run(fetches=fetches, feed_dict=feed_dict,\n **self.session_kwargs)\n return updated[:len(self.outputs)]\n\n def __call__(self, inputs):\n if hasattr(get_session(), '_make_callable_from_options'):\n if py_any(is_sparse(x) for x in self.inputs):\n if py_any(is_tensor(x) for x in inputs):\n raise ValueError(\n 'Feeding from symbolic tensors is not '\n 'supported with sparse inputs.')\n return self._legacy_call(inputs)\n\n # callable generated by Session._make_callable_from_options accepts\n # `run_metadata` keyword argument since TF 1.10\n if self.run_metadata:\n current_version = StrictVersion(tf.__version__.split('-')[0])\n if current_version < StrictVersion('1.10.0'):\n if py_any(is_tensor(x) for x in inputs):\n raise ValueError(\n 'In order to feed symbolic tensors '\n 'to a Keras model and set '\n '`run_metadata`, you need tensorflow 1.10 or higher.')\n return self._legacy_call(inputs)\n\n return self._call(inputs)\n else:\n if py_any(is_tensor(x) for x in inputs):\n raise ValueError(\n 'In order to feed symbolic tensors to a Keras model '\n 'in TensorFlow, you need tensorflow 1.8 or higher.')\n return self._legacy_call(inputs)\n\n\ndef function(inputs, outputs, updates=None, **kwargs):\n \"\"\"Instantiates a Keras function.\n\n # Arguments\n inputs: List of placeholder tensors.\n outputs: List of output tensors.\n updates: List of update ops.\n **kwargs: Passed to `tf.Session.run`.\n\n # Returns\n Output values as Numpy arrays.\n\n # Raises\n ValueError: if invalid kwargs are passed in.\n \"\"\"\n if kwargs:\n for key in kwargs:\n session_has_key = has_arg(tf.Session.run, key, True)\n function_has_key = has_arg(Function.__init__, key, True)\n if not (session_has_key or function_has_key):\n raise ValueError('Invalid argument \"%s\" passed to K.function '\n 'with TensorFlow backend' % key)\n return Function(inputs, outputs, updates=updates, **kwargs)\n\n\ndef gradients(loss, variables):\n \"\"\"Returns the gradients of `loss` w.r.t. `variables`.\n\n # Arguments\n loss: Scalar tensor to minimize.\n variables: List of variables.\n\n # Returns\n A gradients tensor.\n \"\"\"\n return tf.gradients(loss, variables, colocate_gradients_with_ops=True)\n\n\ndef stop_gradient(variables):\n \"\"\"Returns `variables` but with zero gradient w.r.t. every other variable.\n\n # Arguments\n variables: tensor or list of tensors to consider constant with respect\n to any other variable.\n\n # Returns\n A single tensor or a list of tensors (depending on the passed argument)\n that has constant gradient with respect to any other variable.\n \"\"\"\n if isinstance(variables, (list, tuple)):\n return map(tf.stop_gradient, variables)\n else:\n return tf.stop_gradient(variables)\n\n\n# CONTROL FLOW\n\ndef rnn(step_function, inputs, initial_states,\n go_backwards=False, mask=None, constants=None,\n unroll=False, input_length=None):\n \"\"\"Iterates over the time dimension of a tensor.\n\n # Arguments\n step_function:\n Parameters:\n inputs: Tensor with shape (samples, ...) (no time dimension),\n representing input for the batch of samples at a certain\n time step.\n states: List of tensors.\n Returns:\n outputs: Tensor with shape (samples, ...) (no time dimension),\n new_states: List of tensors, same length and shapes\n as 'states'.\n inputs: Tensor of temporal data of shape (samples, time, ...)\n (at least 3D).\n initial_states: Tensor with shape (samples, ...) (no time dimension),\n containing the initial values for the states used in\n the step function.\n go_backwards: Boolean. If True, do the iteration over the time\n dimension in reverse order and return the reversed sequence.\n mask: Binary tensor with shape (samples, time),\n with a zero for every element that is masked.\n constants: A list of constant values passed at each step.\n unroll: Whether to unroll the RNN or to use a symbolic loop\n (`while_loop` or `scan` depending on backend).\n input_length: Static number of timesteps in the input.\n\n # Returns\n A tuple, `(last_output, outputs, new_states)`.\n\n last_output: The latest output of the rnn, of shape `(samples, ...)`\n outputs: Tensor with shape `(samples, time, ...)` where each\n entry `outputs[s, t]` is the output of the step function\n at time `t` for sample `s`.\n new_states: List of tensors, latest states returned by\n the step function, of shape `(samples, ...)`.\n\n # Raises\n ValueError: If input dimension is less than 3.\n ValueError: If `unroll` is `True`\n but input timestep is not a fixed number.\n ValueError: If `mask` is provided (not `None`)\n but states is not provided (`len(states)` == 0).\n\n {{np_implementation}}\n \"\"\"\n ndim = len(inputs.shape)\n if ndim < 3:\n raise ValueError('Input should be at least 3D.')\n\n # Transpose to time-major, i.e.\n # from (batch, time, ...) to (time, batch, ...)\n axes = [1, 0] + list(range(2, ndim))\n inputs = tf.transpose(inputs, (axes))\n\n if mask is not None:\n if mask.dtype != tf.bool:\n mask = tf.cast(mask, tf.bool)\n if len(mask.shape) != 2:\n raise ValueError(\n 'mask should have `shape=(samples, time)`, '\n 'got {}'.format(mask.shape))\n mask = tf.transpose(mask, [1, 0])\n\n def get_matching_mask(mask_t, ref_tensor_t):\n # tf.where needs its condition tensor\n # to be the same shape as its two\n # result tensors\n ndim = len(ref_tensor_t.shape)\n for _ in range(ndim - 1):\n mask_t = expand_dims(mask_t)\n add_shape = tf.shape(ref_tensor_t)[1:]\n multiple = tf.concat([[1], add_shape], 0)\n return tf.tile(mask_t, multiple)\n\n if constants is None:\n constants = []\n\n uses_learning_phase = [False]\n\n if unroll:\n if not inputs.shape[0]:\n raise ValueError('Unrolling requires a '\n 'fixed number of timesteps.')\n states = initial_states\n successive_states = []\n successive_outputs = []\n\n input_list = tf.unstack(inputs)\n if go_backwards:\n input_list.reverse()\n\n if mask is not None:\n mask_list = tf.unstack(mask)\n if go_backwards:\n mask_list.reverse()\n\n for inp, mask_t in zip(input_list, mask_list):\n output, new_states = step_function(inp, states + constants)\n if getattr(output, '_uses_learning_phase', False):\n uses_learning_phase[0] = True\n\n if not successive_outputs:\n prev_output = zeros_like(output)\n else:\n prev_output = successive_outputs[-1]\n\n output_mask_t = get_matching_mask(mask_t, output)\n output = tf.where(output_mask_t, output, prev_output)\n\n return_states = []\n for state, new_state in zip(states, new_states):\n state_mask_t = get_matching_mask(mask_t, new_state)\n return_states.append(tf.where(state_mask_t,\n new_state,\n state))\n states = return_states\n successive_outputs.append(output)\n successive_states.append(states)\n last_output = successive_outputs[-1]\n new_states = successive_states[-1]\n outputs = tf.stack(successive_outputs)\n else:\n for inp in input_list:\n output, states = step_function(inp, states + constants)\n if getattr(output, '_uses_learning_phase', False):\n uses_learning_phase[0] = True\n successive_outputs.append(output)\n successive_states.append(states)\n last_output = successive_outputs[-1]\n new_states = successive_states[-1]\n outputs = tf.stack(successive_outputs)\n\n else:\n if go_backwards:\n inputs = reverse(inputs, 0)\n\n states = tuple(initial_states)\n\n time_steps = tf.shape(inputs)[0]\n output, _ = step_function(inputs[0], initial_states + constants)\n output_ta = tensor_array_ops.TensorArray(\n dtype=output.dtype,\n size=time_steps,\n tensor_array_name='output_ta')\n initial_output = zeros_like(output)\n input_ta = tensor_array_ops.TensorArray(\n dtype=inputs.dtype,\n size=time_steps,\n tensor_array_name='input_ta')\n input_ta = input_ta.unstack(inputs)\n time = tf.constant(0, dtype='int32', name='time')\n while_loop_kwargs = {\n 'cond': lambda time, *_: time < time_steps,\n 'parallel_iterations': 32,\n 'swap_memory': True,\n 'maximum_iterations': input_length}\n\n if mask is not None:\n if go_backwards:\n mask = reverse(mask, 0)\n\n mask_ta = tensor_array_ops.TensorArray(\n dtype=tf.bool,\n size=time_steps,\n tensor_array_name='mask_ta')\n mask_ta = mask_ta.unstack(mask)\n\n def _step(time, output_ta_t, output_tm1, *states):\n \"\"\"RNN step function.\n\n # Arguments\n time: Current timestep value.\n output_ta_t: TensorArray.\n output_tm1: output Tensor from previous timestep\n *states: List of states.\n\n # Returns\n Tuple: `(time + 1,output_ta_t) + tuple(new_states)`\n \"\"\"\n current_input = input_ta.read(time)\n mask_t = mask_ta.read(time)\n output, new_states = step_function(current_input,\n tuple(states) +\n tuple(constants))\n if getattr(output, '_uses_learning_phase', False):\n uses_learning_phase[0] = True\n for state, new_state in zip(states, new_states):\n new_state.set_shape(state.shape)\n\n output_mask_t = get_matching_mask(mask_t, output)\n output = tf.where(output_mask_t, output, output_tm1)\n\n new_states = [tf.where(get_matching_mask(mask_t, new_states[i]),\n new_states[i],\n states[i]) for i in range(len(states))]\n\n output_ta_t = output_ta_t.write(time, output)\n return (time + 1, output_ta_t, output) + tuple(new_states)\n\n final_outputs = control_flow_ops.while_loop(\n body=_step,\n loop_vars=(time, output_ta, initial_output) + states,\n **while_loop_kwargs)\n new_states = final_outputs[3:] # skip output_tm1\n else:\n def _step(time, output_ta_t, *states):\n \"\"\"RNN step function.\n\n # Arguments\n time: Current timestep value.\n output_ta_t: TensorArray.\n *states: List of states.\n\n # Returns\n Tuple: `(time + 1,output_ta_t) + tuple(new_states)`\n \"\"\"\n current_input = input_ta.read(time)\n output, new_states = step_function(current_input,\n tuple(states) +\n tuple(constants))\n if getattr(output, '_uses_learning_phase', False):\n uses_learning_phase[0] = True\n for state, new_state in zip(states, new_states):\n new_state.set_shape(state.shape)\n output_ta_t = output_ta_t.write(time, output)\n return (time + 1, output_ta_t) + tuple(new_states)\n\n final_outputs = control_flow_ops.while_loop(\n body=_step,\n loop_vars=(time, output_ta) + states,\n **while_loop_kwargs)\n new_states = final_outputs[2:]\n\n last_time = final_outputs[0]\n output_ta = final_outputs[1]\n outputs = output_ta.stack()\n last_output = output_ta.read(last_time - 1)\n\n axes = [1, 0] + list(range(2, len(outputs.shape)))\n outputs = tf.transpose(outputs, axes)\n last_output._uses_learning_phase = uses_learning_phase[0]\n return last_output, outputs, new_states\n\n\ndef switch(condition, then_expression, else_expression):\n \"\"\"Switches between two operations depending on a scalar value.\n\n Note that both `then_expression` and `else_expression`\n should be symbolic tensors of the *same shape*.\n\n # Arguments\n condition: tensor (`int` or `bool`).\n then_expression: either a tensor, or a callable that returns a tensor.\n else_expression: either a tensor, or a callable that returns a tensor.\n\n # Returns\n The selected tensor.\n\n # Raises\n ValueError: If rank of `condition` is greater than rank of expressions.\n\n {{np_implementation}}\n \"\"\"\n if condition.dtype != tf.bool:\n condition = tf.cast(condition, 'bool')\n cond_ndim = ndim(condition)\n if not cond_ndim:\n if not callable(then_expression):\n def then_expression_fn():\n return then_expression\n else:\n then_expression_fn = then_expression\n if not callable(else_expression):\n def else_expression_fn():\n return else_expression\n else:\n else_expression_fn = else_expression\n x = tf.cond(condition,\n then_expression_fn,\n else_expression_fn)\n else:\n # tf.where needs its condition tensor\n # to be the same shape as its two\n # result tensors\n if callable(then_expression):\n then_expression = then_expression()\n if callable(else_expression):\n else_expression = else_expression()\n expr_ndim = ndim(then_expression)\n if cond_ndim > expr_ndim:\n raise ValueError('Rank of `condition` should be less than or'\n ' equal to rank of `then_expression` and '\n '`else_expression`. ndim(condition)=' +\n str(cond_ndim) + ', ndim(then_expression)'\n '=' + str(expr_ndim))\n if cond_ndim > 1:\n ndim_diff = expr_ndim - cond_ndim\n cond_shape = tf.concat([tf.shape(condition), [1] * ndim_diff], axis=0)\n condition = tf.reshape(condition, cond_shape)\n expr_shape = tf.shape(then_expression)\n shape_diff = expr_shape - cond_shape\n zero_expr_shape = tf.ones_like(expr_shape)\n tile_shape = tf.where(shape_diff > 0, expr_shape, zero_expr_shape)\n condition = tf.tile(condition, tile_shape)\n x = tf.where(condition, then_expression, else_expression)\n return x\n\n\ndef in_train_phase(x, alt, training=None):\n \"\"\"Selects `x` in train phase, and `alt` otherwise.\n\n Note that `alt` should have the *same shape* as `x`.\n\n # Arguments\n x: What to return in train phase\n (tensor or callable that returns a tensor).\n alt: What to return otherwise\n (tensor or callable that returns a tensor).\n training: Optional scalar tensor\n (or Python boolean, or Python integer)\n specifying the learning phase.\n\n # Returns\n Either `x` or `alt` based on the `training` flag.\n the `training` flag defaults to `K.learning_phase()`.\n \"\"\"\n if training is None:\n training = learning_phase()\n uses_learning_phase = True\n else:\n uses_learning_phase = False\n\n if training is 1 or training is True:\n if callable(x):\n return x()\n else:\n return x\n\n elif training is 0 or training is False:\n if callable(alt):\n return alt()\n else:\n return alt\n\n # else: assume learning phase is a placeholder tensor.\n x = switch(training, x, alt)\n if uses_learning_phase:\n x._uses_learning_phase = True\n return x\n\n\ndef in_test_phase(x, alt, training=None):\n \"\"\"Selects `x` in test phase, and `alt` otherwise.\n\n Note that `alt` should have the *same shape* as `x`.\n\n # Arguments\n x: What to return in test phase\n (tensor or callable that returns a tensor).\n alt: What to return otherwise\n (tensor or callable that returns a tensor).\n training: Optional scalar tensor\n (or Python boolean, or Python integer)\n specifying the learning phase.\n\n # Returns\n Either `x` or `alt` based on `K.learning_phase`.\n \"\"\"\n return in_train_phase(alt, x, training=training)\n\n\n# NN OPERATIONS\n\ndef relu(x, alpha=0., max_value=None, threshold=0.):\n \"\"\"Rectified linear unit.\n\n With default values, it returns element-wise `max(x, 0)`.\n\n Otherwise, it follows:\n `f(x) = max_value` for `x >= max_value`,\n `f(x) = x` for `threshold <= x < max_value`,\n `f(x) = alpha * (x - threshold)` otherwise.\n\n # Arguments\n x: A tensor or variable.\n alpha: A scalar, slope of negative section (default=`0.`).\n max_value: float. Saturation threshold.\n threshold: float. Threshold value for thresholded activation.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n\n if alpha != 0.:\n if max_value is None and threshold == 0.:\n return tf.nn.leaky_relu(x, alpha=alpha)\n\n if threshold != 0.:\n negative_part = tf.nn.relu(-x + threshold)\n else:\n negative_part = tf.nn.relu(-x)\n\n clip_max = max_value is not None\n\n if threshold != 0:\n # computes x for x > threshold else 0\n x = x * tf.cast(tf.greater(x, threshold), floatx())\n elif max_value == 6:\n # if no threshold, then can use nn.relu6 native TF op for performance\n x = tf.nn.relu6(x)\n clip_max = False\n else:\n x = tf.nn.relu(x)\n\n if clip_max:\n max_value = _to_tensor(max_value, x.dtype.base_dtype)\n zero = _to_tensor(0., x.dtype.base_dtype)\n x = tf.clip_by_value(x, zero, max_value)\n\n if alpha != 0:\n alpha = _to_tensor(alpha, x.dtype.base_dtype)\n x -= alpha * negative_part\n return x\n\n\ndef elu(x, alpha=1.):\n \"\"\"Exponential linear unit.\n\n # Arguments\n x: A tensor or variable to compute the activation function for.\n alpha: A scalar, slope of negative section.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n res = tf.nn.elu(x)\n if alpha == 1:\n return res\n else:\n return tf.where(x > 0, res, alpha * res)\n\n\ndef softmax(x, axis=-1):\n \"\"\"Softmax of a tensor.\n\n # Arguments\n x: A tensor or variable.\n axis: The dimension softmax would be performed on.\n The default is -1 which indicates the last dimension.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.nn.softmax(x, axis=axis)\n\n\ndef softplus(x):\n \"\"\"Softplus of a tensor.\n\n # Arguments\n x: A tensor or variable.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.nn.softplus(x)\n\n\ndef softsign(x):\n \"\"\"Softsign of a tensor.\n\n # Arguments\n x: A tensor or variable.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.nn.softsign(x)\n\n\ndef categorical_crossentropy(target, output, from_logits=False, axis=-1):\n \"\"\"Categorical crossentropy between an output tensor and a target tensor.\n\n # Arguments\n target: A tensor of the same shape as `output`.\n output: A tensor resulting from a softmax\n (unless `from_logits` is True, in which\n case `output` is expected to be the logits).\n from_logits: Boolean, whether `output` is the\n result of a softmax, or is a tensor of logits.\n axis: Int specifying the channels axis. `axis=-1`\n corresponds to data format `channels_last`,\n and `axis=1` corresponds to data format\n `channels_first`.\n\n # Returns\n Output tensor.\n\n # Raises\n ValueError: if `axis` is neither -1 nor one of\n the axes of `output`.\n \"\"\"\n output_dimensions = list(range(len(output.get_shape())))\n if axis != -1 and axis not in output_dimensions:\n raise ValueError(\n '{}{}{}'.format(\n 'Unexpected channels axis {}. '.format(axis),\n 'Expected to be -1 or one of the axes of `output`, ',\n 'which has {} dimensions.'.format(len(output.get_shape()))))\n # Note: tf.nn.softmax_cross_entropy_with_logits\n # expects logits, Keras expects probabilities.\n if not from_logits:\n # scale preds so that the class probas of each sample sum to 1\n output /= tf.reduce_sum(output, axis, True)\n # manual computation of crossentropy\n _epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)\n output = tf.clip_by_value(output, _epsilon, 1. - _epsilon)\n return - tf.reduce_sum(target * tf.log(output), axis)\n else:\n return tf.nn.softmax_cross_entropy_with_logits(labels=target,\n logits=output)\n\n\ndef sparse_categorical_crossentropy(target, output, from_logits=False, axis=-1):\n \"\"\"Categorical crossentropy with integer targets.\n\n # Arguments\n target: An integer tensor.\n output: A tensor resulting from a softmax\n (unless `from_logits` is True, in which\n case `output` is expected to be the logits).\n from_logits: Boolean, whether `output` is the\n result of a softmax, or is a tensor of logits.\n axis: Int specifying the channels axis. `axis=-1`\n corresponds to data format `channels_last`,\n and `axis=1` corresponds to data format\n `channels_first`.\n\n # Returns\n Output tensor.\n\n # Raises\n ValueError: if `axis` is neither -1 nor one of\n the axes of `output`.\n \"\"\"\n output_dimensions = list(range(len(output.get_shape())))\n if axis != -1 and axis not in output_dimensions:\n raise ValueError(\n '{}{}{}'.format(\n 'Unexpected channels axis {}. '.format(axis),\n 'Expected to be -1 or one of the axes of `output`, ',\n 'which has {} dimensions.'.format(len(output.get_shape()))))\n # If the channels are not in the last axis, move them to be there:\n if axis != -1 and axis != output_dimensions[-1]:\n permutation = output_dimensions[:axis] + output_dimensions[axis + 1:]\n permutation += [axis]\n output = tf.transpose(output, perm=permutation)\n\n # Note: tf.nn.sparse_softmax_cross_entropy_with_logits\n # expects logits, Keras expects probabilities.\n if not from_logits:\n _epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)\n output = tf.clip_by_value(output, _epsilon, 1 - _epsilon)\n output = tf.log(output)\n\n output_shape = output.get_shape()\n targets = cast(flatten(target), 'int64')\n logits = tf.reshape(output, [-1, int(output_shape[-1])])\n res = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=targets,\n logits=logits)\n if len(output_shape) >= 3:\n # if our output includes timestep dimension\n # or spatial dimensions we need to reshape\n return tf.reshape(res, tf.shape(output)[:-1])\n else:\n return res\n\n\ndef binary_crossentropy(target, output, from_logits=False):\n \"\"\"Binary crossentropy between an output tensor and a target tensor.\n\n # Arguments\n target: A tensor with the same shape as `output`.\n output: A tensor.\n from_logits: Whether `output` is expected to be a logits tensor.\n By default, we consider that `output`\n encodes a probability distribution.\n\n # Returns\n A tensor.\n \"\"\"\n # Note: tf.nn.sigmoid_cross_entropy_with_logits\n # expects logits, Keras expects probabilities.\n if not from_logits:\n # transform back to logits\n _epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)\n output = tf.clip_by_value(output, _epsilon, 1 - _epsilon)\n output = tf.log(output / (1 - output))\n\n return tf.nn.sigmoid_cross_entropy_with_logits(labels=target,\n logits=output)\n\n\ndef sigmoid(x):\n \"\"\"Element-wise sigmoid.\n\n # Arguments\n x: A tensor or variable.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.nn.sigmoid(x)\n\n\ndef hard_sigmoid(x):\n \"\"\"Segment-wise linear approximation of sigmoid.\n\n Faster than sigmoid.\n Returns `0.` if `x < -2.5`, `1.` if `x > 2.5`.\n In `-2.5 <= x <= 2.5`, returns `0.2 * x + 0.5`.\n\n # Arguments\n x: A tensor or variable.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n x = (0.2 * x) + 0.5\n zero = _to_tensor(0., x.dtype.base_dtype)\n one = _to_tensor(1., x.dtype.base_dtype)\n x = tf.clip_by_value(x, zero, one)\n return x\n\n\ndef tanh(x):\n \"\"\"Element-wise tanh.\n\n # Arguments\n x: A tensor or variable.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.nn.tanh(x)\n\n\ndef dropout(x, level, noise_shape=None, seed=None):\n \"\"\"Sets entries in `x` to zero at random, while scaling the entire tensor.\n\n # Arguments\n x: tensor\n level: fraction of the entries in the tensor\n that will be set to 0.\n noise_shape: shape for randomly generated keep/drop flags,\n must be broadcastable to the shape of `x`\n seed: random seed to ensure determinism.\n\n # Returns\n A tensor.\n {{np_implementation}}\n \"\"\"\n retain_prob = 1. - level\n if seed is None:\n seed = np.random.randint(10e6)\n # the dummy 1. works around a TF bug\n # (float32_ref vs. float32 incompatibility)\n return tf.nn.dropout(x * 1., retain_prob, noise_shape, seed=seed)\n\n\ndef l2_normalize(x, axis=None):\n \"\"\"Normalizes a tensor wrt the L2 norm alongside the specified axis.\n\n # Arguments\n x: Tensor or variable.\n axis: axis along which to perform normalization.\n\n # Returns\n A tensor.\n\n {{np_implementation}}\n \"\"\"\n return tf.nn.l2_normalize(x, axis=axis)\n\n\ndef in_top_k(predictions, targets, k):\n \"\"\"Returns whether the `targets` are in the top `k` `predictions`.\n\n # Arguments\n predictions: A tensor of shape `(batch_size, classes)` and type `float32`.\n targets: A 1D tensor of length `batch_size` and type `int32` or `int64`.\n k: An `int`, number of top elements to consider.\n\n # Returns\n A 1D tensor of length `batch_size` and type `bool`.\n `output[i]` is `True` if `predictions[i, targets[i]]` is within top-`k`\n values of `predictions[i]`.\n \"\"\"\n return tf.nn.in_top_k(predictions, targets, k)\n\n\n# CONVOLUTIONS\n\n\ndef _preprocess_conv1d_input(x, data_format):\n \"\"\"Transpose and cast the input before the conv1d.\n\n # Arguments\n x: input tensor.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n\n # Returns\n A tensor.\n \"\"\"\n # tensorflow doesn't support float64 for conv layer before 1.8.0\n if (dtype(x) == 'float64' and\n StrictVersion(tf.__version__.split('-')[0]) < StrictVersion('1.8.0')):\n x = tf.cast(x, 'float32')\n tf_data_format = 'NWC' # to pass TF Conv2dNative operations\n if data_format == 'channels_first':\n if not _has_nchw_support():\n x = tf.transpose(x, (0, 2, 1)) # NCW -> NWC\n else:\n tf_data_format = 'NCW'\n return x, tf_data_format\n\n\ndef _preprocess_conv2d_input(x, data_format, force_transpose=False):\n \"\"\"Transpose and cast the input before the conv2d.\n\n # Arguments\n x: input tensor.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n force_transpose: boolean, whether force to transpose input from NCHW to NHWC\n if the `data_format` is `\"channels_first\"`.\n\n # Returns\n A tensor.\n \"\"\"\n # tensorflow doesn't support float64 for conv layer before 1.8.0\n if (dtype(x) == 'float64' and\n StrictVersion(tf.__version__.split('-')[0]) < StrictVersion('1.8.0')):\n x = tf.cast(x, 'float32')\n tf_data_format = 'NHWC'\n if data_format == 'channels_first':\n if not _has_nchw_support() or force_transpose:\n x = tf.transpose(x, (0, 2, 3, 1)) # NCHW -> NHWC\n else:\n tf_data_format = 'NCHW'\n return x, tf_data_format\n\n\ndef _preprocess_conv3d_input(x, data_format):\n \"\"\"Transpose and cast the input before the conv3d.\n\n # Arguments\n x: input tensor.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n\n # Returns\n A tensor.\n \"\"\"\n # tensorflow doesn't support float64 for conv layer before 1.8.0\n if (dtype(x) == 'float64' and\n StrictVersion(tf.__version__.split('-')[0]) < StrictVersion('1.8.0')):\n x = tf.cast(x, 'float32')\n tf_data_format = 'NDHWC'\n if data_format == 'channels_first':\n if not _has_nchw_support():\n x = tf.transpose(x, (0, 2, 3, 4, 1))\n else:\n tf_data_format = 'NCDHW'\n return x, tf_data_format\n\n\ndef _preprocess_padding(padding):\n \"\"\"Convert keras' padding to tensorflow's padding.\n\n # Arguments\n padding: string, `\"same\"` or `\"valid\"`.\n\n # Returns\n a string, `\"SAME\"` or `\"VALID\"`.\n\n # Raises\n ValueError: if `padding` is invalid.\n \"\"\"\n if padding == 'same':\n padding = 'SAME'\n elif padding == 'valid':\n padding = 'VALID'\n else:\n raise ValueError('Invalid padding: ' + str(padding))\n return padding\n\n\ndef conv1d(x, kernel, strides=1, padding='valid',\n data_format=None, dilation_rate=1):\n \"\"\"1D convolution.\n\n # Arguments\n x: Tensor or variable.\n kernel: kernel tensor.\n strides: stride integer.\n padding: string, `\"same\"`, `\"causal\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n dilation_rate: integer dilate rate.\n\n # Returns\n A tensor, result of 1D convolution.\n\n # Raises\n ValueError: If `data_format` is neither\n `\"channels_last\"` nor `\"channels_first\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n\n kernel_shape = kernel.get_shape().as_list()\n if padding == 'causal':\n if data_format != 'channels_last':\n raise ValueError('When using causal padding in `conv1d`, '\n '`data_format` must be \"channels_last\" '\n '(temporal data).')\n # causal (dilated) convolution:\n left_pad = dilation_rate * (kernel_shape[0] - 1)\n x = temporal_padding(x, (left_pad, 0))\n padding = 'valid'\n padding = _preprocess_padding(padding)\n x, tf_data_format = _preprocess_conv1d_input(x, data_format)\n x = tf.nn.convolution(\n input=x,\n filter=kernel,\n dilation_rate=(dilation_rate,),\n strides=(strides,),\n padding=padding,\n data_format=tf_data_format)\n\n if data_format == 'channels_first' and tf_data_format == 'NWC':\n x = tf.transpose(x, (0, 2, 1)) # NWC -> NCW\n return x\n\n\ndef conv2d(x, kernel, strides=(1, 1), padding='valid',\n data_format=None, dilation_rate=(1, 1)):\n \"\"\"2D convolution.\n\n # Arguments\n x: Tensor or variable.\n kernel: kernel tensor.\n strides: strides tuple.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n Whether to use Theano or TensorFlow/CNTK data format\n for inputs/kernels/outputs.\n dilation_rate: tuple of 2 integers.\n\n # Returns\n A tensor, result of 2D convolution.\n\n # Raises\n ValueError: If `data_format` is neither\n `\"channels_last\"` nor `\"channels_first\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n\n padding = _preprocess_padding(padding)\n x = tf.nn.convolution(\n input=x,\n filter=kernel,\n dilation_rate=dilation_rate,\n strides=strides,\n padding=padding,\n data_format=tf_data_format)\n\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = tf.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW\n return x\n\n\ndef conv2d_transpose(x, kernel, output_shape, strides=(1, 1),\n padding='valid', data_format=None, dilation_rate=(1, 1)):\n \"\"\"2D deconvolution (i.e. transposed convolution).\n\n # Arguments\n x: Tensor or variable.\n kernel: kernel tensor.\n output_shape: 1D int tensor for the output shape.\n strides: strides tuple.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n Whether to use Theano or TensorFlow/CNTK data format\n for inputs/kernels/outputs.\n dilation_rate: tuple of 2 integers.\n\n # Returns\n A tensor, result of transposed 2D convolution.\n\n # Raises\n ValueError: If `data_format` is neither\n `\"channels_last\"` nor `\"channels_first\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n if isinstance(output_shape, (tuple, list)):\n output_shape = tf.stack(output_shape)\n\n # tf.nn.atrous_conv2d_transpose input only supports NHWC format\n if data_format == 'channels_first' and dilation_rate != (1, 1):\n force_transpose = True\n else:\n force_transpose = False\n\n x, tf_data_format = _preprocess_conv2d_input(x, data_format, force_transpose)\n\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n output_shape = (output_shape[0],\n output_shape[2],\n output_shape[3],\n output_shape[1])\n if output_shape[0] is None:\n output_shape = (tf.shape(x)[0],) + tuple(output_shape[1:])\n output_shape = tf.stack(list(output_shape))\n\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NHWC':\n strides = (1,) + strides + (1,)\n else:\n strides = (1, 1) + strides\n\n if dilation_rate == (1, 1):\n x = tf.nn.conv2d_transpose(x, kernel, output_shape, strides,\n padding=padding,\n data_format=tf_data_format)\n else:\n assert dilation_rate[0] == dilation_rate[1]\n x = tf.nn.atrous_conv2d_transpose(\n x, kernel, output_shape, dilation_rate[0], padding)\n\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = tf.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW\n return x\n\n\ndef separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1,\n padding='valid', data_format=None, dilation_rate=1):\n \"\"\"1D convolution with separable filters.\n\n # Arguments\n x: input tensor\n depthwise_kernel: convolution kernel for the depthwise convolution.\n pointwise_kernel: kernel for the 1x1 convolution.\n strides: stride integer.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n dilation_rate: integer dilation rate.\n\n # Returns\n Output tensor.\n\n # Raises\n ValueError: If `data_format` is neither\n `\"channels_last\"` nor `\"channels_first\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n if isinstance(strides, int):\n strides = (strides,)\n if isinstance(dilation_rate, int):\n dilation_rate = (dilation_rate,)\n\n x, tf_data_format = _preprocess_conv1d_input(x, data_format)\n if tf_data_format == 'NWC':\n tf_data_format = 'NHWC'\n else:\n tf_data_format = 'NCHW'\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NHWC':\n spatial_start_dim = 1\n strides = (1,) + strides * 2 + (1,)\n else:\n spatial_start_dim = 2\n strides = (1, 1) + strides * 2\n x = tf.expand_dims(x, spatial_start_dim)\n depthwise_kernel = tf.expand_dims(depthwise_kernel, 0)\n pointwise_kernel = tf.expand_dims(pointwise_kernel, 0)\n dilation_rate = (1,) + dilation_rate\n\n x = tf.nn.separable_conv2d(x, depthwise_kernel, pointwise_kernel,\n strides=strides,\n padding=padding,\n rate=dilation_rate,\n data_format=tf_data_format)\n\n x = tf.squeeze(x, [spatial_start_dim])\n\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = tf.transpose(x, (0, 2, 1)) # NWC -> NCW\n\n return x\n\n\ndef separable_conv2d(x, depthwise_kernel, pointwise_kernel, strides=(1, 1),\n padding='valid', data_format=None, dilation_rate=(1, 1)):\n \"\"\"2D convolution with separable filters.\n\n # Arguments\n x: input tensor\n depthwise_kernel: convolution kernel for the depthwise convolution.\n pointwise_kernel: kernel for the 1x1 convolution.\n strides: strides tuple (length 2).\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n dilation_rate: tuple of integers,\n dilation rates for the separable convolution.\n\n # Returns\n Output tensor.\n\n # Raises\n ValueError: If `data_format` is neither\n `\"channels_last\"` nor `\"channels_first\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NHWC':\n strides = (1,) + strides + (1,)\n else:\n strides = (1, 1) + strides\n\n x = tf.nn.separable_conv2d(x, depthwise_kernel, pointwise_kernel,\n strides=strides,\n padding=padding,\n rate=dilation_rate,\n data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = tf.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW\n return x\n\n\ndef depthwise_conv2d(x, depthwise_kernel, strides=(1, 1), padding='valid',\n data_format=None, dilation_rate=(1, 1)):\n \"\"\"2D convolution with separable filters.\n\n # Arguments\n x: input tensor\n depthwise_kernel: convolution kernel for the depthwise convolution.\n strides: strides tuple (length 2).\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n dilation_rate: tuple of integers,\n dilation rates for the separable convolution.\n\n # Returns\n Output tensor.\n\n # Raises\n ValueError: If `data_format` is neither\n `\"channels_last\"` nor `\"channels_first\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NHWC':\n strides = (1,) + strides + (1,)\n else:\n strides = (1, 1) + strides\n\n x = tf.nn.depthwise_conv2d(x, depthwise_kernel,\n strides=strides,\n padding=padding,\n rate=dilation_rate,\n data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = tf.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW\n return x\n\n\ndef conv3d(x, kernel, strides=(1, 1, 1), padding='valid',\n data_format=None, dilation_rate=(1, 1, 1)):\n \"\"\"3D convolution.\n\n # Arguments\n x: Tensor or variable.\n kernel: kernel tensor.\n strides: strides tuple.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n Whether to use Theano or TensorFlow/CNTK data format\n for inputs/kernels/outputs.\n dilation_rate: tuple of 3 integers.\n\n # Returns\n A tensor, result of 3D convolution.\n\n # Raises\n ValueError: If `data_format` is neither\n `\"channels_last\"` nor `\"channels_first\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n\n x, tf_data_format = _preprocess_conv3d_input(x, data_format)\n padding = _preprocess_padding(padding)\n x = tf.nn.convolution(\n input=x,\n filter=kernel,\n dilation_rate=dilation_rate,\n strides=strides,\n padding=padding,\n data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NDHWC':\n x = tf.transpose(x, (0, 4, 1, 2, 3))\n return x\n\n\ndef conv3d_transpose(x, kernel, output_shape, strides=(1, 1, 1),\n padding='valid', data_format=None):\n \"\"\"3D deconvolution (i.e. transposed convolution).\n\n # Arguments\n x: input tensor.\n kernel: kernel tensor.\n output_shape: 1D int tensor for the output shape.\n strides: strides tuple.\n padding: string, \"same\" or \"valid\".\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n Whether to use Theano or TensorFlow/CNTK data format\n for inputs/kernels/outputs.\n\n # Returns\n A tensor, result of transposed 3D convolution.\n\n # Raises\n ValueError: If `data_format` is neither\n `\"channels_last\"` nor `\"channels_first\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n if isinstance(output_shape, (tuple, list)):\n output_shape = tf.stack(output_shape)\n\n x, tf_data_format = _preprocess_conv3d_input(x, data_format)\n\n if data_format == 'channels_first' and tf_data_format == 'NDHWC':\n output_shape = (output_shape[0],\n output_shape[2],\n output_shape[3],\n output_shape[4],\n output_shape[1])\n if output_shape[0] is None:\n output_shape = (tf.shape(x)[0],) + tuple(output_shape[1:])\n output_shape = tf.stack(list(output_shape))\n\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NDHWC':\n strides = (1,) + strides + (1,)\n else:\n strides = (1, 1) + strides\n\n x = tf.nn.conv3d_transpose(x, kernel, output_shape, strides,\n padding=padding,\n data_format=tf_data_format)\n if data_format == 'channels_first' and tf_data_format == 'NDHWC':\n x = tf.transpose(x, (0, 4, 1, 2, 3))\n return x\n\n\ndef pool2d(x, pool_size, strides=(1, 1),\n padding='valid', data_format=None,\n pool_mode='max'):\n \"\"\"2D Pooling.\n\n # Arguments\n x: Tensor or variable.\n pool_size: tuple of 2 integers.\n strides: tuple of 2 integers.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n pool_mode: string, `\"max\"` or `\"avg\"`.\n\n # Returns\n A tensor, result of 2D pooling.\n\n # Raises\n ValueError: if `data_format` is\n neither `\"channels_last\"` or `\"channels_first\"`.\n ValueError: if `pool_mode` is neither `\"max\"` or `\"avg\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n\n x, tf_data_format = _preprocess_conv2d_input(x, data_format)\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NHWC':\n strides = (1,) + strides + (1,)\n pool_size = (1,) + pool_size + (1,)\n else:\n strides = (1, 1) + strides\n pool_size = (1, 1) + pool_size\n\n if pool_mode == 'max':\n x = tf.nn.max_pool(x, pool_size, strides,\n padding=padding,\n data_format=tf_data_format)\n elif pool_mode == 'avg':\n x = tf.nn.avg_pool(x, pool_size, strides,\n padding=padding,\n data_format=tf_data_format)\n else:\n raise ValueError('Invalid pool_mode: ' + str(pool_mode))\n\n if data_format == 'channels_first' and tf_data_format == 'NHWC':\n x = tf.transpose(x, (0, 3, 1, 2)) # NHWC -> NCHW\n return x\n\n\ndef pool3d(x, pool_size, strides=(1, 1, 1), padding='valid',\n data_format=None, pool_mode='max'):\n \"\"\"3D Pooling.\n\n # Arguments\n x: Tensor or variable.\n pool_size: tuple of 3 integers.\n strides: tuple of 3 integers.\n padding: string, `\"same\"` or `\"valid\"`.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n pool_mode: string, `\"max\"` or `\"avg\"`.\n\n # Returns\n A tensor, result of 3D pooling.\n\n # Raises\n ValueError: if `data_format` is\n neither `\"channels_last\"` or `\"channels_first\"`.\n ValueError: if `pool_mode` is neither `\"max\"` or `\"avg\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n\n x, tf_data_format = _preprocess_conv3d_input(x, data_format)\n padding = _preprocess_padding(padding)\n if tf_data_format == 'NDHWC':\n strides = (1,) + strides + (1,)\n pool_size = (1,) + pool_size + (1,)\n else:\n strides = (1, 1) + strides\n pool_size = (1, 1) + pool_size\n\n if pool_mode == 'max':\n x = tf.nn.max_pool3d(x, pool_size, strides,\n padding=padding,\n data_format=tf_data_format)\n elif pool_mode == 'avg':\n x = tf.nn.avg_pool3d(x, pool_size, strides,\n padding=padding,\n data_format=tf_data_format)\n else:\n raise ValueError('Invalid pool_mode: ' + str(pool_mode))\n\n if data_format == 'channels_first' and tf_data_format == 'NDHWC':\n x = tf.transpose(x, (0, 4, 1, 2, 3))\n return x\n\n\ndef bias_add(x, bias, data_format=None):\n \"\"\"Adds a bias vector to a tensor.\n\n # Arguments\n x: Tensor or variable.\n bias: Bias tensor to add.\n data_format: string, `\"channels_last\"` or `\"channels_first\"`.\n\n # Returns\n Output tensor.\n\n # Raises\n ValueError: In one of the two cases below:\n 1. invalid `data_format` argument.\n 2. invalid bias shape.\n the bias should be either a vector or\n a tensor with ndim(x) - 1 dimension\n {{np_implementation}}\n \"\"\"\n data_format = normalize_data_format(data_format)\n bias_shape = int_shape(bias)\n if len(bias_shape) != 1 and len(bias_shape) != ndim(x) - 1:\n raise ValueError('Unexpected bias dimensions %d, '\n 'expect to be 1 or %d dimensions'\n % (len(bias_shape), ndim(x)))\n if ndim(x) == 5:\n if len(bias_shape) == 1:\n new_shape = (1, 1, 1, 1, bias_shape[0])\n else:\n new_shape = (1,) + bias_shape\n new_shape = transpose_shape(new_shape, data_format, spatial_axes=(1, 2, 3))\n x += reshape(bias, new_shape)\n elif ndim(x) == 4:\n if data_format == 'channels_first':\n if len(bias_shape) == 1:\n if _has_nchw_support():\n x = tf.nn.bias_add(x, bias,\n data_format='NCHW')\n else:\n x += reshape(bias, (1, bias_shape[0], 1, 1))\n else:\n x += reshape(bias, (1, bias_shape[2]) + bias_shape[:2])\n elif data_format == 'channels_last':\n if len(bias_shape) == 1:\n x = tf.nn.bias_add(x, bias,\n data_format='NHWC')\n else:\n x += reshape(bias, (1,) + bias_shape)\n elif ndim(x) == 3:\n if len(bias_shape) == 1:\n new_shape = (1, 1, bias_shape[0])\n else:\n new_shape = (1,) + bias_shape\n new_shape = transpose_shape(new_shape, data_format, spatial_axes=(1,))\n x += reshape(bias, new_shape)\n else:\n x = tf.nn.bias_add(x, bias)\n return x\n\n\n# RANDOMNESS\n\ndef random_normal(shape, mean=0.0, stddev=1.0, dtype=None, seed=None):\n \"\"\"Returns a tensor with normal distribution of values.\n\n # Arguments\n shape: A tuple of integers, the shape of tensor to create.\n mean: A float, mean of the normal distribution to draw samples.\n stddev: A float, standard deviation of the normal distribution\n to draw samples.\n dtype: String, dtype of returned tensor.\n seed: Integer, random seed.\n\n # Returns\n A tensor.\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if seed is None:\n seed = np.random.randint(10e6)\n return tf.random_normal(shape, mean=mean, stddev=stddev,\n dtype=dtype, seed=seed)\n\n\ndef random_uniform(shape, minval=0.0, maxval=1.0, dtype=None, seed=None):\n \"\"\"Returns a tensor with uniform distribution of values.\n\n # Arguments\n shape: A tuple of integers, the shape of tensor to create.\n minval: A float, lower boundary of the uniform distribution\n to draw samples.\n maxval: A float, upper boundary of the uniform distribution\n to draw samples.\n dtype: String, dtype of returned tensor.\n seed: Integer, random seed.\n\n # Returns\n A tensor.\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if seed is None:\n seed = np.random.randint(10e6)\n return tf.random_uniform(shape, minval=minval, maxval=maxval,\n dtype=dtype, seed=seed)\n\n\ndef random_binomial(shape, p=0.0, dtype=None, seed=None):\n \"\"\"Returns a tensor with random binomial distribution of values.\n\n # Arguments\n shape: A tuple of integers, the shape of tensor to create.\n p: A float, `0. <= p <= 1`, probability of binomial distribution.\n dtype: String, dtype of returned tensor.\n seed: Integer, random seed.\n\n # Returns\n A tensor.\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if seed is None:\n seed = np.random.randint(10e6)\n return tf.where(tf.random_uniform(shape, dtype=dtype, seed=seed) <= p,\n tf.ones(shape, dtype=dtype),\n tf.zeros(shape, dtype=dtype))\n\n\ndef truncated_normal(shape, mean=0.0, stddev=1.0, dtype=None, seed=None):\n \"\"\"Returns a tensor with truncated random normal distribution of values.\n\n The generated values follow a normal distribution\n with specified mean and standard deviation,\n except that values whose magnitude is more than\n two standard deviations from the mean are dropped and re-picked.\n\n # Arguments\n shape: A tuple of integers, the shape of tensor to create.\n mean: Mean of the values.\n stddev: Standard deviation of the values.\n dtype: String, dtype of returned tensor.\n seed: Integer, random seed.\n\n # Returns\n A tensor.\n \"\"\"\n if dtype is None:\n dtype = floatx()\n if seed is None:\n seed = np.random.randint(10e6)\n return tf.truncated_normal(shape, mean, stddev, dtype=dtype, seed=seed)\n\n\n# CTC\n# TensorFlow has a native implementation, but it uses sparse tensors\n# and therefore requires a wrapper for Keras. The functions below convert\n# dense to sparse tensors and also wraps up the beam search code that is\n# in TensorFlow's CTC implementation\n\n\ndef ctc_label_dense_to_sparse(labels, label_lengths):\n \"\"\"Converts CTC labels from dense to sparse.\n\n # Arguments\n labels: dense CTC labels.\n label_lengths: length of the labels.\n\n # Returns\n A sparse tensor representation of the labels.\n \"\"\"\n label_shape = tf.shape(labels)\n num_batches_tns = tf.stack([label_shape[0]])\n max_num_labels_tns = tf.stack([label_shape[1]])\n\n def range_less_than(_, current_input):\n return tf.expand_dims(tf.range(label_shape[1]), 0) < tf.fill(\n max_num_labels_tns, current_input)\n\n init = tf.cast(tf.fill([1, label_shape[1]], 0), tf.bool)\n dense_mask = functional_ops.scan(range_less_than, label_lengths,\n initializer=init, parallel_iterations=1)\n dense_mask = dense_mask[:, 0, :]\n\n label_array = tf.reshape(tf.tile(tf.range(label_shape[1]), num_batches_tns),\n label_shape)\n label_ind = tf.boolean_mask(label_array, dense_mask)\n\n tmp = tf.tile(tf.range(label_shape[0]), max_num_labels_tns)\n batch_array = tf.transpose(tf.reshape(tmp, reverse(label_shape, 0)))\n batch_ind = tf.boolean_mask(batch_array, dense_mask)\n\n indices = concatenate([batch_ind, label_ind], axis=0)\n indices = tf.transpose(tf.reshape(indices, [2, -1]))\n\n vals_sparse = tf.gather_nd(labels, indices)\n\n indices = tf.cast(indices, tf.int64)\n label_shape = tf.cast(label_shape, tf.int64)\n return tf.SparseTensor(indices, vals_sparse, label_shape)\n\n\ndef ctc_batch_cost(y_true, y_pred, input_length, label_length):\n \"\"\"Runs CTC loss algorithm on each batch element.\n\n # Arguments\n y_true: tensor `(samples, max_string_length)`\n containing the truth labels.\n y_pred: tensor `(samples, time_steps, num_categories)`\n containing the prediction, or output of the softmax.\n input_length: tensor `(samples, 1)` containing the sequence length for\n each batch item in `y_pred`.\n label_length: tensor `(samples, 1)` containing the sequence length for\n each batch item in `y_true`.\n\n # Returns\n Tensor with shape (samples,1) containing the\n CTC loss of each element.\n \"\"\"\n label_length = tf.cast(tf.squeeze(label_length, axis=-1), tf.int32)\n input_length = tf.cast(tf.squeeze(input_length, axis=-1), tf.int32)\n sparse_labels = tf.cast(\n ctc_label_dense_to_sparse(y_true, label_length), tf.int32)\n y_pred = tf.log(tf.transpose(y_pred, perm=[1, 0, 2]) + epsilon())\n return tf.expand_dims(ctc.ctc_loss(inputs=y_pred,\n labels=sparse_labels,\n sequence_length=input_length), 1)\n\n\ndef ctc_decode(y_pred, input_length, greedy=True, beam_width=100,\n top_paths=1, merge_repeated=False):\n \"\"\"Decodes the output of a softmax.\n\n Can use either greedy search (also known as best path)\n or a constrained dictionary search.\n\n # Arguments\n y_pred: tensor `(samples, time_steps, num_categories)`\n containing the prediction, or output of the softmax.\n input_length: tensor `(samples, )` containing the sequence length for\n each batch item in `y_pred`.\n greedy: perform much faster best-path search if `True`.\n This does not use a dictionary.\n beam_width: if `greedy` is `False`: a beam search decoder will be used\n with a beam of this width.\n top_paths: if `greedy` is `False`,\n how many of the most probable paths will be returned.\n merge_repeated: if `greedy` is `False`,\n merge repeated classes in the output beams.\n\n # Returns\n Tuple:\n List: if `greedy` is `True`, returns a list of one element that\n contains the decoded sequence.\n If `False`, returns the `top_paths` most probable\n decoded sequences.\n Important: blank labels are returned as `-1`.\n Tensor `(top_paths, )` that contains\n the log probability of each decoded sequence.\n \"\"\"\n y_pred = tf.log(tf.transpose(y_pred, perm=[1, 0, 2]) + epsilon())\n input_length = tf.cast(input_length, tf.int32)\n\n if greedy:\n (decoded, log_prob) = ctc.ctc_greedy_decoder(\n inputs=y_pred,\n sequence_length=input_length)\n else:\n (decoded, log_prob) = ctc.ctc_beam_search_decoder(\n inputs=y_pred,\n sequence_length=input_length, beam_width=beam_width,\n top_paths=top_paths, merge_repeated=merge_repeated)\n\n decoded_dense = []\n for st in decoded:\n dense_tensor = tf.sparse.to_dense(st, default_value=-1)\n decoded_dense.append(dense_tensor)\n return (decoded_dense, log_prob)\n\n\n# HIGH ORDER FUNCTIONS\n\ndef map_fn(fn, elems, name=None, dtype=None):\n \"\"\"Map the function fn over the elements elems and return the outputs.\n\n # Arguments\n fn: Callable that will be called upon each element in elems\n elems: tensor\n name: A string name for the map node in the graph\n dtype: Output data type.\n\n # Returns\n Tensor with dtype `dtype`.\n \"\"\"\n return tf.map_fn(fn, elems, name=name, dtype=dtype)\n\n\ndef foldl(fn, elems, initializer=None, name=None):\n \"\"\"Reduce elems using fn to combine them from left to right.\n\n # Arguments\n fn: Callable that will be called upon each element in elems and an\n accumulator, for instance `lambda acc, x: acc + x`\n elems: tensor\n initializer: The first value used (`elems[0]` in case of None)\n name: A string name for the foldl node in the graph\n\n # Returns\n Tensor with same type and shape as `initializer`.\n \"\"\"\n return tf.foldl(fn, elems, initializer=initializer, name=name)\n\n\ndef foldr(fn, elems, initializer=None, name=None):\n \"\"\"Reduce elems using fn to combine them from right to left.\n\n # Arguments\n fn: Callable that will be called upon each element in elems and an\n accumulator, for instance `lambda acc, x: acc + x`\n elems: tensor\n initializer: The first value used (`elems[-1]` in case of None)\n name: A string name for the foldr node in the graph\n\n # Returns\n Tensor with same type and shape as `initializer`.\n \"\"\"\n return tf.foldr(fn, elems, initializer=initializer, name=name)\n\n\ndef local_conv1d(inputs, kernel, kernel_size, strides, data_format=None):\n \"\"\"Apply 1D conv with un-shared weights.\n\n # Arguments\n inputs: 3D tensor with shape: (batch_size, steps, input_dim)\n kernel: the unshared weight for convolution,\n with shape (output_length, feature_dim, filters)\n kernel_size: a tuple of a single integer,\n specifying the length of the 1D convolution window\n strides: a tuple of a single integer,\n specifying the stride length of the convolution\n data_format: the data format, channels_first or channels_last\n\n # Returns\n the tensor after 1d conv with un-shared weights,\n with shape (batch_size, output_length, filters)\n\n # Raises\n ValueError: If `data_format` is neither\n `\"channels_last\"` nor `\"channels_first\"`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n\n stride = strides[0]\n kernel_shape = int_shape(kernel)\n output_length, feature_dim, filters = kernel_shape\n\n xs = []\n for i in range(output_length):\n slice_length = py_slice(i * stride,\n i * stride + kernel_size[0])\n xs.append(reshape(inputs[:, slice_length, :],\n (1, -1, feature_dim)))\n x_aggregate = concatenate(xs, axis=0)\n # Shape: `(output_length, batch_size, filters)`.\n output = batch_dot(x_aggregate, kernel)\n return permute_dimensions(output, (1, 0, 2))\n\n\ndef local_conv2d(inputs,\n kernel,\n kernel_size,\n strides,\n output_shape,\n data_format=None):\n \"\"\"Apply 2D conv with un-shared weights.\n\n # Arguments\n inputs: 4D tensor with shape:\n (batch_size, filters, new_rows, new_cols)\n if data_format='channels_first'\n or 4D tensor with shape:\n (batch_size, new_rows, new_cols, filters)\n if data_format='channels_last'.\n kernel: the unshared weight for convolution,\n with shape (output_items, feature_dim, filters)\n kernel_size: a tuple of 2 integers, specifying the\n width and height of the 2D convolution window.\n strides: a tuple of 2 integers, specifying the strides\n of the convolution along the width and height.\n output_shape: a tuple with (output_row, output_col)\n data_format: the data format, channels_first or channels_last\n\n # Returns\n A 4d tensor with shape:\n (batch_size, filters, new_rows, new_cols)\n if data_format='channels_first'\n or 4D tensor with shape:\n (batch_size, new_rows, new_cols, filters)\n if data_format='channels_last'.\n\n # Raises\n ValueError: if `data_format` is neither\n `channels_last` or `channels_first`.\n \"\"\"\n data_format = normalize_data_format(data_format)\n\n stride_row, stride_col = strides\n output_row, output_col = output_shape\n kernel_shape = int_shape(kernel)\n _, feature_dim, filters = kernel_shape\n\n xs = []\n for i in range(output_row):\n for j in range(output_col):\n slice_row = py_slice(i * stride_row,\n i * stride_row + kernel_size[0])\n slice_col = py_slice(j * stride_col,\n j * stride_col + kernel_size[1])\n if data_format == 'channels_first':\n xs.append(reshape(inputs[:, :, slice_row, slice_col],\n (1, -1, feature_dim)))\n else:\n xs.append(reshape(inputs[:, slice_row, slice_col, :],\n (1, -1, feature_dim)))\n\n x_aggregate = concatenate(xs, axis=0)\n output = batch_dot(x_aggregate, kernel)\n output = reshape(output,\n (output_row, output_col, -1, filters))\n\n if data_format == 'channels_first':\n output = permute_dimensions(output, (2, 3, 0, 1))\n else:\n output = permute_dimensions(output, (2, 0, 1, 3))\n return output\n"
] |
[
[
"tensorflow.compat.v1.assign_sub",
"tensorflow.compat.v1.reduce_all",
"tensorflow.compat.v1.foldr",
"tensorflow.compat.v1.nn.elu",
"tensorflow.compat.v1.eye",
"tensorflow.compat.v1.image.resize_nearest_neighbor",
"tensorflow.python.ops.ctc_ops.ctc_loss",
"tensorflow.compat.v1.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.compat.v1.ones_like",
"tensorflow.compat.v1.argmin",
"tensorflow.compat.v1.nn.softmax",
"tensorflow.compat.v1.reduce_any",
"tensorflow.python.ops.ctc_ops.ctc_greedy_decoder",
"tensorflow.compat.v1.split",
"numpy.delete",
"tensorflow.compat.v1.Print",
"tensorflow.compat.v1.reduce_max",
"tensorflow.compat.v1.nn.fused_batch_norm",
"numpy.array",
"tensorflow.core.protobuf.config_pb2.CallableOptions",
"tensorflow.compat.v1.log",
"tensorflow.compat.v1.stack",
"tensorflow.compat.v1.nn.tanh",
"tensorflow.compat.v1.assign_add",
"tensorflow.compat.v1.nn.embedding_lookup",
"tensorflow.compat.v1.nn.sigmoid_cross_entropy_with_logits",
"tensorflow.compat.v1.nn.bias_add",
"tensorflow.compat.v1.__version__.split",
"tensorflow.compat.v1.sin",
"tensorflow.compat.v1.nn.dropout",
"numpy.expand_dims",
"tensorflow.compat.v1.sparse_placeholder",
"tensorflow.compat.v1.concat",
"tensorflow.python.client.device_lib.list_local_devices",
"tensorflow.compat.v1.equal",
"tensorflow.python.framework.ops._as_graph_element",
"tensorflow.python.ops.control_flow_ops.while_loop",
"tensorflow.compat.v1.gradients",
"tensorflow.compat.v1.group",
"tensorflow.compat.v1.nn.softsign",
"tensorflow.compat.v1.shape",
"tensorflow.compat.v1.truncated_normal",
"tensorflow.compat.v1.nn.depthwise_conv2d",
"tensorflow.python.training.moving_averages.assign_moving_average",
"tensorflow.compat.v1.nn.sigmoid",
"tensorflow.compat.v1.sparse_tensor_to_dense",
"tensorflow.compat.v1.global_variables",
"tensorflow.compat.v1.reduce_sum",
"tensorflow.compat.v1.one_hot",
"tensorflow.compat.v1.random_uniform",
"tensorflow.python.ops.ctc_ops.ctc_beam_search_decoder",
"tensorflow.compat.v1.transpose",
"tensorflow.compat.v1.name_scope",
"tensorflow.compat.v1.where",
"tensorflow.python.ops.tensor_array_ops.TensorArray",
"tensorflow.compat.v1.reduce_logsumexp",
"tensorflow.compat.v1.nn.softplus",
"tensorflow.compat.v1.zeros",
"tensorflow.compat.v1.map_fn",
"tensorflow.compat.v1.nn.leaky_relu",
"tensorflow.compat.v1.tile",
"tensorflow.compat.v1.sparse_tensor_dense_matmul",
"tensorflow.compat.v1.disable_eager_execution",
"tensorflow.compat.v1.get_default_graph",
"tensorflow.compat.v1.variables_initializer",
"tensorflow.compat.v1.control_dependencies",
"tensorflow.compat.v1.slice",
"tensorflow.compat.v1.random_uniform_initializer",
"tensorflow.compat.v1.cumprod",
"tensorflow.compat.v1.sqrt",
"tensorflow.compat.v1.boolean_mask",
"tensorflow.python.framework.ops.is_dense_tensor_like",
"tensorflow.compat.v1.greater_equal",
"tensorflow.compat.v1.placeholder_with_default",
"tensorflow.compat.v1.nn.avg_pool3d",
"tensorflow.compat.v1.constant",
"tensorflow.compat.v1.cumsum",
"numpy.random.randint",
"tensorflow.compat.v1.pow",
"tensorflow.compat.v1.ones",
"tensorflow.compat.v1.round",
"tensorflow.compat.v1.nn.avg_pool",
"tensorflow.compat.v1.maximum",
"tensorflow.compat.v1.nn.batch_normalization",
"tensorflow.compat.v1.nn.moments",
"tensorflow.compat.v1.fill",
"tensorflow.compat.v1.SparseTensor",
"tensorflow.compat.v1.clip_by_value",
"tensorflow.compat.v1.minimum",
"tensorflow.compat.v1.nn.relu",
"tensorflow.compat.v1.nn.max_pool",
"tensorflow.compat.v1.cond",
"tensorflow.compat.v1.cast",
"tensorflow.compat.v1.nn.conv3d_transpose",
"tensorflow.compat.v1.sparse_concat",
"tensorflow.compat.v1.ConfigProto",
"tensorflow.compat.v1.as_dtype",
"tensorflow.compat.v1.is_variable_initialized",
"tensorflow.compat.v1.expand_dims",
"tensorflow.compat.v1.reduce_prod",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.matmul",
"tensorflow.compat.v1.placeholder",
"tensorflow.compat.v1.reset_default_graph",
"tensorflow.compat.v1.squeeze",
"tensorflow.compat.v1.pad",
"tensorflow.compat.v1.nn.in_top_k",
"tensorflow.compat.v1.not_equal",
"tensorflow.compat.v1.random_normal",
"tensorflow.compat.v1.nn.convolution",
"tensorflow.compat.v1.identity",
"tensorflow.compat.v1.reverse",
"tensorflow.compat.v1.nn.relu6",
"tensorflow.compat.v1.abs",
"tensorflow.compat.v1.cos",
"tensorflow.compat.v1.reshape",
"tensorflow.compat.v1.nn.atrous_conv2d_transpose",
"tensorflow.compat.v1.stop_gradient",
"tensorflow.compat.v1.zeros_like",
"tensorflow.compat.v1.foldl",
"tensorflow.compat.v1.unstack",
"tensorflow.compat.v1.gather_nd",
"tensorflow.compat.v1.square",
"tensorflow.compat.v1.exp",
"tensorflow.compat.v1.nn.softmax_cross_entropy_with_logits",
"tensorflow.compat.v1.sparse.to_dense",
"tensorflow.compat.v1.assign",
"tensorflow.compat.v1.reduce_mean",
"tensorflow.compat.v1.less",
"tensorflow.compat.v1.get_default_session",
"tensorflow.compat.v1.nn.separable_conv2d",
"tensorflow.compat.v1.image.resize_bilinear",
"tensorflow.compat.v1.nn.l2_normalize",
"tensorflow.compat.v1.random_normal_initializer",
"tensorflow.compat.v1.less_equal",
"tensorflow.python.ops.functional_ops.scan",
"tensorflow.compat.v1.argmax",
"tensorflow.compat.v1.nn.conv2d_transpose",
"tensorflow.compat.v1.convert_to_tensor",
"tensorflow.compat.v1.nn.max_pool3d",
"tensorflow.compat.v1.reduce_min",
"tensorflow.compat.v1.range",
"tensorflow.compat.v1.sign",
"tensorflow.compat.v1.greater"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mweiss17/transformers
|
[
"ae88d5adc89a2020c21d62481e98f058f91784aa"
] |
[
"src/transformers/trainer.py"
] |
[
"# coding=utf-8\n# Copyright 2020-present the HuggingFace Inc. team.\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\"\"\"\nThe Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task.\n\"\"\"\n\nimport collections\nimport inspect\nimport math\nimport os\nimport random\nimport re\nimport shutil\nimport sys\nimport time\nimport warnings\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union\n\nfrom tqdm.auto import tqdm\n\n\n# Integrations must be imported before ML frameworks:\nfrom .integrations import ( # isort: split\n default_hp_search_backend,\n get_reporting_integration_callbacks,\n hp_params,\n is_fairscale_available,\n is_optuna_available,\n is_ray_tune_available,\n run_hp_search_optuna,\n run_hp_search_ray,\n)\n\nimport numpy as np\nimport torch\nfrom packaging import version\nfrom torch import nn\nfrom torch.utils.data import DataLoader, Dataset, IterableDataset, RandomSampler, SequentialSampler\nfrom torch.utils.data.distributed import DistributedSampler\n\nfrom . import __version__\nfrom .configuration_utils import PretrainedConfig\nfrom .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator\nfrom .debug_utils import DebugOption, DebugUnderflowOverflow\nfrom .deepspeed import deepspeed_init, is_deepspeed_zero3_enabled\nfrom .dependency_versions_check import dep_version_check\nfrom .file_utils import (\n CONFIG_NAME,\n WEIGHTS_NAME,\n PushToHubMixin,\n is_apex_available,\n is_datasets_available,\n is_in_notebook,\n is_sagemaker_dp_enabled,\n is_sagemaker_mp_enabled,\n is_torch_tpu_available,\n)\nfrom .modelcard import TrainingSummary\nfrom .modeling_utils import PreTrainedModel, unwrap_model\nfrom .models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES\nfrom .optimization import Adafactor, AdamW, get_scheduler\nfrom .tokenization_utils_base import PreTrainedTokenizerBase\nfrom .trainer_callback import (\n CallbackHandler,\n DefaultFlowCallback,\n PrinterCallback,\n ProgressCallback,\n TrainerCallback,\n TrainerControl,\n TrainerState,\n)\nfrom .trainer_pt_utils import (\n DistributedLengthGroupedSampler,\n DistributedSamplerWithLoop,\n DistributedTensorGatherer,\n IterableDatasetShard,\n LabelSmoother,\n LengthGroupedSampler,\n SequentialDistributedSampler,\n ShardSampler,\n distributed_broadcast_scalars,\n distributed_concat,\n find_batch_size,\n get_parameter_names,\n nested_concat,\n nested_detach,\n nested_numpify,\n nested_truncate,\n nested_xla_mesh_reduce,\n reissue_pt_warnings,\n)\nfrom .trainer_utils import (\n PREFIX_CHECKPOINT_DIR,\n BestRun,\n EvalLoopOutput,\n EvalPrediction,\n HPSearchBackend,\n PredictionOutput,\n ShardedDDPOption,\n TrainerMemoryTracker,\n TrainOutput,\n default_compute_objective,\n default_hp_space,\n denumpify_detensorize,\n get_last_checkpoint,\n number_of_arguments,\n set_seed,\n speed_metrics,\n)\nfrom .training_args import ParallelMode, TrainingArguments\nfrom .utils import logging\n\n\n_is_torch_generator_available = False\n_is_native_amp_available = False\n\nDEFAULT_CALLBACKS = [DefaultFlowCallback]\nDEFAULT_PROGRESS_CALLBACK = ProgressCallback\n\nif is_in_notebook():\n from .utils.notebook import NotebookProgressCallback\n\n DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback\n\nif is_apex_available():\n from apex import amp\n\nif version.parse(torch.__version__) >= version.parse(\"1.6\"):\n _is_torch_generator_available = True\n _is_native_amp_available = True\n from torch.cuda.amp import autocast\n\nif is_datasets_available():\n import datasets\n\nif is_torch_tpu_available():\n import torch_xla.core.xla_model as xm\n import torch_xla.debug.metrics as met\n import torch_xla.distributed.parallel_loader as pl\n\nif is_fairscale_available():\n dep_version_check(\"fairscale\")\n import fairscale\n from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP\n from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP\n from fairscale.nn.wrap import auto_wrap\n from fairscale.optim import OSS\n from fairscale.optim.grad_scaler import ShardedGradScaler\n\nif is_sagemaker_dp_enabled():\n import smdistributed.dataparallel.torch.distributed as dist\n from smdistributed.dataparallel.torch.parallel.distributed import DistributedDataParallel as DDP\nelse:\n import torch.distributed as dist\n\nif is_sagemaker_mp_enabled():\n import smdistributed.modelparallel.torch as smp\n\n from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat\n\n\nif TYPE_CHECKING:\n import optuna\n\nlogger = logging.get_logger(__name__)\n\n\nclass Trainer:\n \"\"\"\n Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers.\n\n Args:\n model (:class:`~transformers.PreTrainedModel` or :obj:`torch.nn.Module`, `optional`):\n The model to train, evaluate or use for predictions. If not provided, a ``model_init`` must be passed.\n\n .. note::\n\n :class:`~transformers.Trainer` is optimized to work with the :class:`~transformers.PreTrainedModel`\n provided by the library. You can still use your own models defined as :obj:`torch.nn.Module` as long as\n they work the same way as the 🤗 Transformers models.\n args (:class:`~transformers.TrainingArguments`, `optional`):\n The arguments to tweak for training. Will default to a basic instance of\n :class:`~transformers.TrainingArguments` with the ``output_dir`` set to a directory named `tmp_trainer` in\n the current directory if not provided.\n data_collator (:obj:`DataCollator`, `optional`):\n The function to use to form a batch from a list of elements of :obj:`train_dataset` or :obj:`eval_dataset`.\n Will default to :func:`~transformers.default_data_collator` if no ``tokenizer`` is provided, an instance of\n :func:`~transformers.DataCollatorWithPadding` otherwise.\n train_dataset (:obj:`torch.utils.data.Dataset` or :obj:`torch.utils.data.IterableDataset`, `optional`):\n The dataset to use for training. If it is an :obj:`datasets.Dataset`, columns not accepted by the\n ``model.forward()`` method are automatically removed.\n\n Note that if it's a :obj:`torch.utils.data.IterableDataset` with some randomization and you are training in\n a distributed fashion, your iterable dataset should either use a internal attribute :obj:`generator` that\n is a :obj:`torch.Generator` for the randomization that must be identical on all processes (and the Trainer\n will manually set the seed of this :obj:`generator` at each epoch) or have a :obj:`set_epoch()` method that\n internally sets the seed of the RNGs used.\n eval_dataset (:obj:`torch.utils.data.Dataset`, `optional`):\n The dataset to use for evaluation. If it is an :obj:`datasets.Dataset`, columns not accepted by the\n ``model.forward()`` method are automatically removed.\n tokenizer (:class:`PreTrainedTokenizerBase`, `optional`):\n The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the\n maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an\n interrupted training or reuse the fine-tuned model.\n model_init (:obj:`Callable[[], PreTrainedModel]`, `optional`):\n A function that instantiates the model to be used. If provided, each call to\n :meth:`~transformers.Trainer.train` will start from a new instance of the model as given by this function.\n\n The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be\n able to choose different architectures according to hyper parameters (such as layer count, sizes of inner\n layers, dropout probabilities etc).\n compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`):\n The function that will be used to compute metrics at evaluation. Must take a\n :class:`~transformers.EvalPrediction` and return a dictionary string to metric values.\n callbacks (List of :obj:`~transformers.TrainerCallback`, `optional`):\n A list of callbacks to customize the training loop. Will add those to the list of default callbacks\n detailed in :doc:`here <callback>`.\n\n If you want to remove one of the default callbacks used, use the :meth:`Trainer.remove_callback` method.\n optimizers (:obj:`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR`, `optional`): A tuple\n containing the optimizer and the scheduler to use. Will default to an instance of\n :class:`~transformers.AdamW` on your model and a scheduler given by\n :func:`~transformers.get_linear_schedule_with_warmup` controlled by :obj:`args`.\n\n Important attributes:\n\n - **model** -- Always points to the core model. If using a transformers model, it will be a\n :class:`~transformers.PreTrainedModel` subclass.\n - **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the\n original model. This is the model that should be used for the forward pass. For example, under ``DeepSpeed``,\n the inner model is wrapped in ``DeepSpeed`` and then again in ``torch.nn.DistributedDataParallel``. If the\n inner model hasn't been wrapped, then ``self.model_wrapped`` is the same as ``self.model``.\n - **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from\n data parallelism, this means some of the model layers are split on different GPUs).\n - **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set\n to :obj:`False` if model parallel or deepspeed is used, or if the default\n ``TrainingArguments.place_model_on_device`` is overridden to return :obj:`False` .\n - **is_in_train** -- Whether or not a model is currently running ``train`` (e.g. when ``evaluate`` is called\n while in ``train``)\n\n \"\"\"\n\n from .trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state\n\n def __init__(\n self,\n model: Union[PreTrainedModel, nn.Module] = None,\n args: TrainingArguments = None,\n data_collator: Optional[DataCollator] = None,\n train_dataset: Optional[Dataset] = None,\n eval_dataset: Optional[Dataset] = None,\n tokenizer: Optional[PreTrainedTokenizerBase] = None,\n model_init: Callable[[], PreTrainedModel] = None,\n compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,\n callbacks: Optional[List[TrainerCallback]] = None,\n optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),\n ):\n if args is None:\n output_dir = \"tmp_trainer\"\n logger.info(f\"No `TrainingArguments` passed, using `output_dir={output_dir}`.\")\n args = TrainingArguments(output_dir=output_dir)\n self.args = args\n # Seed must be set before instantiating the model when using model\n set_seed(self.args.seed)\n self.hp_name = None\n self.deepspeed = None\n self.is_in_train = False\n\n # memory metrics - must set up as early as possible\n self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics)\n self._memory_tracker.start()\n\n # set the correct log level depending on the node\n log_level = args.get_process_log_level()\n logging.set_verbosity(log_level)\n\n # force device and distributed setup init explicitly\n args._setup_devices\n\n if model is None:\n if model_init is not None:\n self.model_init = model_init\n model = self.call_model_init()\n else:\n raise RuntimeError(\"`Trainer` requires either a `model` or `model_init` argument\")\n else:\n if model_init is not None:\n warnings.warn(\n \"`Trainer` requires either a `model` or `model_init` argument, but not both. \"\n \"`model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.\",\n FutureWarning,\n )\n self.model_init = model_init\n\n if hasattr(model, \"is_parallelizable\") and model.is_parallelizable and model.model_parallel:\n self.is_model_parallel = True\n else:\n self.is_model_parallel = False\n\n # Setup Sharded DDP training\n self.sharded_ddp = None\n if len(args.sharded_ddp) > 0:\n if args.deepspeed:\n raise ValueError(\n \"Using --sharded_ddp xxx together with --deepspeed is not possible, deactivate one of those flags.\"\n )\n\n if args.local_rank == -1:\n raise ValueError(\"Using sharded DDP only works in distributed training.\")\n elif not is_fairscale_available():\n raise ImportError(\"Sharded DDP training requires fairscale: `pip install fairscale`.\")\n elif ShardedDDPOption.SIMPLE not in args.sharded_ddp and FullyShardedDDP is None:\n raise ImportError(\n \"Sharded DDP in a mode other than simple training requires fairscale version >= 0.3, found \"\n f\"{fairscale.__version__}. Upgrade your fairscale library: `pip install --upgrade fairscale`.\"\n )\n elif ShardedDDPOption.SIMPLE in args.sharded_ddp:\n self.sharded_ddp = ShardedDDPOption.SIMPLE\n elif ShardedDDPOption.ZERO_DP_2 in args.sharded_ddp:\n self.sharded_ddp = ShardedDDPOption.ZERO_DP_2\n elif ShardedDDPOption.ZERO_DP_3 in args.sharded_ddp:\n self.sharded_ddp = ShardedDDPOption.ZERO_DP_3\n\n # one place to sort out whether to place the model on device or not\n # postpone switching model to cuda when:\n # 1. MP - since we are trying to fit a much bigger than 1 gpu model\n # 2. fp16-enabled DeepSpeed loads the model in half the size and it doesn't need .to() anyway,\n # and we only use deepspeed for training at the moment\n # 3. full fp16 eval - since the model needs to be half'ed first\n # 4. Sharded DDP - same as MP\n self.place_model_on_device = args.place_model_on_device\n if (\n self.is_model_parallel\n or args.deepspeed\n or (args.fp16_full_eval and not args.do_train)\n or (self.sharded_ddp in [ShardedDDPOption.ZERO_DP_2, ShardedDDPOption.ZERO_DP_3])\n ):\n self.place_model_on_device = False\n\n default_collator = default_data_collator if tokenizer is None else DataCollatorWithPadding(tokenizer)\n self.data_collator = data_collator if data_collator is not None else default_collator\n self.train_dataset = train_dataset\n self.eval_dataset = eval_dataset\n self.tokenizer = tokenizer\n\n if self.place_model_on_device:\n self._move_model_to_device(model, args.device)\n\n # Force n_gpu to 1 to avoid DataParallel as MP will manage the GPUs\n if self.is_model_parallel:\n self.args._n_gpu = 1\n\n # later use `self.model is self.model_wrapped` to check if it's wrapped or not\n self.model_wrapped = model\n self.model = model\n\n self.compute_metrics = compute_metrics\n self.optimizer, self.lr_scheduler = optimizers\n if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None):\n raise RuntimeError(\n \"Passing a `model_init` is incompatible with providing the `optimizers` argument.\"\n \"You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method.\"\n )\n default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to)\n callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks\n self.callback_handler = CallbackHandler(\n callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler\n )\n self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK)\n\n # Will be set to True by `self._setup_loggers()` on first call to `self.log()`.\n self._loggers_initialized = False\n\n # Create clone of distant repo and output directory if needed\n if self.args.push_to_hub:\n self.init_git_repo()\n if self.args.should_save:\n os.makedirs(self.args.output_dir, exist_ok=True)\n\n if not callable(self.data_collator) and callable(getattr(self.data_collator, \"collate_batch\", None)):\n raise ValueError(\"The `data_collator` should be a simple callable (function, class with `__call__`).\")\n\n if args.max_steps > 0:\n logger.info(\"max_steps is given, it will override any value given in num_train_epochs\")\n\n if train_dataset is not None and not isinstance(train_dataset, collections.abc.Sized) and args.max_steps <= 0:\n raise ValueError(\"train_dataset does not implement __len__, max_steps has to be specified\")\n\n self._signature_columns = None\n\n # Mixed precision setup\n self.use_apex = False\n self.use_amp = False\n self.fp16_backend = None\n\n if args.fp16:\n if args.fp16_backend == \"auto\":\n self.fp16_backend = \"amp\" if _is_native_amp_available else \"apex\"\n else:\n self.fp16_backend = args.fp16_backend\n logger.info(f\"Using {self.fp16_backend} fp16 backend\")\n\n if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16\n if self.fp16_backend == \"amp\":\n self.use_amp = True\n if is_sagemaker_mp_enabled():\n self.scaler = smp.amp.GradScaler()\n elif self.sharded_ddp is not None:\n self.scaler = ShardedGradScaler()\n else:\n self.scaler = torch.cuda.amp.GradScaler()\n else:\n if not is_apex_available():\n raise ImportError(\n \"Using FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex.\"\n )\n self.use_apex = True\n\n # FP16 + model parallelism in SageMaker: gradient clipping does not work for now so we raise a helpful error.\n if is_sagemaker_mp_enabled() and self.use_amp and args.max_grad_norm is not None and args.max_grad_norm > 0:\n raise ValueError(\n \"SageMaker Model Parallelism in mixed precision mode does not support gradient clipping yet. Pass \"\n \"along 'max_grad_norm': 0 in your hyperparameters.\"\n )\n\n # Label smoothing\n if self.args.label_smoothing_factor != 0:\n self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor)\n else:\n self.label_smoother = None\n\n self.state = TrainerState()\n self.control = TrainerControl()\n # Internal variable to count flos in each process, will be accumulated in `self.state.total_flos` then\n # returned to 0 every time flos need to be logged\n self.current_flos = 0\n self.hp_search_backend = None\n self.use_tune_checkpoints = False\n default_label_names = (\n [\"start_positions\", \"end_positions\"]\n if type(self.model).__name__ in MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES.values()\n else [\"labels\"]\n )\n self.label_names = default_label_names if self.args.label_names is None else self.args.label_names\n self.control = self.callback_handler.on_init_end(self.args, self.state, self.control)\n\n # very last\n self._memory_tracker.stop_and_update_metrics()\n\n def add_callback(self, callback):\n \"\"\"\n Add a callback to the current list of :class:`~transformer.TrainerCallback`.\n\n Args:\n callback (:obj:`type` or :class:`~transformer.TrainerCallback`):\n A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.\n In the first case, will instantiate a member of that class.\n \"\"\"\n self.callback_handler.add_callback(callback)\n\n def pop_callback(self, callback):\n \"\"\"\n Remove a callback from the current list of :class:`~transformer.TrainerCallback` and returns it.\n\n If the callback is not found, returns :obj:`None` (and no error is raised).\n\n Args:\n callback (:obj:`type` or :class:`~transformer.TrainerCallback`):\n A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.\n In the first case, will pop the first member of that class found in the list of callbacks.\n\n Returns:\n :class:`~transformer.TrainerCallback`: The callback removed, if found.\n \"\"\"\n return self.callback_handler.pop_callback(callback)\n\n def remove_callback(self, callback):\n \"\"\"\n Remove a callback from the current list of :class:`~transformer.TrainerCallback`.\n\n Args:\n callback (:obj:`type` or :class:`~transformer.TrainerCallback`):\n A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.\n In the first case, will remove the first member of that class found in the list of callbacks.\n \"\"\"\n self.callback_handler.remove_callback(callback)\n\n def _move_model_to_device(self, model, device):\n model = model.to(device)\n # Moving a model to an XLA device disconnects the tied weights, so we have to retie them.\n if self.args.parallel_mode == ParallelMode.TPU and hasattr(model, \"tie_weights\"):\n model.tie_weights()\n\n def _remove_unused_columns(self, dataset: \"datasets.Dataset\", description: Optional[str] = None):\n if not self.args.remove_unused_columns:\n return dataset\n if self._signature_columns is None:\n # Inspect model forward signature to keep only the arguments it accepts.\n signature = inspect.signature(self.model.forward)\n self._signature_columns = list(signature.parameters.keys())\n # Labels may be named label or label_ids, the default data collator handles that.\n self._signature_columns += [\"label\", \"label_ids\"]\n columns = [k for k in self._signature_columns if k in dataset.column_names]\n ignored_columns = list(set(dataset.column_names) - set(self._signature_columns))\n if len(ignored_columns) > 0:\n dset_description = \"\" if description is None else f\"in the {description} set \"\n logger.info(\n f\"The following columns {dset_description} don't have a corresponding argument in \"\n f\"`{self.model.__class__.__name__}.forward` and have been ignored: {', '.join(ignored_columns)}.\"\n )\n\n if version.parse(datasets.__version__) < version.parse(\"1.4.0\"):\n dataset.set_format(\n type=dataset.format[\"type\"], columns=columns, format_kwargs=dataset.format[\"format_kwargs\"]\n )\n return dataset\n else:\n return dataset.remove_columns(ignored_columns)\n\n def _get_train_sampler(self) -> Optional[torch.utils.data.Sampler]:\n if not isinstance(self.train_dataset, collections.abc.Sized):\n return None\n\n generator = None\n if self.args.world_size <= 1 and _is_torch_generator_available:\n generator = torch.Generator()\n generator.manual_seed(int(torch.empty((), dtype=torch.int64).random_().item()))\n\n # Build the sampler.\n if self.args.group_by_length:\n if is_datasets_available() and isinstance(self.train_dataset, datasets.Dataset):\n lengths = (\n self.train_dataset[self.args.length_column_name]\n if self.args.length_column_name in self.train_dataset.column_names\n else None\n )\n else:\n lengths = None\n model_input_name = self.tokenizer.model_input_names[0] if self.tokenizer is not None else None\n if self.args.world_size <= 1:\n return LengthGroupedSampler(\n self.train_dataset,\n self.args.train_batch_size,\n lengths=lengths,\n model_input_name=model_input_name,\n generator=generator,\n )\n else:\n return DistributedLengthGroupedSampler(\n self.train_dataset,\n self.args.train_batch_size,\n num_replicas=self.args.world_size,\n rank=self.args.process_index,\n lengths=lengths,\n model_input_name=model_input_name,\n seed=self.args.seed,\n )\n\n else:\n if self.args.world_size <= 1:\n if _is_torch_generator_available:\n return RandomSampler(self.train_dataset, generator=generator)\n return RandomSampler(self.train_dataset)\n elif (\n self.args.parallel_mode in [ParallelMode.TPU, ParallelMode.SAGEMAKER_MODEL_PARALLEL]\n and not self.args.dataloader_drop_last\n ):\n # Use a loop for TPUs when drop_last is False to have all batches have the same size.\n return DistributedSamplerWithLoop(\n self.train_dataset,\n batch_size=self.args.per_device_train_batch_size,\n num_replicas=self.args.world_size,\n rank=self.args.process_index,\n seed=self.args.seed,\n )\n else:\n return DistributedSampler(\n self.train_dataset,\n num_replicas=self.args.world_size,\n rank=self.args.process_index,\n seed=self.args.seed,\n )\n\n def get_train_dataloader(self) -> DataLoader:\n \"\"\"\n Returns the training :class:`~torch.utils.data.DataLoader`.\n\n Will use no sampler if :obj:`self.train_dataset` does not implement :obj:`__len__`, a random sampler (adapted\n to distributed training if necessary) otherwise.\n\n Subclass and override this method if you want to inject some custom behavior.\n \"\"\"\n if self.train_dataset is None:\n raise ValueError(\"Trainer: training requires a train_dataset.\")\n\n train_dataset = self.train_dataset\n if is_datasets_available() and isinstance(train_dataset, datasets.Dataset):\n train_dataset = self._remove_unused_columns(train_dataset, description=\"training\")\n\n if isinstance(train_dataset, torch.utils.data.IterableDataset):\n if self.args.world_size > 1:\n train_dataset = IterableDatasetShard(\n train_dataset,\n batch_size=self.args.train_batch_size,\n drop_last=self.args.dataloader_drop_last,\n num_processes=self.args.world_size,\n process_index=self.args.process_index,\n )\n\n return DataLoader(\n train_dataset,\n batch_size=self.args.train_batch_size,\n collate_fn=self.data_collator,\n num_workers=self.args.dataloader_num_workers,\n pin_memory=self.args.dataloader_pin_memory,\n )\n\n train_sampler = self._get_train_sampler()\n\n return DataLoader(\n train_dataset,\n batch_size=self.args.train_batch_size,\n sampler=train_sampler,\n collate_fn=self.data_collator,\n drop_last=self.args.dataloader_drop_last,\n num_workers=self.args.dataloader_num_workers,\n pin_memory=self.args.dataloader_pin_memory,\n )\n\n def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.Sampler]:\n # Deprecated code\n if self.args.use_legacy_prediction_loop:\n if is_torch_tpu_available():\n return SequentialDistributedSampler(\n eval_dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal()\n )\n elif is_sagemaker_mp_enabled():\n return SequentialDistributedSampler(\n eval_dataset,\n num_replicas=smp.dp_size(),\n rank=smp.dp_rank(),\n batch_size=self.args.per_device_eval_batch_size,\n )\n elif self.args.local_rank != -1:\n return SequentialDistributedSampler(eval_dataset)\n else:\n return SequentialSampler(eval_dataset)\n\n if self.args.world_size <= 1:\n return SequentialSampler(eval_dataset)\n else:\n return ShardSampler(\n eval_dataset,\n batch_size=self.args.per_device_eval_batch_size,\n num_processes=self.args.world_size,\n process_index=self.args.process_index,\n )\n\n def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:\n \"\"\"\n Returns the evaluation :class:`~torch.utils.data.DataLoader`.\n\n Subclass and override this method if you want to inject some custom behavior.\n\n Args:\n eval_dataset (:obj:`torch.utils.data.Dataset`, `optional`):\n If provided, will override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not\n accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.\n \"\"\"\n if eval_dataset is None and self.eval_dataset is None:\n raise ValueError(\"Trainer: evaluation requires an eval_dataset.\")\n eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset\n\n if is_datasets_available() and isinstance(eval_dataset, datasets.Dataset):\n eval_dataset = self._remove_unused_columns(eval_dataset, description=\"evaluation\")\n\n if isinstance(eval_dataset, torch.utils.data.IterableDataset):\n if self.args.world_size > 1:\n eval_dataset = IterableDatasetShard(\n eval_dataset,\n batch_size=self.args.eval_batch_size,\n drop_last=self.args.dataloader_drop_last,\n num_processes=self.args.world_size,\n process_index=self.args.process_index,\n )\n return DataLoader(\n eval_dataset,\n batch_size=self.args.eval_batch_size,\n collate_fn=self.data_collator,\n num_workers=self.args.dataloader_num_workers,\n pin_memory=self.args.dataloader_pin_memory,\n )\n\n eval_sampler = self._get_eval_sampler(eval_dataset)\n\n return DataLoader(\n eval_dataset,\n sampler=eval_sampler,\n batch_size=self.args.eval_batch_size,\n collate_fn=self.data_collator,\n drop_last=self.args.dataloader_drop_last,\n num_workers=self.args.dataloader_num_workers,\n pin_memory=self.args.dataloader_pin_memory,\n )\n\n def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader:\n \"\"\"\n Returns the test :class:`~torch.utils.data.DataLoader`.\n\n Subclass and override this method if you want to inject some custom behavior.\n\n Args:\n test_dataset (:obj:`torch.utils.data.Dataset`, `optional`):\n The test dataset to use. If it is an :obj:`datasets.Dataset`, columns not accepted by the\n ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.\n \"\"\"\n if is_datasets_available() and isinstance(test_dataset, datasets.Dataset):\n test_dataset = self._remove_unused_columns(test_dataset, description=\"test\")\n\n if isinstance(test_dataset, torch.utils.data.IterableDataset):\n if self.args.world_size > 1:\n test_dataset = IterableDatasetShard(\n test_dataset,\n batch_size=self.args.eval_batch_size,\n drop_last=self.args.dataloader_drop_last,\n num_processes=self.args.world_size,\n process_index=self.args.process_index,\n )\n return DataLoader(\n test_dataset,\n batch_size=self.args.eval_batch_size,\n collate_fn=self.data_collator,\n num_workers=self.args.dataloader_num_workers,\n pin_memory=self.args.dataloader_pin_memory,\n )\n\n test_sampler = self._get_eval_sampler(test_dataset)\n\n # We use the same batch_size as for eval.\n return DataLoader(\n test_dataset,\n sampler=test_sampler,\n batch_size=self.args.eval_batch_size,\n collate_fn=self.data_collator,\n drop_last=self.args.dataloader_drop_last,\n pin_memory=self.args.dataloader_pin_memory,\n )\n\n def create_optimizer_and_scheduler(self, num_training_steps: int):\n \"\"\"\n Setup the optimizer and the learning rate scheduler.\n\n We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the\n Trainer's init through :obj:`optimizers`, or subclass and override this method (or :obj:`create_optimizer`\n and/or :obj:`create_scheduler`) in a subclass.\n \"\"\"\n self.create_optimizer()\n self.create_scheduler(num_training_steps)\n\n def create_optimizer(self):\n \"\"\"\n Setup the optimizer.\n\n We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the\n Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.\n \"\"\"\n if self.optimizer is None:\n decay_parameters = get_parameter_names(self.model, [nn.LayerNorm])\n decay_parameters = [name for name in decay_parameters if \"bias\" not in name]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in self.model.named_parameters() if n in decay_parameters],\n \"weight_decay\": self.args.weight_decay,\n },\n {\n \"params\": [p for n, p in self.model.named_parameters() if n not in decay_parameters],\n \"weight_decay\": 0.0,\n },\n ]\n optimizer_cls = Adafactor if self.args.adafactor else AdamW\n if self.args.adafactor:\n optimizer_cls = Adafactor\n optimizer_kwargs = {\"scale_parameter\": False, \"relative_step\": False}\n else:\n optimizer_cls = AdamW\n optimizer_kwargs = {\n \"betas\": (self.args.adam_beta1, self.args.adam_beta2),\n \"eps\": self.args.adam_epsilon,\n }\n optimizer_kwargs[\"lr\"] = self.args.learning_rate\n if self.sharded_ddp == ShardedDDPOption.SIMPLE:\n self.optimizer = OSS(\n params=optimizer_grouped_parameters,\n optim=optimizer_cls,\n **optimizer_kwargs,\n )\n else:\n self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)\n\n if is_sagemaker_mp_enabled():\n self.optimizer = smp.DistributedOptimizer(self.optimizer)\n\n def create_scheduler(self, num_training_steps: int):\n \"\"\"\n Setup the scheduler. The optimizer of the trainer must have been set up before this method is called.\n\n Args:\n num_training_steps (int): The number of training steps to do.\n \"\"\"\n if self.lr_scheduler is None:\n self.lr_scheduler = get_scheduler(\n self.args.lr_scheduler_type,\n self.optimizer,\n num_warmup_steps=self.args.get_warmup_steps(num_training_steps),\n num_training_steps=num_training_steps,\n )\n\n def num_examples(self, dataloader: DataLoader) -> int:\n \"\"\"\n Helper to get number of samples in a :class:`~torch.utils.data.DataLoader` by accessing its dataset.\n\n Will raise an exception if the underlying dataset does not implement method :obj:`__len__`\n \"\"\"\n return len(dataloader.dataset)\n\n def _hp_search_setup(self, trial: Union[\"optuna.Trial\", Dict[str, Any]]):\n \"\"\"HP search setup code\"\"\"\n self._trial = trial\n\n if self.hp_search_backend is None or trial is None:\n return\n if self.hp_search_backend == HPSearchBackend.OPTUNA:\n params = self.hp_space(trial)\n elif self.hp_search_backend == HPSearchBackend.RAY:\n params = trial\n params.pop(\"wandb\", None)\n\n for key, value in params.items():\n if not hasattr(self.args, key):\n logger.warn(\n f\"Trying to set {key} in the hyperparameter search but there is no corresponding field in `TrainingArguments`.\"\n )\n continue\n old_attr = getattr(self.args, key, None)\n # Casting value to the proper type\n if old_attr is not None:\n value = type(old_attr)(value)\n setattr(self.args, key, value)\n if self.hp_search_backend == HPSearchBackend.OPTUNA:\n logger.info(\"Trial:\", trial.params)\n if self.args.deepspeed:\n # Rebuild the deepspeed config to reflect the updated training parameters\n from transformers.deepspeed import HfDeepSpeedConfig\n\n self.args.hf_deepspeed_config = HfDeepSpeedConfig(self.args)\n\n def _report_to_hp_search(\n self, trial: Union[\"optuna.Trial\", Dict[str, Any]], epoch: int, metrics: Dict[str, float]\n ):\n if self.hp_search_backend is None or trial is None:\n return\n self.objective = self.compute_objective(metrics.copy())\n if self.hp_search_backend == HPSearchBackend.OPTUNA:\n import optuna\n\n trial.report(self.objective, epoch)\n if trial.should_prune():\n raise optuna.TrialPruned()\n elif self.hp_search_backend == HPSearchBackend.RAY:\n from ray import tune\n\n if self.control.should_save:\n self._tune_save_checkpoint()\n tune.report(objective=self.objective, **metrics)\n\n def _tune_save_checkpoint(self):\n from ray import tune\n\n if not self.use_tune_checkpoints:\n return\n with tune.checkpoint_dir(step=self.state.global_step) as checkpoint_dir:\n output_dir = os.path.join(checkpoint_dir, f\"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}\")\n self.save_model(output_dir)\n if self.args.should_save:\n self.state.save_to_json(os.path.join(output_dir, \"trainer_state.json\"))\n torch.save(self.optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\n torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n\n def call_model_init(self, trial=None):\n model_init_argcount = number_of_arguments(self.model_init)\n if model_init_argcount == 0:\n model = self.model_init()\n elif model_init_argcount == 1:\n model = self.model_init(trial)\n else:\n raise RuntimeError(\"model_init should have 0 or 1 argument.\")\n\n if model is None:\n raise RuntimeError(\"model_init should not return None.\")\n\n return model\n\n def _wrap_model(self, model, training=True):\n if is_sagemaker_mp_enabled():\n # Wrapping the base model twice in a DistributedModel will raise an error.\n if isinstance(self.model_wrapped, smp.model.DistributedModel):\n return self.model_wrapped\n return smp.DistributedModel(model, backward_passes_per_step=self.args.gradient_accumulation_steps)\n\n # already initialized its own DDP and AMP\n if self.deepspeed:\n return self.deepspeed\n\n # train/eval could be run multiple-times - if already wrapped, don't re-wrap it again\n if unwrap_model(model) is not model:\n return model\n\n # Mixed precision training with apex (torch < 1.6)\n if self.use_apex and training:\n model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level)\n\n # Multi-gpu training (should be after apex fp16 initialization)\n if self.args.n_gpu > 1:\n model = nn.DataParallel(model)\n\n # Note: in torch.distributed mode, there's no point in wrapping the model\n # inside a DistributedDataParallel as we'll be under `no_grad` anyways.\n if not training:\n return model\n\n # Distributed training (should be after apex fp16 initialization)\n if self.sharded_ddp is not None:\n # Sharded DDP!\n if self.sharded_ddp == ShardedDDPOption.SIMPLE:\n model = ShardedDDP(model, self.optimizer)\n else:\n mixed_precision = self.args.fp16\n cpu_offload = ShardedDDPOption.OFFLOAD in self.args.sharded_ddp\n zero_3 = self.sharded_ddp == ShardedDDPOption.ZERO_DP_3\n # XXX: Breaking the self.model convention but I see no way around it for now.\n if ShardedDDPOption.AUTO_WRAP in self.args.sharded_ddp:\n model = auto_wrap(model)\n self.model = model = FullyShardedDDP(\n model,\n mixed_precision=mixed_precision,\n reshard_after_forward=zero_3,\n cpu_offload=cpu_offload,\n ).to(self.args.device)\n\n elif is_sagemaker_dp_enabled():\n model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False)\n elif self.args.local_rank != -1:\n if self.args.ddp_find_unused_parameters is not None:\n find_unused_parameters = self.args.ddp_find_unused_parameters\n elif isinstance(model, PreTrainedModel):\n # find_unused_parameters breaks checkpointing as per\n # https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021\n find_unused_parameters = not getattr(model.config, \"gradient_checkpointing\", False)\n else:\n find_unused_parameters = True\n model = nn.parallel.DistributedDataParallel(\n model,\n device_ids=[self.args.local_rank],\n output_device=self.args.local_rank,\n find_unused_parameters=find_unused_parameters,\n )\n\n return model\n\n def train(\n self,\n resume_from_checkpoint: Optional[Union[str, bool]] = None,\n trial: Union[\"optuna.Trial\", Dict[str, Any]] = None,\n ignore_keys_for_eval: Optional[List[str]] = None,\n **kwargs,\n ):\n \"\"\"\n Main training entry point.\n\n Args:\n resume_from_checkpoint (:obj:`str` or :obj:`bool`, `optional`):\n If a :obj:`str`, local path to a saved checkpoint as saved by a previous instance of\n :class:`~transformers.Trainer`. If a :obj:`bool` and equals `True`, load the last checkpoint in\n `args.output_dir` as saved by a previous instance of :class:`~transformers.Trainer`. If present,\n training will resume from the model/optimizer/scheduler states loaded here.\n trial (:obj:`optuna.Trial` or :obj:`Dict[str, Any]`, `optional`):\n The trial run or the hyperparameter dictionary for hyperparameter search.\n ignore_keys_for_eval (:obj:`List[str]`, `optional`)\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions for evaluation during the training.\n kwargs:\n Additional keyword arguments used to hide deprecated arguments\n \"\"\"\n resume_from_checkpoint = None if not resume_from_checkpoint else resume_from_checkpoint\n\n # memory metrics - must set up as early as possible\n self._memory_tracker.start()\n\n args = self.args\n\n self.is_in_train = True\n\n # do_train is not a reliable argument, as it might not be set and .train() still called, so\n # the following is a workaround:\n if args.fp16_full_eval and not args.do_train:\n self._move_model_to_device(self.model, args.device)\n\n if \"model_path\" in kwargs:\n resume_from_checkpoint = kwargs.pop(\"model_path\")\n warnings.warn(\n \"`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` \"\n \"instead.\",\n FutureWarning,\n )\n if len(kwargs) > 0:\n raise TypeError(f\"train() received got unexpected keyword arguments: {', '.join(list(kwargs.keys()))}.\")\n # This might change the seed so needs to run first.\n self._hp_search_setup(trial)\n\n # Model re-init\n model_reloaded = False\n if self.model_init is not None:\n # Seed must be set before instantiating the model when using model_init.\n set_seed(args.seed)\n self.model = self.call_model_init(trial)\n model_reloaded = True\n # Reinitializes optimizer and scheduler\n self.optimizer, self.lr_scheduler = None, None\n\n # Load potential model checkpoint\n if isinstance(resume_from_checkpoint, bool) and resume_from_checkpoint:\n resume_from_checkpoint = get_last_checkpoint(args.output_dir)\n if resume_from_checkpoint is None:\n raise ValueError(f\"No valid checkpoint found in output directory ({args.output_dir})\")\n\n if resume_from_checkpoint is not None:\n if not os.path.isfile(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)):\n raise ValueError(f\"Can't find a valid checkpoint at {resume_from_checkpoint}\")\n\n logger.info(f\"Loading model from {resume_from_checkpoint}).\")\n\n if os.path.isfile(os.path.join(resume_from_checkpoint, CONFIG_NAME)):\n config = PretrainedConfig.from_json_file(os.path.join(resume_from_checkpoint, CONFIG_NAME))\n checkpoint_version = config.transformers_version\n if checkpoint_version is not None and checkpoint_version != __version__:\n logger.warn(\n f\"You are resuming training from a checkpoint trained with {checkpoint_version} of \"\n f\"Transformers but your current version is {__version__}. This is not recommended and could \"\n \"yield to errors or unwanted behaviors.\"\n )\n\n if args.deepspeed:\n # will be resumed in deepspeed_init\n pass\n else:\n # We load the model state dict on the CPU to avoid an OOM error.\n state_dict = torch.load(os.path.join(resume_from_checkpoint, WEIGHTS_NAME), map_location=\"cpu\")\n # If the model is on the GPU, it still works!\n self._load_state_dict_in_model(state_dict)\n\n # release memory\n del state_dict\n\n # If model was re-initialized, put it on the right device and update self.model_wrapped\n if model_reloaded:\n if self.place_model_on_device:\n self._move_model_to_device(self.model, args.device)\n self.model_wrapped = self.model\n\n # Keeping track whether we can can len() on the dataset or not\n train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized)\n\n # Data loader and number of training steps\n train_dataloader = self.get_train_dataloader()\n\n # Setting up training control variables:\n # number of training epochs: num_train_epochs\n # number of training steps per epoch: num_update_steps_per_epoch\n # total number of training steps to execute: max_steps\n total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size\n if train_dataset_is_sized:\n num_update_steps_per_epoch = len(train_dataloader) // args.gradient_accumulation_steps\n num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)\n if args.max_steps > 0:\n max_steps = args.max_steps\n num_train_epochs = args.max_steps // num_update_steps_per_epoch + int(\n args.max_steps % num_update_steps_per_epoch > 0\n )\n # May be slightly incorrect if the last batch in the training datalaoder has a smaller size but it's\n # the best we can do.\n num_train_samples = args.max_steps * total_train_batch_size\n else:\n max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch)\n num_train_epochs = math.ceil(args.num_train_epochs)\n num_train_samples = len(self.train_dataset) * args.num_train_epochs\n else:\n # see __init__. max_steps is set when the dataset has no __len__\n max_steps = args.max_steps\n # Setting a very large number of epochs so we go as many times as necessary over the iterator.\n num_train_epochs = sys.maxsize\n num_update_steps_per_epoch = max_steps\n num_train_samples = args.max_steps * total_train_batch_size\n\n if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug:\n if self.args.n_gpu > 1:\n # nn.DataParallel(model) replicates the model, creating new variables and module\n # references registered here no longer work on other gpus, breaking the module\n raise ValueError(\n \"Currently --debug underflow_overflow is not supported under DP. Please use DDP (torch.distributed.launch).\"\n )\n else:\n debug_overflow = DebugUnderflowOverflow(self.model) # noqa\n\n delay_optimizer_creation = self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE\n if args.deepspeed:\n deepspeed_engine, optimizer, lr_scheduler = deepspeed_init(\n self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint\n )\n self.model = deepspeed_engine.module\n self.model_wrapped = deepspeed_engine\n self.deepspeed = deepspeed_engine\n self.optimizer = optimizer\n self.lr_scheduler = lr_scheduler\n elif not delay_optimizer_creation:\n self.create_optimizer_and_scheduler(num_training_steps=max_steps)\n\n self.state = TrainerState()\n self.state.is_hyper_param_search = trial is not None\n\n model = self._wrap_model(self.model_wrapped)\n\n # for the rest of this function `model` is the outside model, whether it was wrapped or not\n if model is not self.model:\n self.model_wrapped = model\n\n if delay_optimizer_creation:\n self.create_optimizer_and_scheduler(num_training_steps=max_steps)\n\n # Check if saved optimizer or scheduler states exist\n self._load_optimizer_and_scheduler(resume_from_checkpoint)\n\n # important: at this point:\n # self.model is the Transformers Model\n # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc.\n\n # Train!\n num_examples = (\n self.num_examples(train_dataloader) if train_dataset_is_sized else total_train_batch_size * args.max_steps\n )\n\n logger.info(\"***** Running training *****\")\n logger.info(f\" Num examples = {num_examples}\")\n logger.info(f\" Num Epochs = {num_train_epochs}\")\n logger.info(f\" Instantaneous batch size per device = {args.per_device_train_batch_size}\")\n logger.info(f\" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}\")\n logger.info(f\" Gradient Accumulation steps = {args.gradient_accumulation_steps}\")\n logger.info(f\" Total optimization steps = {max_steps}\")\n\n self.state.epoch = 0\n start_time = time.time()\n epochs_trained = 0\n steps_trained_in_current_epoch = 0\n steps_trained_progress_bar = None\n\n # Check if continuing training from a checkpoint\n if resume_from_checkpoint is not None and os.path.isfile(\n os.path.join(resume_from_checkpoint, \"trainer_state.json\")\n ):\n self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, \"trainer_state.json\"))\n epochs_trained = self.state.global_step // num_update_steps_per_epoch\n if not args.ignore_data_skip:\n steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch)\n steps_trained_in_current_epoch *= args.gradient_accumulation_steps\n else:\n steps_trained_in_current_epoch = 0\n\n logger.info(\" Continuing training from checkpoint, will skip to saved global_step\")\n logger.info(f\" Continuing training from epoch {epochs_trained}\")\n logger.info(f\" Continuing training from global step {self.state.global_step}\")\n if not args.ignore_data_skip:\n logger.info(\n f\" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} \"\n \"batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` \"\n \"flag to your launch command, but you will resume the training on data already seen by your model.\"\n )\n if self.is_local_process_zero() and not args.disable_tqdm:\n steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch)\n steps_trained_progress_bar.set_description(\"Skipping the first batches\")\n\n # Update the references\n self.callback_handler.model = self.model\n self.callback_handler.optimizer = self.optimizer\n self.callback_handler.lr_scheduler = self.lr_scheduler\n self.callback_handler.train_dataloader = train_dataloader\n self.state.trial_name = self.hp_name(trial) if self.hp_name is not None else None\n self.state.trial_params = hp_params(trial) if trial is not None else None\n # This should be the same if the state has been saved but in case the training arguments changed, it's safer\n # to set this after the load.\n self.state.max_steps = max_steps\n self.state.num_train_epochs = num_train_epochs\n self.state.is_local_process_zero = self.is_local_process_zero()\n self.state.is_world_process_zero = self.is_world_process_zero()\n\n # tr_loss is a tensor to avoid synchronization of TPUs through .item()\n tr_loss = torch.tensor(0.0).to(args.device)\n # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses\n self._total_loss_scalar = 0.0\n self._globalstep_last_logged = self.state.global_step\n model.zero_grad()\n\n self.control = self.callback_handler.on_train_begin(args, self.state, self.control)\n\n # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.\n if not args.ignore_data_skip:\n for epoch in range(epochs_trained):\n # We just need to begin an iteration to create the randomization of the sampler.\n for _ in train_dataloader:\n break\n\n for epoch in range(epochs_trained, num_train_epochs):\n if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler):\n train_dataloader.sampler.set_epoch(epoch)\n elif isinstance(train_dataloader.dataset, IterableDatasetShard):\n train_dataloader.dataset.set_epoch(epoch)\n\n if is_torch_tpu_available():\n parallel_loader = pl.ParallelLoader(train_dataloader, [args.device]).per_device_loader(args.device)\n epoch_iterator = parallel_loader\n else:\n epoch_iterator = train_dataloader\n\n # Reset the past mems state at the beginning of each epoch if necessary.\n if args.past_index >= 0:\n self._past = None\n\n steps_in_epoch = (\n len(epoch_iterator) if train_dataset_is_sized else args.max_steps * args.gradient_accumulation_steps\n )\n self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control)\n\n for step, inputs in enumerate(epoch_iterator):\n\n # Skip past any already trained steps if resuming training\n if steps_trained_in_current_epoch > 0:\n steps_trained_in_current_epoch -= 1\n if steps_trained_progress_bar is not None:\n steps_trained_progress_bar.update(1)\n if steps_trained_in_current_epoch == 0:\n self._load_rng_state(resume_from_checkpoint)\n continue\n elif steps_trained_progress_bar is not None:\n steps_trained_progress_bar.close()\n steps_trained_progress_bar = None\n\n if step % args.gradient_accumulation_steps == 0:\n self.control = self.callback_handler.on_step_begin(args, self.state, self.control)\n\n if (\n ((step + 1) % args.gradient_accumulation_steps != 0)\n and args.local_rank != -1\n and args._no_sync_in_gradient_accumulation\n ):\n # Avoid unnecessary DDP synchronization since there will be no backward pass on this example.\n with model.no_sync():\n tr_loss += self.training_step(model, inputs)\n else:\n tr_loss += self.training_step(model, inputs)\n self.current_flos += float(self.floating_point_ops(inputs))\n\n # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps\n if self.deepspeed:\n self.deepspeed.step()\n\n if (step + 1) % args.gradient_accumulation_steps == 0 or (\n # last step in epoch but step is always smaller than gradient_accumulation_steps\n steps_in_epoch <= args.gradient_accumulation_steps\n and (step + 1) == steps_in_epoch\n ):\n # Gradient clipping\n if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed:\n # deepspeed does its own clipping\n\n if self.use_amp:\n # AMP: gradients need unscaling\n self.scaler.unscale_(self.optimizer)\n\n if hasattr(self.optimizer, \"clip_grad_norm\"):\n # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping\n self.optimizer.clip_grad_norm(args.max_grad_norm)\n elif hasattr(model, \"clip_grad_norm_\"):\n # Some models (like FullyShardedDDP) have a specific way to do gradient clipping\n model.clip_grad_norm_(args.max_grad_norm)\n else:\n # Revert to normal clipping otherwise, handling Apex or full precision\n nn.utils.clip_grad_norm_(\n amp.master_params(self.optimizer) if self.use_apex else model.parameters(),\n args.max_grad_norm,\n )\n\n # Optimizer step\n optimizer_was_run = True\n if self.deepspeed:\n pass # called outside the loop\n elif is_torch_tpu_available():\n xm.optimizer_step(self.optimizer)\n elif self.use_amp:\n scale_before = self.scaler.get_scale()\n self.scaler.step(self.optimizer)\n self.scaler.update()\n scale_after = self.scaler.get_scale()\n optimizer_was_run = scale_before <= scale_after\n else:\n self.optimizer.step()\n\n if optimizer_was_run and not self.deepspeed:\n self.lr_scheduler.step()\n\n model.zero_grad()\n self.state.global_step += 1\n self.state.epoch = epoch + (step + 1) / steps_in_epoch\n self.control = self.callback_handler.on_step_end(args, self.state, self.control)\n\n self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval)\n else:\n self.control = self.callback_handler.on_substep_end(args, self.state, self.control)\n\n if self.control.should_epoch_stop or self.control.should_training_stop:\n break\n\n self.control = self.callback_handler.on_epoch_end(args, self.state, self.control)\n self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval)\n\n if DebugOption.TPU_METRICS_DEBUG in self.args.debug:\n if is_torch_tpu_available():\n # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)\n xm.master_print(met.metrics_report())\n else:\n logger.warning(\n \"You enabled PyTorch/XLA debug metrics but you don't have a TPU \"\n \"configured. Check your training configuration if this is unexpected.\"\n )\n if self.control.should_training_stop:\n break\n\n if args.past_index and hasattr(self, \"_past\"):\n # Clean the state at the end of training\n delattr(self, \"_past\")\n\n logger.info(\"\\n\\nTraining completed. Do not forget to share your model on huggingface.co/models =)\\n\\n\")\n if args.load_best_model_at_end and self.state.best_model_checkpoint is not None:\n # Wait for everyone to get here so we are sur the model has been saved by process 0.\n if is_torch_tpu_available():\n xm.rendezvous(\"load_best_model_at_end\")\n elif args.local_rank != -1:\n dist.barrier()\n\n logger.info(\n f\"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric}).\"\n )\n\n best_model_path = os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME)\n if os.path.exists(best_model_path):\n # We load the model state dict on the CPU to avoid an OOM error.\n state_dict = torch.load(best_model_path, map_location=\"cpu\")\n # If the model is on the GPU, it still works!\n self._load_state_dict_in_model(state_dict)\n else:\n logger.warn(\n f\"Could not locate the best model at {best_model_path}, if you are running a distributed training \"\n \"on multiple nodes, you should activate `--save_on_each_node`.\"\n )\n\n if self.deepspeed:\n self.deepspeed.load_checkpoint(\n self.state.best_model_checkpoint, load_optimizer_states=False, load_lr_scheduler_states=False\n )\n\n # add remaining tr_loss\n self._total_loss_scalar += tr_loss.item()\n train_loss = self._total_loss_scalar / self.state.global_step\n\n metrics = speed_metrics(\"train\", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps)\n self.store_flos()\n metrics[\"total_flos\"] = self.state.total_flos\n metrics[\"train_loss\"] = train_loss\n\n self.is_in_train = False\n\n self._memory_tracker.stop_and_update_metrics(metrics)\n\n self.log(metrics)\n\n self.control = self.callback_handler.on_train_end(args, self.state, self.control)\n\n return TrainOutput(self.state.global_step, train_loss, metrics)\n\n def _load_state_dict_in_model(self, state_dict):\n load_result = self.model.load_state_dict(state_dict, strict=False)\n\n if len(load_result.missing_keys) != 0:\n if set(load_result.missing_keys) == set(self.model._keys_to_ignore_on_save):\n self.model.tie_weights()\n else:\n logger.warn(f\"There were missing keys in the checkpoint model loaded: {load_result.missing_keys}.\")\n if len(load_result.unexpected_keys) != 0:\n logger.warn(f\"There were unexpected keys in the checkpoint model loaded: {load_result.unexpected_keys}.\")\n\n def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch, ignore_keys_for_eval):\n if self.control.should_log:\n logs: Dict[str, float] = {}\n tr_loss_scalar = tr_loss.item()\n # reset tr_loss to zero\n tr_loss -= tr_loss\n\n logs[\"loss\"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)\n logs[\"learning_rate\"] = self._get_learning_rate()\n\n self._total_loss_scalar += tr_loss_scalar\n self._globalstep_last_logged = self.state.global_step\n self.store_flos()\n\n self.log(logs)\n\n metrics = None\n if self.control.should_evaluate:\n metrics = self.evaluate(ignore_keys=ignore_keys_for_eval)\n self._report_to_hp_search(trial, epoch, metrics)\n\n if self.control.should_save:\n self._save_checkpoint(model, trial, metrics=metrics)\n self.control = self.callback_handler.on_save(self.args, self.state, self.control)\n\n def _load_rng_state(self, checkpoint):\n # Load RNG states from `checkpoint`\n if checkpoint is None:\n return\n\n local_rank = xm.get_local_ordinal() if is_torch_tpu_available() else self.args.local_rank\n if local_rank != -1:\n rng_file = os.path.join(checkpoint, f\"rng_state_{local_rank}.pth\")\n if not os.path.isfile(os.path.join(checkpoint, rng_file)):\n logger.info(\n f\"Didn't find an RNG file for process {local_rank}, if you are resuming a training that \"\n \"wasn't launched in a distributed fashion, reproducibility is not guaranteed.\"\n )\n return\n else:\n rng_file = os.path.join(checkpoint, \"rng_state.pth\")\n if not os.path.isfile(os.path.join(checkpoint, rng_file)):\n logger.info(\n \"Didn't find an RNG file, if you are resuming a training that was launched in a distributed \"\n \"fashion, reproducibility is not guaranteed.\"\n )\n return\n\n checkpoint_rng_state = torch.load(rng_file)\n random.setstate(checkpoint_rng_state[\"python\"])\n np.random.set_state(checkpoint_rng_state[\"numpy\"])\n torch.random.set_rng_state(checkpoint_rng_state[\"cpu\"])\n if torch.cuda.is_available():\n if self.args.local_rank != -1:\n torch.cuda.random.set_rng_state(checkpoint_rng_state[\"cuda\"])\n else:\n torch.cuda.random.set_rng_state_all(checkpoint_rng_state[\"cuda\"])\n if is_torch_tpu_available():\n xm.set_rng_state(checkpoint_rng_state[\"xla\"])\n\n def _save_checkpoint(self, model, trial, metrics=None):\n # In all cases, including ddp/dp/deepspeed, self.model is always a reference to the model we\n # want to save except FullyShardedDDP.\n # assert unwrap_model(model) is self.model, \"internal model should be a reference to self.model\"\n\n # Save model checkpoint\n checkpoint_folder = f\"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}\"\n\n if self.hp_search_backend is not None and trial is not None:\n if self.hp_search_backend == HPSearchBackend.OPTUNA:\n run_id = trial.number\n else:\n from ray import tune\n\n run_id = tune.get_trial_id()\n run_name = self.hp_name(trial) if self.hp_name is not None else f\"run-{run_id}\"\n run_dir = os.path.join(self.args.output_dir, run_name)\n else:\n run_dir = self.args.output_dir\n self.store_flos()\n\n output_dir = os.path.join(run_dir, checkpoint_folder)\n self.save_model(output_dir)\n if self.deepspeed:\n # under zero3 model file itself doesn't get saved since it's bogus! Unless deepspeed\n # config `stage3_gather_fp16_weights_on_model_save` is True\n self.deepspeed.save_checkpoint(output_dir)\n\n # Save optimizer and scheduler\n if self.sharded_ddp == ShardedDDPOption.SIMPLE:\n self.optimizer.consolidate_state_dict()\n\n if is_torch_tpu_available():\n xm.rendezvous(\"saving_optimizer_states\")\n xm.save(self.optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\n with warnings.catch_warnings(record=True) as caught_warnings:\n xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n reissue_pt_warnings(caught_warnings)\n elif is_sagemaker_mp_enabled():\n if smp.dp_rank() == 0:\n # Consolidate the state dict on all processed of dp_rank 0\n opt_state_dict = self.optimizer.state_dict()\n # Save it and the scheduler on the main process\n if self.args.should_save:\n torch.save(opt_state_dict, os.path.join(output_dir, \"optimizer.pt\"))\n with warnings.catch_warnings(record=True) as caught_warnings:\n torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n reissue_pt_warnings(caught_warnings)\n if self.use_amp:\n torch.save(self.scaler.state_dict(), os.path.join(output_dir, \"scaler.pt\"))\n elif self.args.should_save and not self.deepspeed:\n # deepspeed.save_checkpoint above saves model/optim/sched\n torch.save(self.optimizer.state_dict(), os.path.join(output_dir, \"optimizer.pt\"))\n with warnings.catch_warnings(record=True) as caught_warnings:\n torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, \"scheduler.pt\"))\n reissue_pt_warnings(caught_warnings)\n if self.use_amp:\n torch.save(self.scaler.state_dict(), os.path.join(output_dir, \"scaler.pt\"))\n\n # Determine the new best metric / best model checkpoint\n if metrics is not None and self.args.metric_for_best_model is not None:\n metric_to_check = self.args.metric_for_best_model\n if not metric_to_check.startswith(\"eval_\"):\n metric_to_check = f\"eval_{metric_to_check}\"\n metric_value = metrics[metric_to_check]\n\n operator = np.greater if self.args.greater_is_better else np.less\n if (\n self.state.best_metric is None\n or self.state.best_model_checkpoint is None\n or operator(metric_value, self.state.best_metric)\n ):\n self.state.best_metric = metric_value\n self.state.best_model_checkpoint = output_dir\n\n # Save the Trainer state\n if self.args.should_save:\n self.state.save_to_json(os.path.join(output_dir, \"trainer_state.json\"))\n\n # Save RNG state in non-distributed training\n rng_states = {\n \"python\": random.getstate(),\n \"numpy\": np.random.get_state(),\n \"cpu\": torch.random.get_rng_state(),\n }\n if torch.cuda.is_available():\n if self.args.local_rank == -1:\n # In non distributed, we save the global CUDA RNG state (will take care of DataParallel)\n rng_states[\"cuda\"] = torch.cuda.random.get_rng_state_all()\n else:\n rng_states[\"cuda\"] = torch.cuda.random.get_rng_state()\n\n if is_torch_tpu_available():\n rng_states[\"xla\"] = xm.get_rng_state()\n\n # A process can arrive here before the process 0 has a chance to save the model, in which case output_dir may\n # not yet exist.\n os.makedirs(output_dir, exist_ok=True)\n local_rank = xm.get_local_ordinal() if is_torch_tpu_available() else self.args.local_rank\n if local_rank == -1:\n torch.save(rng_states, os.path.join(output_dir, \"rng_state.pth\"))\n else:\n torch.save(rng_states, os.path.join(output_dir, f\"rng_state_{local_rank}.pth\"))\n\n # Maybe delete some older checkpoints.\n if self.args.should_save:\n self._rotate_checkpoints(use_mtime=True, output_dir=run_dir)\n\n def _load_optimizer_and_scheduler(self, checkpoint):\n \"\"\"If optimizer and scheduler states exist, load them.\"\"\"\n if checkpoint is None:\n return\n\n if self.deepspeed:\n # deepspeed loads optimizer/lr_scheduler together with the model in deepspeed_init\n return\n\n if os.path.isfile(os.path.join(checkpoint, \"optimizer.pt\")) and os.path.isfile(\n os.path.join(checkpoint, \"scheduler.pt\")\n ):\n # Load in optimizer and scheduler states\n if is_torch_tpu_available():\n # On TPU we have to take some extra precautions to properly load the states on the right device.\n optimizer_state = torch.load(os.path.join(checkpoint, \"optimizer.pt\"), map_location=\"cpu\")\n with warnings.catch_warnings(record=True) as caught_warnings:\n lr_scheduler_state = torch.load(os.path.join(checkpoint, \"scheduler.pt\"), map_location=\"cpu\")\n reissue_pt_warnings(caught_warnings)\n\n xm.send_cpu_data_to_device(optimizer_state, self.args.device)\n xm.send_cpu_data_to_device(lr_scheduler_state, self.args.device)\n\n self.optimizer.load_state_dict(optimizer_state)\n self.lr_scheduler.load_state_dict(lr_scheduler_state)\n else:\n map_location = \"cpu\" if is_sagemaker_mp_enabled() else self.args.device\n self.optimizer.load_state_dict(\n torch.load(os.path.join(checkpoint, \"optimizer.pt\"), map_location=map_location)\n )\n with warnings.catch_warnings(record=True) as caught_warnings:\n self.lr_scheduler.load_state_dict(torch.load(os.path.join(checkpoint, \"scheduler.pt\")))\n reissue_pt_warnings(caught_warnings)\n if self.use_amp and os.path.isfile(os.path.join(checkpoint, \"scaler.pt\")):\n self.scaler.load_state_dict(torch.load(os.path.join(checkpoint, \"scaler.pt\")))\n\n def hyperparameter_search(\n self,\n hp_space: Optional[Callable[[\"optuna.Trial\"], Dict[str, float]]] = None,\n compute_objective: Optional[Callable[[Dict[str, float]], float]] = None,\n n_trials: int = 20,\n direction: str = \"minimize\",\n backend: Optional[Union[\"str\", HPSearchBackend]] = None,\n hp_name: Optional[Callable[[\"optuna.Trial\"], str]] = None,\n **kwargs,\n ) -> BestRun:\n \"\"\"\n Launch an hyperparameter search using ``optuna`` or ``Ray Tune``. The optimized quantity is determined by\n :obj:`compute_objective`, which defaults to a function returning the evaluation loss when no metric is\n provided, the sum of all metrics otherwise.\n\n .. warning::\n\n To use this method, you need to have provided a ``model_init`` when initializing your\n :class:`~transformers.Trainer`: we need to reinitialize the model at each new run. This is incompatible\n with the ``optimizers`` argument, so you need to subclass :class:`~transformers.Trainer` and override the\n method :meth:`~transformers.Trainer.create_optimizer_and_scheduler` for custom optimizer/scheduler.\n\n Args:\n hp_space (:obj:`Callable[[\"optuna.Trial\"], Dict[str, float]]`, `optional`):\n A function that defines the hyperparameter search space. Will default to\n :func:`~transformers.trainer_utils.default_hp_space_optuna` or\n :func:`~transformers.trainer_utils.default_hp_space_ray` depending on your backend.\n compute_objective (:obj:`Callable[[Dict[str, float]], float]`, `optional`):\n A function computing the objective to minimize or maximize from the metrics returned by the\n :obj:`evaluate` method. Will default to :func:`~transformers.trainer_utils.default_compute_objective`.\n n_trials (:obj:`int`, `optional`, defaults to 100):\n The number of trial runs to test.\n direction(:obj:`str`, `optional`, defaults to :obj:`\"minimize\"`):\n Whether to optimize greater or lower objects. Can be :obj:`\"minimize\"` or :obj:`\"maximize\"`, you should\n pick :obj:`\"minimize\"` when optimizing the validation loss, :obj:`\"maximize\"` when optimizing one or\n several metrics.\n backend(:obj:`str` or :class:`~transformers.training_utils.HPSearchBackend`, `optional`):\n The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which\n one is installed. If both are installed, will default to optuna.\n kwargs:\n Additional keyword arguments passed along to :obj:`optuna.create_study` or :obj:`ray.tune.run`. For\n more information see:\n\n - the documentation of `optuna.create_study\n <https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html>`__\n - the documentation of `tune.run\n <https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run>`__\n\n Returns:\n :class:`transformers.trainer_utils.BestRun`: All the information about the best run.\n \"\"\"\n if backend is None:\n backend = default_hp_search_backend()\n if backend is None:\n raise RuntimeError(\n \"At least one of optuna or ray should be installed. \"\n \"To install optuna run `pip install optuna`.\"\n \"To install ray run `pip install ray[tune]`.\"\n )\n backend = HPSearchBackend(backend)\n if backend == HPSearchBackend.OPTUNA and not is_optuna_available():\n raise RuntimeError(\"You picked the optuna backend, but it is not installed. Use `pip install optuna`.\")\n if backend == HPSearchBackend.RAY and not is_ray_tune_available():\n raise RuntimeError(\n \"You picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`.\"\n )\n self.hp_search_backend = backend\n if self.model_init is None:\n raise RuntimeError(\n \"To use hyperparameter search, you need to pass your model through a model_init function.\"\n )\n\n self.hp_space = default_hp_space[backend] if hp_space is None else hp_space\n self.hp_name = hp_name\n self.compute_objective = default_compute_objective if compute_objective is None else compute_objective\n\n run_hp_search = run_hp_search_optuna if backend == HPSearchBackend.OPTUNA else run_hp_search_ray\n best_run = run_hp_search(self, n_trials, direction, **kwargs)\n\n self.hp_search_backend = None\n return best_run\n\n def log(self, logs: Dict[str, float]) -> None:\n \"\"\"\n Log :obj:`logs` on the various objects watching training.\n\n Subclass and override this method to inject custom behavior.\n\n Args:\n logs (:obj:`Dict[str, float]`):\n The values to log.\n \"\"\"\n if self.state.epoch is not None:\n logs[\"epoch\"] = round(self.state.epoch, 2)\n\n output = {**logs, **{\"step\": self.state.global_step}}\n self.state.log_history.append(output)\n self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs)\n\n def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]:\n \"\"\"\n Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and\n handling potential state.\n \"\"\"\n for k, v in inputs.items():\n if isinstance(v, torch.Tensor):\n kwargs = dict(device=self.args.device)\n if self.deepspeed and inputs[k].dtype != torch.int64:\n # NLP models inputs are int64 and those get adjusted to the right dtype of the\n # embedding. Other models such as wav2vec2's inputs are already float and thus\n # may need special handling to match the dtypes of the model\n kwargs.update(dict(dtype=self.args.hf_deepspeed_config.dtype()))\n\n inputs[k] = v.to(**kwargs)\n\n if self.args.past_index >= 0 and self._past is not None:\n inputs[\"mems\"] = self._past\n\n return inputs\n\n def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor:\n \"\"\"\n Perform a training step on a batch of inputs.\n\n Subclass and override to inject custom behavior.\n\n Args:\n model (:obj:`nn.Module`):\n The model to train.\n inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):\n The inputs and targets of the model.\n\n The dictionary will be unpacked before being fed to the model. Most models expect the targets under the\n argument :obj:`labels`. Check your model's documentation for all accepted arguments.\n\n Return:\n :obj:`torch.Tensor`: The tensor with training loss on this batch.\n \"\"\"\n model.train()\n inputs = self._prepare_inputs(inputs)\n\n if is_sagemaker_mp_enabled():\n scaler = self.scaler if self.use_amp else None\n loss_mb = smp_forward_backward(model, inputs, self.args.gradient_accumulation_steps, scaler=scaler)\n return loss_mb.reduce_mean().detach().to(self.args.device)\n\n if self.use_amp:\n with autocast():\n loss = self.compute_loss(model, inputs)\n else:\n loss = self.compute_loss(model, inputs)\n\n if self.args.n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu parallel training\n\n if self.args.gradient_accumulation_steps > 1 and not self.deepspeed:\n # deepspeed handles loss scaling by gradient_accumulation_steps in its `backward`\n loss = loss / self.args.gradient_accumulation_steps\n\n if self.use_amp:\n self.scaler.scale(loss).backward()\n elif self.use_apex:\n with amp.scale_loss(loss, self.optimizer) as scaled_loss:\n scaled_loss.backward()\n elif self.deepspeed:\n # loss gets scaled under gradient_accumulation_steps in deepspeed\n loss = self.deepspeed.backward(loss)\n else:\n loss.backward()\n\n return loss.detach()\n\n def compute_loss(self, model, inputs, return_outputs=False):\n \"\"\"\n How the loss is computed by Trainer. By default, all models return the loss in the first element.\n\n Subclass and override for custom behavior.\n \"\"\"\n if self.label_smoother is not None and \"labels\" in inputs:\n labels = inputs.pop(\"labels\")\n else:\n labels = None\n outputs = model(**inputs)\n # Save past state if it exists\n # TODO: this needs to be fixed and made cleaner later.\n if self.args.past_index >= 0:\n self._past = outputs[self.args.past_index]\n\n if labels is not None:\n loss = self.label_smoother(outputs, labels)\n else:\n # We don't use .loss here since the model may return tuples instead of ModelOutput.\n loss = outputs[\"loss\"] if isinstance(outputs, dict) else outputs[0]\n\n return (loss, outputs) if return_outputs else loss\n\n def is_local_process_zero(self) -> bool:\n \"\"\"\n Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several\n machines) main process.\n \"\"\"\n return self.args.local_process_index == 0\n\n def is_world_process_zero(self) -> bool:\n \"\"\"\n Whether or not this process is the global main process (when training in a distributed fashion on several\n machines, this is only going to be :obj:`True` for one process).\n \"\"\"\n # Special case for SageMaker ModelParallel since there process_index is dp_process_index, not the global\n # process index.\n if is_sagemaker_mp_enabled():\n return smp.rank() == 0\n else:\n return self.args.process_index == 0\n\n def save_model(self, output_dir: Optional[str] = None):\n \"\"\"\n Will save the model, so you can reload it using :obj:`from_pretrained()`.\n\n Will only save from the main process.\n \"\"\"\n\n if output_dir is None:\n output_dir = self.args.output_dir\n\n if is_torch_tpu_available():\n self._save_tpu(output_dir)\n elif is_sagemaker_mp_enabled():\n # Calling the state_dict needs to be done on the wrapped model and on all processes.\n state_dict = self.model_wrapped.state_dict()\n if self.args.should_save:\n self._save(output_dir, state_dict=state_dict)\n elif (\n ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp\n ):\n state_dict = self.model.state_dict()\n\n if self.args.should_save:\n self._save(output_dir, state_dict=state_dict)\n elif self.deepspeed:\n\n # this takes care of everything as long as we aren't under zero3\n if self.args.should_save:\n self._save(output_dir)\n\n if is_deepspeed_zero3_enabled():\n # It's too complicated to try to override different places where the weights dump gets\n # saved, so since under zero3 the file is bogus, simply delete it. The user should\n # either user deepspeed checkpoint to resume or to recover full weights use\n # zero_to_fp32.py stored in the checkpoint.\n if self.args.should_save:\n file = os.path.join(output_dir, WEIGHTS_NAME)\n if os.path.isfile(file):\n # logger.info(f\"deepspeed zero3: removing {file}, see zero_to_fp32.py to recover weights\")\n os.remove(file)\n\n # now save the real model if stage3_gather_fp16_weights_on_model_save=True\n # if false it will not be saved.\n # This must be called on all ranks\n self.deepspeed.save_fp16_model(output_dir, WEIGHTS_NAME)\n\n elif self.args.should_save:\n self._save(output_dir)\n\n def _save_tpu(self, output_dir: Optional[str] = None):\n output_dir = output_dir if output_dir is not None else self.args.output_dir\n logger.info(f\"Saving model checkpoint to {output_dir}\")\n\n if xm.is_master_ordinal():\n os.makedirs(output_dir, exist_ok=True)\n torch.save(self.args, os.path.join(output_dir, \"training_args.bin\"))\n\n # Save a trained model and configuration using `save_pretrained()`.\n # They can then be reloaded using `from_pretrained()`\n xm.rendezvous(\"saving_checkpoint\")\n if not isinstance(self.model, PreTrainedModel):\n if isinstance(unwrap_model(self.model), PreTrainedModel):\n unwrap_model(self.model).save_pretrained(\n output_dir,\n save_config=self.args.should_save,\n state_dict=self.model.state_dict(),\n save_function=xm.save,\n )\n else:\n logger.info(\"Trainer.model is not a `PreTrainedModel`, only saving its state dict.\")\n state_dict = self.model.state_dict()\n xm.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))\n else:\n self.model.save_pretrained(output_dir, save_config=self.args.should_save, save_function=xm.save)\n if self.tokenizer is not None and self.args.should_save:\n self.tokenizer.save_pretrained(output_dir)\n\n def _save(self, output_dir: Optional[str] = None, state_dict=None):\n # If we are executing this function, we are the process zero, so we don't check for that.\n output_dir = output_dir if output_dir is not None else self.args.output_dir\n os.makedirs(output_dir, exist_ok=True)\n logger.info(f\"Saving model checkpoint to {output_dir}\")\n # Save a trained model and configuration using `save_pretrained()`.\n # They can then be reloaded using `from_pretrained()`\n if not isinstance(self.model, PreTrainedModel):\n if isinstance(unwrap_model(self.model), PreTrainedModel):\n if state_dict is None:\n state_dict = self.model.state_dict()\n unwrap_model(self.model).save_pretrained(output_dir, state_dict=state_dict)\n else:\n logger.info(\"Trainer.model is not a `PreTrainedModel`, only saving its state dict.\")\n if state_dict is None:\n state_dict = self.model.state_dict()\n torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))\n else:\n self.model.save_pretrained(output_dir, state_dict=state_dict)\n if self.tokenizer is not None:\n self.tokenizer.save_pretrained(output_dir)\n\n # Good practice: save your training arguments together with the trained model\n torch.save(self.args, os.path.join(output_dir, \"training_args.bin\"))\n\n def store_flos(self):\n # Storing the number of floating-point operations that went into the model\n if self.args.local_rank != -1:\n self.state.total_flos += distributed_broadcast_scalars([self.current_flos]).sum().item()\n self.current_flos = 0\n else:\n self.state.total_flos += self.current_flos\n self.current_flos = 0\n\n def _sorted_checkpoints(\n self, output_dir=None, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False\n ) -> List[str]:\n ordering_and_checkpoint_path = []\n\n glob_checkpoints = [str(x) for x in Path(output_dir).glob(f\"{checkpoint_prefix}-*\")]\n\n for path in glob_checkpoints:\n if use_mtime:\n ordering_and_checkpoint_path.append((os.path.getmtime(path), path))\n else:\n regex_match = re.match(f\".*{checkpoint_prefix}-([0-9]+)\", path)\n if regex_match is not None and regex_match.groups() is not None:\n ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))\n\n checkpoints_sorted = sorted(ordering_and_checkpoint_path)\n checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]\n # Make sure we don't delete the best model.\n if self.state.best_model_checkpoint is not None:\n best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint)))\n for i in range(best_model_index, len(checkpoints_sorted) - 2):\n checkpoints_sorted[i], checkpoints_sorted[i + 1] = checkpoints_sorted[i + 1], checkpoints_sorted[i]\n return checkpoints_sorted\n\n def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None:\n if self.args.save_total_limit is None or self.args.save_total_limit <= 0:\n return\n\n # Check if we should delete older checkpoint(s)\n checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime, output_dir=output_dir)\n if len(checkpoints_sorted) <= self.args.save_total_limit:\n return\n\n # If save_total_limit=1 with load_best_model_at_end=True, we could end up deleting the last checkpoint, which\n # we don't do to allow resuming.\n save_total_limit = self.args.save_total_limit\n if (\n self.state.best_model_checkpoint is not None\n and self.args.save_total_limit == 1\n and checkpoints_sorted[-1] != self.state.best_model_checkpoint\n ):\n save_total_limit = 2\n\n number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - save_total_limit)\n checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]\n for checkpoint in checkpoints_to_be_deleted:\n logger.info(f\"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit\")\n shutil.rmtree(checkpoint)\n\n def evaluate(\n self,\n eval_dataset: Optional[Dataset] = None,\n ignore_keys: Optional[List[str]] = None,\n metric_key_prefix: str = \"eval\",\n ) -> Dict[str, float]:\n \"\"\"\n Run evaluation and returns metrics.\n\n The calling script will be responsible for providing a method to compute metrics, as they are task-dependent\n (pass it to the init :obj:`compute_metrics` argument).\n\n You can also subclass and override this method to inject custom behavior.\n\n Args:\n eval_dataset (:obj:`Dataset`, `optional`):\n Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`,\n columns not accepted by the ``model.forward()`` method are automatically removed. It must implement the\n :obj:`__len__` method.\n ignore_keys (:obj:`Lst[str]`, `optional`):\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions.\n metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`\"eval\"`):\n An optional prefix to be used as the metrics key prefix. For example the metrics \"bleu\" will be named\n \"eval_bleu\" if the prefix is \"eval\" (default)\n\n Returns:\n A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The\n dictionary also contains the epoch number which comes from the training state.\n \"\"\"\n # memory metrics - must set up as early as possible\n self._memory_tracker.start()\n\n eval_dataloader = self.get_eval_dataloader(eval_dataset)\n start_time = time.time()\n\n eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop\n output = eval_loop(\n eval_dataloader,\n description=\"Evaluation\",\n # No point gathering the predictions if there are no metrics, otherwise we defer to\n # self.args.prediction_loss_only\n prediction_loss_only=True if self.compute_metrics is None else None,\n ignore_keys=ignore_keys,\n metric_key_prefix=metric_key_prefix,\n )\n\n total_batch_size = self.args.eval_batch_size * self.args.world_size\n output.metrics.update(\n speed_metrics(\n metric_key_prefix,\n start_time,\n num_samples=output.num_samples,\n num_steps=math.ceil(output.num_samples / total_batch_size),\n )\n )\n\n self.log(output.metrics)\n\n if DebugOption.TPU_METRICS_DEBUG in self.args.debug:\n # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)\n xm.master_print(met.metrics_report())\n\n self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics)\n\n self._memory_tracker.stop_and_update_metrics(output.metrics)\n\n return output.metrics\n\n def predict(\n self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = \"test\"\n ) -> PredictionOutput:\n \"\"\"\n Run prediction and returns predictions and potential metrics.\n\n Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method\n will also return metrics, like in :obj:`evaluate()`.\n\n Args:\n test_dataset (:obj:`Dataset`):\n Dataset to run the predictions on. If it is an :obj:`datasets.Dataset`, columns not accepted by the\n ``model.forward()`` method are automatically removed. Has to implement the method :obj:`__len__`\n ignore_keys (:obj:`Lst[str]`, `optional`):\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions.\n metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`\"test\"`):\n An optional prefix to be used as the metrics key prefix. For example the metrics \"bleu\" will be named\n \"test_bleu\" if the prefix is \"test\" (default)\n\n .. note::\n\n If your predictions or labels have different sequence length (for instance because you're doing dynamic\n padding in a token classification task) the predictions will be padded (on the right) to allow for\n concatenation into one array. The padding index is -100.\n\n Returns: `NamedTuple` A namedtuple with the following keys:\n\n - predictions (:obj:`np.ndarray`): The predictions on :obj:`test_dataset`.\n - label_ids (:obj:`np.ndarray`, `optional`): The labels (if the dataset contained some).\n - metrics (:obj:`Dict[str, float]`, `optional`): The potential dictionary of metrics (if the dataset\n contained labels).\n \"\"\"\n # memory metrics - must set up as early as possible\n self._memory_tracker.start()\n\n test_dataloader = self.get_test_dataloader(test_dataset)\n start_time = time.time()\n\n eval_loop = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop\n output = eval_loop(\n test_dataloader, description=\"Prediction\", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix\n )\n total_batch_size = self.args.eval_batch_size * self.args.world_size\n output.metrics.update(\n speed_metrics(\n metric_key_prefix,\n start_time,\n num_samples=output.num_samples,\n num_steps=math.ceil(output.num_samples / total_batch_size),\n )\n )\n\n self._memory_tracker.stop_and_update_metrics(output.metrics)\n\n return PredictionOutput(predictions=output.predictions, label_ids=output.label_ids, metrics=output.metrics)\n\n def evaluation_loop(\n self,\n dataloader: DataLoader,\n description: str,\n prediction_loss_only: Optional[bool] = None,\n ignore_keys: Optional[List[str]] = None,\n metric_key_prefix: str = \"eval\",\n ) -> EvalLoopOutput:\n \"\"\"\n Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`.\n\n Works both with or without labels.\n \"\"\"\n prediction_loss_only = (\n prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only\n )\n\n # if eval is called w/o train init deepspeed here\n if self.args.deepspeed and not self.deepspeed:\n\n # XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval\n # from the checkpoint eventually\n deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None)\n self.model = deepspeed_engine.module\n self.model_wrapped = deepspeed_engine\n self.deepspeed = deepspeed_engine\n # XXX: we don't need optim/sched for inference, but this needs to be sorted out, since\n # for example the Z3-optimizer is a must for zero3 to work even for inference - what we\n # don't need is the deepspeed basic optimizer which is self.optimizer.optimizer\n deepspeed_engine.optimizer.optimizer = None\n deepspeed_engine.lr_scheduler = None\n\n model = self._wrap_model(self.model, training=False)\n\n # if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while\n # ``train`` is running, halve it first and then put on device\n if not self.is_in_train and self.args.fp16_full_eval:\n model = model.half().to(self.args.device)\n\n batch_size = dataloader.batch_size\n\n logger.info(f\"***** Running {description} *****\")\n if isinstance(dataloader.dataset, collections.abc.Sized):\n logger.info(f\" Num examples = {self.num_examples(dataloader)}\")\n else:\n logger.info(\" Num examples: Unknown\")\n logger.info(f\" Batch size = {batch_size}\")\n\n model.eval()\n\n self.callback_handler.eval_dataloader = dataloader\n # Do this before wrapping.\n eval_dataset = dataloader.dataset\n\n if is_torch_tpu_available():\n dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device)\n\n if self.args.past_index >= 0:\n self._past = None\n\n # Initialize containers\n # losses/preds/labels on GPU/TPU (accumulated for eval_accumulation_steps)\n losses_host = None\n preds_host = None\n labels_host = None\n # losses/preds/labels on CPU (final containers)\n all_losses = None\n all_preds = None\n all_labels = None\n # Will be useful when we have an iterable dataset so don't know its length.\n\n observed_num_examples = 0\n # Main evaluation loop\n for step, inputs in enumerate(dataloader):\n # Update the observed num examples\n observed_batch_size = find_batch_size(inputs)\n if observed_batch_size is not None:\n observed_num_examples += observed_batch_size\n\n # Prediction step\n loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)\n\n # Update containers on host\n if loss is not None:\n losses = self._nested_gather(loss.repeat(batch_size))\n losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)\n if logits is not None:\n logits = self._pad_across_processes(logits)\n logits = self._nested_gather(logits)\n preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)\n if labels is not None:\n labels = self._pad_across_processes(labels)\n labels = self._nested_gather(labels)\n labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)\n self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control)\n\n # Gather all tensors and put them back on the CPU if we have done enough accumulation steps.\n if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0:\n if losses_host is not None:\n losses = nested_numpify(losses_host)\n all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0)\n if preds_host is not None:\n logits = nested_numpify(preds_host)\n all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)\n if labels_host is not None:\n labels = nested_numpify(labels_host)\n all_labels = (\n labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100)\n )\n\n # Set back to None to begin a new accumulation\n losses_host, preds_host, labels_host = None, None, None\n\n if self.args.past_index and hasattr(self, \"_past\"):\n # Clean the state at the end of the evaluation loop\n delattr(self, \"_past\")\n\n # Gather all remaining tensors and put them back on the CPU\n if losses_host is not None:\n losses = nested_numpify(losses_host)\n all_losses = losses if all_losses is None else np.concatenate((all_losses, losses), axis=0)\n if preds_host is not None:\n logits = nested_numpify(preds_host)\n all_preds = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)\n if labels_host is not None:\n labels = nested_numpify(labels_host)\n all_labels = labels if all_labels is None else nested_concat(all_labels, labels, padding_index=-100)\n\n # Number of samples\n if not isinstance(eval_dataset, IterableDataset):\n num_samples = len(eval_dataset)\n # The instance check is weird and does not actually check for the type, but whether the dataset has the right\n # methods. Therefore we need to make sure it also has the attribute.\n elif isinstance(eval_dataset, IterableDatasetShard) and hasattr(eval_dataset, \"num_examples\"):\n num_samples = eval_dataset.num_examples\n else:\n num_samples = observed_num_examples\n\n # Number of losses has been rounded to a multiple of batch_size and in a distributed training, the number of\n # samplers has been rounded to a multiple of batch_size, so we truncate.\n if all_losses is not None:\n all_losses = all_losses[:num_samples]\n if all_preds is not None:\n all_preds = nested_truncate(all_preds, num_samples)\n if all_labels is not None:\n all_labels = nested_truncate(all_labels, num_samples)\n\n # Metrics!\n if self.compute_metrics is not None and all_preds is not None and all_labels is not None:\n metrics = self.compute_metrics(EvalPrediction(predictions=all_preds, label_ids=all_labels))\n else:\n metrics = {}\n\n # To be JSON-serializable, we need to remove numpy types or zero-d tensors\n metrics = denumpify_detensorize(metrics)\n\n if all_losses is not None:\n metrics[f\"{metric_key_prefix}_loss\"] = all_losses.mean().item()\n\n # Prefix all keys with metric_key_prefix + '_'\n for key in list(metrics.keys()):\n if not key.startswith(f\"{metric_key_prefix}_\"):\n metrics[f\"{metric_key_prefix}_{key}\"] = metrics.pop(key)\n\n return EvalLoopOutput(predictions=all_preds, label_ids=all_labels, metrics=metrics, num_samples=num_samples)\n\n def _nested_gather(self, tensors, name=None):\n \"\"\"\n Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before\n concatenating them to `gathered`\n \"\"\"\n if tensors is None:\n return\n if is_torch_tpu_available():\n if name is None:\n name = \"nested_gather\"\n tensors = nested_xla_mesh_reduce(tensors, name)\n elif is_sagemaker_mp_enabled():\n tensors = smp_gather(tensors)\n elif self.args.local_rank != -1:\n tensors = distributed_concat(tensors)\n return tensors\n\n # Copied from Accelerate.\n def _pad_across_processes(self, tensor, pad_index=-100):\n \"\"\"\n Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so\n they can safely be gathered.\n \"\"\"\n if isinstance(tensor, (list, tuple)):\n return type(tensor)(self._pad_across_processes(t, pad_index=pad_index) for t in tensor)\n elif isinstance(tensor, dict):\n return type(tensor)({k: self._pad_across_processes(v, pad_index=pad_index) for k, v in tensor.items()})\n elif not isinstance(tensor, torch.Tensor):\n raise TypeError(\n f\"Can't pad the values of type {type(tensor)}, only of nested list/tuple/dicts of tensors.\"\n )\n\n if len(tensor.shape) < 2:\n return tensor\n # Gather all sizes\n size = torch.tensor(tensor.shape, device=tensor.device)[None]\n sizes = self._nested_gather(size).cpu()\n\n max_size = max(s[1] for s in sizes)\n if tensor.shape[1] == max_size:\n return tensor\n\n # Then pad to the maximum size\n old_size = tensor.shape\n new_size = list(old_size)\n new_size[1] = max_size\n new_tensor = tensor.new_zeros(tuple(new_size)) + pad_index\n new_tensor[:, : old_size[1]] = tensor\n return new_tensor\n\n def prediction_step(\n self,\n model: nn.Module,\n inputs: Dict[str, Union[torch.Tensor, Any]],\n prediction_loss_only: bool,\n ignore_keys: Optional[List[str]] = None,\n ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]:\n \"\"\"\n Perform an evaluation step on :obj:`model` using obj:`inputs`.\n\n Subclass and override to inject custom behavior.\n\n Args:\n model (:obj:`nn.Module`):\n The model to evaluate.\n inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):\n The inputs and targets of the model.\n\n The dictionary will be unpacked before being fed to the model. Most models expect the targets under the\n argument :obj:`labels`. Check your model's documentation for all accepted arguments.\n prediction_loss_only (:obj:`bool`):\n Whether or not to return the loss only.\n ignore_keys (:obj:`Lst[str]`, `optional`):\n A list of keys in the output of your model (if it is a dictionary) that should be ignored when\n gathering predictions.\n\n Return:\n Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss,\n logits and labels (each being optional).\n \"\"\"\n has_labels = all(inputs.get(k) is not None for k in self.label_names)\n inputs = self._prepare_inputs(inputs)\n if ignore_keys is None:\n if hasattr(self.model, \"config\"):\n ignore_keys = getattr(self.model.config, \"keys_to_ignore_at_inference\", [])\n else:\n ignore_keys = []\n\n # labels may be popped when computing the loss (label smoothing for instance) so we grab them first.\n if has_labels:\n labels = nested_detach(tuple(inputs.get(name) for name in self.label_names))\n if len(labels) == 1:\n labels = labels[0]\n else:\n labels = None\n\n with torch.no_grad():\n if is_sagemaker_mp_enabled():\n raw_outputs = smp_forward_only(model, inputs)\n if has_labels:\n if isinstance(raw_outputs, dict):\n loss_mb = raw_outputs[\"loss\"]\n logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys + [\"loss\"])\n else:\n loss_mb = raw_outputs[0]\n logits_mb = raw_outputs[1:]\n\n loss = loss_mb.reduce_mean().detach().cpu()\n logits = smp_nested_concat(logits_mb)\n else:\n loss = None\n if isinstance(raw_outputs, dict):\n logits_mb = tuple(v for k, v in raw_outputs.items() if k not in ignore_keys)\n else:\n logits_mb = raw_outputs\n logits = smp_nested_concat(logits_mb)\n else:\n if has_labels:\n loss, outputs = self.compute_loss(model, inputs, return_outputs=True)\n loss = loss.mean().detach()\n if isinstance(outputs, dict):\n logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + [\"loss\"])\n else:\n logits = outputs[1:]\n else:\n loss = None\n if self.use_amp:\n with autocast():\n outputs = model(**inputs)\n else:\n outputs = model(**inputs)\n if isinstance(outputs, dict):\n logits = tuple(v for k, v in outputs.items() if k not in ignore_keys)\n else:\n logits = outputs\n # TODO: this needs to be fixed and made cleaner later.\n if self.args.past_index >= 0:\n self._past = outputs[self.args.past_index - 1]\n\n if prediction_loss_only:\n return (loss, None, None)\n\n logits = nested_detach(logits)\n if len(logits) == 1:\n logits = logits[0]\n\n return (loss, logits, labels)\n\n def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]):\n \"\"\"\n For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of\n floating point operations for every backward + forward pass. If using another model, either implement such a\n method in the model or subclass and override this method.\n\n Args:\n inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):\n The inputs and targets of the model.\n\n Returns:\n :obj:`int`: The number of floating-point operations.\n \"\"\"\n if hasattr(self.model, \"floating_point_ops\"):\n return self.model.floating_point_ops(inputs)\n else:\n return 0\n\n def init_git_repo(self):\n \"\"\"\n Initializes a git repo in :obj:`self.args.push_to_hub_model_id`.\n \"\"\"\n if not self.args.should_save:\n return\n use_auth_token = True if self.args.push_to_hub_token is None else self.args.push_to_hub_token\n repo_url = PushToHubMixin._get_repo_url_from_name(\n self.args.push_to_hub_model_id,\n organization=self.args.push_to_hub_organization,\n use_auth_token=use_auth_token,\n )\n self.repo = PushToHubMixin._create_or_get_repo(\n self.args.output_dir, repo_url=repo_url, use_auth_token=use_auth_token\n )\n\n # By default, ignore the checkpoint folders\n if not os.path.exists(os.path.join(self.args.output_dir, \".gitignore\")):\n with open(os.path.join(self.args.output_dir, \".gitignore\"), \"w\", encoding=\"utf-8\") as writer:\n writer.writelines([\"checkpoint-*/\"])\n\n def create_model_card(\n self,\n language: Optional[str] = None,\n license: Optional[str] = None,\n tags: Optional[str] = None,\n model_name: Optional[str] = None,\n finetuned_from: Optional[str] = None,\n tasks: Optional[str] = None,\n dataset_tags: Optional[Union[str, List[str]]] = None,\n dataset: Optional[Union[str, List[str]]] = None,\n dataset_args: Optional[Union[str, List[str]]] = None,\n ):\n training_summary = TrainingSummary.from_trainer(\n self,\n language=language,\n license=license,\n tags=tags,\n model_name=model_name,\n finetuned_from=finetuned_from,\n tasks=tasks,\n dataset_tags=dataset_tags,\n dataset=dataset,\n dataset_args=dataset_args,\n )\n model_card = training_summary.to_model_card()\n with open(os.path.join(self.args.output_dir, \"README.md\"), \"w\") as f:\n f.write(model_card)\n\n def push_to_hub(self, commit_message: Optional[str] = \"add model\", **kwargs) -> str:\n \"\"\"\n Upload `self.model` and `self.tokenizer` to the 🤗 model hub on the repo `self.args.push_to_hub_model_id`.\n\n Parameters:\n commit_message (:obj:`str`, `optional`, defaults to :obj:`\"add model\"`):\n Message to commit while pushing.\n kwargs:\n Additional keyword arguments passed along to :meth:`~transformers.Trainer.create_model_card`.\n\n Returns:\n The url of the commit of your model in the given repository.\n \"\"\"\n\n if self.args.should_save:\n self.create_model_card(model_name=self.args.push_to_hub_model_id, **kwargs)\n # Needs to be executed on all processes for TPU training, but will only save on the processed determined by\n # self.args.should_save.\n self.save_model()\n\n # Only push from one node.\n if not self.is_world_process_zero():\n return\n\n return self.repo.push_to_hub(commit_message=commit_message)\n\n #\n # Deprecated code\n #\n\n def prediction_loop(\n self,\n dataloader: DataLoader,\n description: str,\n prediction_loss_only: Optional[bool] = None,\n ignore_keys: Optional[List[str]] = None,\n metric_key_prefix: str = \"eval\",\n ) -> PredictionOutput:\n \"\"\"\n Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`.\n\n Works both with or without labels.\n \"\"\"\n if not isinstance(dataloader.dataset, collections.abc.Sized):\n raise ValueError(\"dataset must implement __len__\")\n prediction_loss_only = (\n prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only\n )\n\n # if eval is called w/o train init deepspeed here\n if self.args.deepspeed and not self.deepspeed:\n\n # XXX: eval doesn't have `resume_from_checkpoint` arg but we should be able to do eval\n # from the checkpoint eventually\n deepspeed_engine, _, _ = deepspeed_init(self, num_training_steps=0, resume_from_checkpoint=None)\n self.model = deepspeed_engine.module\n self.model_wrapped = deepspeed_engine\n self.deepspeed = deepspeed_engine\n # XXX: we don't need optim/sched for inference, but this needs to be sorted out, since\n # for example the Z3-optimizer is a must for zero3 to work even for inference - what we\n # don't need is the deepspeed basic optimizer which is self.optimizer.optimizer\n deepspeed_engine.optimizer.optimizer = None\n deepspeed_engine.lr_scheduler = None\n\n model = self._wrap_model(self.model, training=False)\n\n # if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while\n # ``train`` is running, halve it first and then put on device\n if not self.is_in_train and self.args.fp16_full_eval:\n model = model.half().to(self.args.device)\n\n batch_size = dataloader.batch_size\n num_examples = self.num_examples(dataloader)\n logger.info(f\"***** Running {description} *****\")\n logger.info(f\" Num examples = {num_examples}\")\n logger.info(f\" Batch size = {batch_size}\")\n losses_host: torch.Tensor = None\n preds_host: Union[torch.Tensor, List[torch.Tensor]] = None\n labels_host: Union[torch.Tensor, List[torch.Tensor]] = None\n\n world_size = max(1, self.args.world_size)\n\n eval_losses_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=batch_size)\n if not prediction_loss_only:\n # The actual number of eval_sample can be greater than num_examples in distributed settings (when we pass\n # a batch size to the sampler)\n make_multiple_of = None\n if hasattr(dataloader, \"sampler\") and isinstance(dataloader.sampler, SequentialDistributedSampler):\n make_multiple_of = dataloader.sampler.batch_size\n preds_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of)\n labels_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=make_multiple_of)\n\n model.eval()\n\n if is_torch_tpu_available():\n dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device)\n\n if self.args.past_index >= 0:\n self._past = None\n\n self.callback_handler.eval_dataloader = dataloader\n\n for step, inputs in enumerate(dataloader):\n loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)\n if loss is not None:\n losses = loss.repeat(batch_size)\n losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)\n if logits is not None:\n preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)\n if labels is not None:\n labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)\n self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control)\n\n # Gather all tensors and put them back on the CPU if we have done enough accumulation steps.\n if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0:\n eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, \"eval_losses\"))\n if not prediction_loss_only:\n preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, \"eval_preds\"))\n labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, \"eval_label_ids\"))\n\n # Set back to None to begin a new accumulation\n losses_host, preds_host, labels_host = None, None, None\n\n if self.args.past_index and hasattr(self, \"_past\"):\n # Clean the state at the end of the evaluation loop\n delattr(self, \"_past\")\n\n # Gather all remaining tensors and put them back on the CPU\n eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, \"eval_losses\"))\n if not prediction_loss_only:\n preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, \"eval_preds\"))\n labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, \"eval_label_ids\"))\n\n eval_loss = eval_losses_gatherer.finalize()\n preds = preds_gatherer.finalize() if not prediction_loss_only else None\n label_ids = labels_gatherer.finalize() if not prediction_loss_only else None\n\n if self.compute_metrics is not None and preds is not None and label_ids is not None:\n metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))\n else:\n metrics = {}\n\n # To be JSON-serializable, we need to remove numpy types or zero-d tensors\n metrics = denumpify_detensorize(metrics)\n\n if eval_loss is not None:\n metrics[f\"{metric_key_prefix}_loss\"] = eval_loss.mean().item()\n\n # Prefix all keys with metric_key_prefix + '_'\n for key in list(metrics.keys()):\n if not key.startswith(f\"{metric_key_prefix}_\"):\n metrics[f\"{metric_key_prefix}_{key}\"] = metrics.pop(key)\n\n return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics)\n\n def _gather_and_numpify(self, tensors, name):\n \"\"\"\n Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before\n concatenating them to `gathered`\n \"\"\"\n if tensors is None:\n return\n if is_torch_tpu_available():\n tensors = nested_xla_mesh_reduce(tensors, name)\n elif is_sagemaker_mp_enabled():\n tensors = smp_gather(tensors)\n elif self.args.local_rank != -1:\n tensors = distributed_concat(tensors)\n\n return nested_numpify(tensors)\n"
] |
[
[
"torch.load",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.cuda.random.get_rng_state_all",
"torch.cuda.amp.autocast",
"numpy.concatenate",
"torch.no_grad",
"torch.cuda.is_available",
"torch.Generator",
"torch.utils.data.distributed.DistributedSampler",
"torch.distributed.barrier",
"torch.tensor",
"numpy.random.set_state",
"torch.distributed.get_local_rank",
"torch.empty",
"torch.cuda.random.get_rng_state",
"torch.cuda.amp.GradScaler",
"torch.cuda.random.set_rng_state",
"torch.nn.parallel.DistributedDataParallel",
"numpy.random.get_state",
"torch.cuda.random.set_rng_state_all",
"torch.random.set_rng_state",
"torch.random.get_rng_state",
"torch.utils.data.SequentialSampler",
"torch.utils.data.RandomSampler",
"torch.nn.DataParallel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kapikantzari/MultiBench
|
[
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f",
"44ab6ea028682040a0c04de68239ce5cdf15123f"
] |
[
"deprecated/examples_robust/multimedia/avmnist_unimodal_1_robust.py",
"deprecated/dataloaders/mimic/get_data.py",
"deprecated/dataloaders/affect/humor_dataset.py",
"deprecated/robustness_tests_draft.py",
"deprecated/examples_robust/affect/mosi_early_fusion_robust.py",
"examples/hci/enrico_unimodal_1.py",
"deprecated/dataloaders/deprecated_examples/affect/humor_early_fusion.py",
"deprecated/examples_robust/multimedia/mmimdb_contrast_robust.py",
"private_test_scripts/avmvae.py",
"examples/multimedia/kinetics_gradient_blend.py",
"deprecated/examples_robust/gentle_push/unimodal_pos_robust.py",
"deprecated/examples_robust/multimedia/avmnist_simple_late_fusion_robust.py",
"special/kinetics_video_unimodal_16.py",
"examples/gentle_push/LF.py",
"deprecated/dataloaders/deprecated_examples/multimedia/avmnist_simple_late_fusion.py"
] |
[
"from unimodals.common_models import LeNet, MLP, Constant\nimport torch\nfrom torch import nn\nfrom datasets.avmnist.get_data_robust import get_dataloader\nfrom training_structures.unimodal import train, test\nimport sys\nimport os\nsys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))\n\nfilename_encoder = 'avmnist_unimodal_1_encoder.pt'\nfilename_head = 'avmnist_unimodal_1_head.pt'\nmodalnum = 1\ntraindata, validdata, testdata, robustdata = get_dataloader(\n '../../../../yiwei/avmnist/_MFAS/avmnist')\nchannels = 6\n# encoders=[LeNet(1,channels,3).cuda(),LeNet(1,channels,5).cuda()]\nencoder = LeNet(1, channels, 5).cuda()\nhead = MLP(channels*32, 100, 10).cuda()\n\n\ntrain(encoder, head, traindata, validdata, 20, optimtype=torch.optim.SGD, lr=0.1,\n weight_decay=0.0001, modalnum=modalnum, save_encoder=filename_encoder, save_head=filename_head)\n\nencoder = torch.load(filename_encoder).cuda()\nhead = torch.load(filename_head)\nprint(\"Testing:\")\ntest(encoder, head, testdata, modalnum=modalnum)\n\nprint(\"Robustness testing:\")\ntest(encoder, head, robustdata, modalnum=modalnum)\n",
"import numpy as np\nfrom torch.utils.data import DataLoader\nimport random\nimport pickle\n# task: integer between -1 and 19 inclusive, -1 means mortality task, 0-19 means icd9 task\n# flatten time series: whether to flatten time series into 1-dim large vectors or not\n\n\ndef get_dataloader(task, batch_size=40, num_workers=1, train_shuffle=True, imputed_path='im.pk', flatten_time_series=False):\n f = open(imputed_path, 'rb')\n datafile = pickle.load(f)\n f.close()\n X_t = datafile['ep_tdata']\n X_s = datafile['adm_features_all']\n\n X_t[np.isinf(X_t)] = 0\n X_t[np.isnan(X_t)] = 0\n X_s[np.isinf(X_s)] = 0\n X_s[np.isnan(X_s)] = 0\n\n X_s_avg = np.average(X_s, axis=0)\n X_s_std = np.std(X_s, axis=0)\n X_t_avg = np.average(X_t, axis=(0, 1))\n X_t_std = np.std(X_t, axis=(0, 1))\n\n for i in range(len(X_s)):\n X_s[i] = (X_s[i]-X_s_avg)/X_s_std\n for j in range(len(X_t[0])):\n X_t[i][j] = (X_t[i][j]-X_t_avg)/X_t_std\n\n static_dim = len(X_s[0])\n timestep = len(X_t[0])\n series_dim = len(X_t[0][0])\n if flatten_time_series:\n X_t = X_t.reshape(len(X_t), timestep*series_dim)\n if task < 0:\n y = datafile['adm_labels_all'][:, 1]\n admlbl = datafile['adm_labels_all']\n le = len(y)\n for i in range(0, le):\n if admlbl[i][1] > 0:\n y[i] = 1\n elif admlbl[i][2] > 0:\n y[i] = 2\n elif admlbl[i][3] > 0:\n y[i] = 3\n elif admlbl[i][4] > 0:\n y[i] = 4\n elif admlbl[i][5] > 0:\n y[i] = 5\n else:\n y[i] = 0\n else:\n y = datafile['y_icd9'][:, task]\n le = len(y)\n datasets = [(X_s[i], X_t[i], y[i]) for i in range(le)]\n\n random.seed(10)\n\n random.shuffle(datasets)\n\n valids = DataLoader(datasets[0:le//10], shuffle=False,\n num_workers=num_workers, batch_size=batch_size)\n tests = DataLoader(datasets[le//10:le//5], shuffle=False,\n num_workers=num_workers, batch_size=batch_size)\n trains = DataLoader(datasets[le//5:], shuffle=train_shuffle,\n num_workers=num_workers, batch_size=batch_size)\n return trains, valids, tests\n",
"import pickle\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport numpy as np\nimport torch.nn as nn\n\n\ndef load_pickle(pickle_file):\n try:\n with open(pickle_file, 'rb') as f:\n pickle_data = pickle.load(f)\n except UnicodeDecodeError as e:\n with open(pickle_file, 'rb') as f:\n pickle_data = pickle.load(f, encoding='latin1')\n except Exception as e:\n print('Unable to load data ', pickle_file, ':', e)\n raise\n return pickle_data\n\n\nclass HumorDataset(Dataset):\n\n def __init__(self, id_list, max_context_len=5, max_sen_len=20):\n self.id_list = id_list\n openface_file = \"openface_features_sdk.pkl\"\n covarep_file = \"covarep_features_sdk.pkl\"\n language_file = \"language_sdk.pkl\"\n word_embedding_list_file = \"word_embedding_list.pkl\"\n humor_label_file = \"humor_label_sdk.pkl\"\n\n self.word_aligned_openface_sdk = load_pickle(openface_file)\n self.word_aligned_covarep_sdk = load_pickle(covarep_file)\n self.language_sdk = load_pickle(language_file)\n self.word_embedding_list_sdk = load_pickle(word_embedding_list_file)\n self.humor_label_sdk = load_pickle(humor_label_file)\n self.of_d = 371\n self.cvp_d = 81\n self.glove_d = 300\n self.total_dim = self.glove_d + self.of_d + self.cvp_d\n self.max_context_len = max_context_len\n self.max_sen_len = max_sen_len\n\n # left padding with zero vector upto maximum number of words in a sentence * glove embedding dimension\n def paded_word_idx(self, seq, max_sen_len=20, left_pad=1):\n seq = seq[0:max_sen_len]\n pad_w = np.concatenate((np.zeros(max_sen_len - len(seq)), seq), axis=0)\n pad_w = np.array([self.word_embedding_list_sdk[int(w_id)]\n for w_id in pad_w])\n return pad_w\n\n # left padding with zero vector upto maximum number of words in a sentence * covarep dimension\n def padded_covarep_features(self, seq, max_sen_len=20, left_pad=1):\n seq = seq[0:max_sen_len]\n return np.concatenate((np.zeros((max_sen_len - len(seq), self.cvp_d)), seq), axis=0)\n\n # left padding with zero vector upto maximum number of words in a sentence * openface dimension\n def padded_openface_features(self, seq, max_sen_len=20, left_pad=1):\n seq = seq[0:max_sen_len]\n return np.concatenate((np.zeros(((max_sen_len - len(seq)), self.of_d)), seq), axis=0)\n\n # left padding with zero vectors upto maximum number of sentences in context * maximum num of words in a sentence * 456\n def padded_context_features(self, context_w, context_of, context_cvp, max_context_len=5, max_sen_len=20):\n context_w = context_w[-max_context_len:]\n context_of = context_of[-max_context_len:]\n context_cvp = context_cvp[-max_context_len:]\n\n padded_context = []\n for i in range(len(context_w)):\n p_seq_w = self.paded_word_idx(context_w[i], max_sen_len)\n p_seq_cvp = self.padded_covarep_features(\n context_cvp[i], max_sen_len)\n p_seq_of = self.padded_openface_features(\n context_of[i], max_sen_len)\n padded_context.append(np.concatenate(\n (p_seq_w, p_seq_cvp, p_seq_of), axis=1))\n\n pad_c_len = max_context_len - len(padded_context)\n padded_context = np.array(padded_context)\n\n # if there is no context\n if not padded_context.any():\n return np.zeros((max_context_len, max_sen_len, self.total_dim))\n\n return np.concatenate((np.zeros((pad_c_len, max_sen_len, self.total_dim)), padded_context), axis=0)\n\n def padded_punchline_features(self, punchline_w, punchline_of, punchline_cvp, max_sen_len=20, left_pad=1):\n\n p_seq_w = self.paded_word_idx(punchline_w, max_sen_len)\n p_seq_cvp = self.padded_covarep_features(punchline_cvp, max_sen_len)\n p_seq_of = self.padded_openface_features(punchline_of, max_sen_len)\n return np.concatenate((p_seq_w, p_seq_cvp, p_seq_of), axis=1)\n\n def __len__(self):\n return len(self.id_list)\n\n def __getitem__(self, index):\n\n hid = self.id_list[index]\n punchline_w = np.array(\n self.language_sdk[hid]['punchline_embedding_indexes'])\n punchline_of = np.array(\n self.word_aligned_openface_sdk[hid]['punchline_features'])\n punchline_cvp = np.array(\n self.word_aligned_covarep_sdk[hid]['punchline_features'])\n\n context_w = np.array(\n self.language_sdk[hid]['context_embedding_indexes'])\n context_of = np.array(\n self.word_aligned_openface_sdk[hid]['context_features'])\n context_cvp = np.array(\n self.word_aligned_covarep_sdk[hid]['context_features'])\n\n # punchline feature\n x_p = torch.LongTensor(\n self.padded_punchline_features(punchline_w, punchline_of, punchline_cvp, self.max_sen_len))\n # context feature\n x_c = torch.LongTensor(\n self.padded_context_features(context_w, context_of, context_cvp, self.max_context_len, self.max_sen_len))\n\n y = torch.FloatTensor([self.humor_label_sdk[hid]])\n\n return x_p, x_c, y\n",
"import h5py\nimport pickle\nimport numpy as np\n# import read_affect_data as r\n# from tqdm import tqdm\nimport random\n\nfrom PIL import Image, ImageOps, ImageEnhance\nimport colorsys\n\n\n# def read_h5_data_set(path):\n# f = h5py.File(path, 'r')\n# time_stamps = list(f[list(f.keys())[0]].keys())\n# d = {time : dict() for time in time_stamps}\n# for feature in list(f.keys()):\n# if hasattr(f[feature], 'keys'):\n\n# for time in tqdm(list(f[feature].keys())):\n# k = list(f[feature][time].keys())[0]\n# d[time][feature] = np.array(f[feature][time][k])\n# return d\n\n\n# def read_pkl_data_set(path):\n# f = r.load_pickle(path)\n# time_stamps = list(f[list(f.keys())[0]].keys())\n# d = {time : dict() for time in time_stamps}\n# for feature in list(f.keys()):\n# if hasattr(f[feature], 'keys'):\n\n# for time in tqdm(list(f[feature].keys())):\n# if hasattr(f[feature][time], 'keys'):\n# for k in list(f[feature][time].keys()):\n# d[time][feature] = np.array(f[feature][time][k])\n# return d\n\n\n##############################################################################\n# Visual\ndef visual_robustness(tests, noise_level=0.3, gray=True, contrast=True, s_and_p=True, gaus=True, rot=True, crop=True):\n noises = []\n if gray:\n noises.append(grayscale)\n if contrast:\n noises.append(low_contrast)\n if s_and_p:\n noises.append(salt_and_pepper)\n if gaus:\n noises.append(gaussian)\n if rot:\n noises.append(rotate)\n if crop:\n noises.append(random_crop)\n robustness_tests = []\n for i in range(len(tests)):\n img = Image.fromarray(tests[i])\n for noise in noises:\n img = noise(img, noise_level)\n robustness_tests.append(np.array(img))\n return robustness_tests\n\n\ndef grayscale(img, p):\n if np.random.sample() <= p:\n return ImageOps.grayscale(img)\n else:\n return img\n\n\ndef low_contrast(img, factor):\n if np.random.sample() <= p:\n enhancer = ImageEnhance.Contrast(img)\n return enhancer.enhance(factor)\n else:\n return img\n\n\ndef inversion(img, p):\n if np.random.sample() <= p:\n return ImageOps.invert(img)\n else:\n return img\n\n\ndef WB(img, p):\n if np.random.sample() <= p:\n kelvin_table = {1000: (255, 56, 0), 1500: (255, 109, 0), 2000: (255, 137, 18), 2500: (255, 161, 72), 3000: (255, 180, 107), 3500: (255, 196, 137), 4000: (255, 209, 163), 4500: (255, 219, 186), 5000: (255, 228, 206), 5500: (\n 255, 236, 224), 6000: (255, 243, 239), 6500: (255, 249, 253), 7000: (245, 243, 255), 7500: (235, 238, 255), 8000: (227, 233, 255), 8500: (220, 229, 255), 9000: (214, 225, 255), 9500: (208, 222, 255), 10000: (204, 219, 255)}\n temp = np.random.choice(kelvin_table.keys())\n r, g, b = kelvin_table[temp]\n matrix = (r / 255.0, 0.0, 0.0, 0.0,\n 0.0, g / 255.0, 0.0, 0.0,\n 0.0, 0.0, b / 255.0, 0.0)\n return img.convert('RGB', matrix)\n else:\n return img\n\n\ndef colorize(img, p):\n if np.random.sample() <= p:\n color = np.random.choice(['red', 'blue', 'green'])\n layer = Image.new('RGB', img.size, color)\n return Image.blend(img, layer, 0.3)\n else:\n return img\n\n\ndef salt_and_pepper(img, p):\n if np.random.sample() <= p:\n output = np.copy(np.array(img))\n nb_salt = np.ceil(p*output.size*0.5)\n coords = [np.random.randint(0, i-1, int(nb_salt))\n for i in output.shape]\n for i in coords:\n output[i] = 1\n nb_pepper = np.ceil(p*output.size*0.5)\n coords = [np.random.randint(0, i-1, int(nb_pepper))\n for i in output.shape]\n for i in coords:\n output[i] = 0\n return Image.fromarray(output)\n else:\n return img\n\n\ndef gaussian(img, p):\n if np.random.sample() <= p:\n height, width = np.array(img).shape\n gauss = np.random.normal(0, p, (height, width))\n return Image.fromarray((np.array(img)+gauss).astype('uint8'))\n else:\n return img\n\n\ndef rotate(img, p):\n if np.random.sample() <= p:\n angle = np.random.random_sample()*40-20\n return img.rotate(angle, Image.BILINEAR)\n else:\n return img\n\n\ndef horizontal_flip(img, p):\n if np.random.sample() <= p:\n return img.transpose(Image.FLIP_LEFT_RIGHT)\n else:\n return img\n\n\ndef random_crop(img, p):\n if np.random.sample() <= p:\n dim = np.array(img).shape\n height = dim[0]\n width = dim[1]\n cropped_height = height / 5\n cropped_width = width / 5\n init_height = np.random.random_sample() * cropped_height\n init_width = np.random.random_sample() * cropped_width\n end_height = height - cropped_height + init_height\n end_width = width - cropped_width + init_width\n return img.crop((init_width, init_height, end_width, end_height)).resize((height, width))\n else:\n return img\n\n\ndef periodic(img, periodic_noise_filename=\"periodic_noise\"):\n height = img.height\n width = img.width\n output = []\n for i in range(6):\n noise = Image.open(\"{}_{}.png\".format(\n periodic_noise_filename, i+1)).convert(\"RGBA\")\n noise = random_crop(rotate(noise.resize(\n (width*2, height*2)), np.random.random_sample()*360, 'white'), height, width)\n output.append(Image.blend(img.convert(\"RGBA\"), noise, 0.3))\n return output\n\n\n##############################################################################\n# Text\ndef text_robustness(tests, noise_level=0.3, swap=True, rand_mid=True, typo=True, sticky=True, omit=True):\n noises = []\n if swap:\n noises.append(swap_letter)\n if rand_mid:\n noises.append(random_mid)\n if typo:\n noises.append(qwerty_typo)\n if sticky:\n noises.append(sticky_keys)\n if omit:\n noises.append(omission)\n robustness_tests = []\n for i in range(len(tests)):\n newtext = []\n text = tests[i].lower().split()\n for word in text:\n if len(word) > 3 and np.random.sample() <= noise_level:\n mode = np.random.randint(len(noises))\n newtext.append(noises[mode](word))\n else:\n newtext.append(word)\n robustness_tests.append(' '.join(newtext))\n return np.array(robustness_tests)\n\n\ndef last_char(word):\n for i in range(len(word)):\n if word[len(word)-1-i].isalpha():\n return len(word) - 1 - i\n\n\ndef swap_letter(word):\n # swap two random adjacent letters\n last = last_char(word)\n pos = np.random.randint(last-2) + 1\n return word[:pos] + word[pos+1] + word[pos] + word[pos+2:]\n\n\ndef random_mid(word):\n # randomly permute the middle chunk of a word (all letters except the first and last letter)\n last = last_char(word)\n mid = [char for char in word[1:last]]\n np.random.shuffle(mid)\n return word[0]+''.join(mid)+word[last:]\n\n\ndef qwerty_typo(word, num_typo=1):\n # randomly replace num_typo number of letters of a word to a one adjacent to it on qwerty keyboard\n qwerty = {'q': ['w'], 'w': ['q', 'e', 's'], 'e': ['w', 'r', 'd'], 'r': ['e', 't', 'f'], 't': ['r', 'g', 'y'], 'y': ['t', 'u', 'h'], 'u': ['y', 'i', 'j'], 'i': ['u', 'o', 'k'], 'o': ['i', 'p', 'l'], 'p': ['o'], 'a': ['q', 's', 'z'], 's': ['a', 'w', 'd', 'x', 'z'], 'd': ['s', 'e', 'f', 'x', 'c'], 'f': ['d', 'r', 'g', 'c', 'v'], 'g': [\n 'f', 't', 'h', 'v', 'b'], 'h': ['g', 'y', 'j', 'b', 'n'], 'j': ['h', 'u', 'k', 'n', 'm'], 'k': ['j', 'i', 'l', 'm'], 'l': ['k', 'o'], 'z': ['a', 's', 'x'], 'x': ['z', 's', 'd', 'c'], 'c': ['x', 'd', 'f', 'v'], 'v': ['c', 'f', 'g', 'b'], 'b': ['v', 'g', 'h', 'n'], 'n': ['b', 'h', 'm', 'j'], 'm': ['n', 'j', 'k']}\n last = last_char(word)\n typos = np.arange(last+1)\n np.random.shuffle(typos)\n for i in range(num_typo):\n typo = qwerty[word[typos[i]]]\n key = typo[np.random.randint(len(typo))]\n word = word[:typos[i]] + key + word[typos[i]+1:]\n return word\n\n\ndef sticky_keys(word, num_sticky=1):\n # randomly repeat num_sticky number of letters of a word\n last = last_char(word)\n sticky = np.arange(last+1)\n np.random.shuffle(sticky)\n for i in range(num_sticky):\n word = word[:sticky[i]] + word[sticky[i]] + word[sticky[i]:]\n return word\n\n\ndef omission(word, num_omit=1):\n # randomly omit num_omit number of letters of a word\n last = last_char(word)\n for i in range(num_omit):\n omit = np.random.randint(last-1) + 1\n word = word[:omit] + word[omit+1:]\n last -= 1\n return word\n\n##############################################################################\n# Audio\n\n\ndef audio_robustness(tests, noise_level=0.3, noises=None):\n if noises == None:\n noises = [additive_white_gaussian_noise,\n audio_random_dropout, audio_structured_dropout]\n robustness_tests = np.zeros(tests.shape)\n for i in range(len(tests)):\n if np.random.sample() <= noise_level:\n mode = np.random.randint(len(noises))\n robustness_tests[i] = noises[mode](tests[i], noise_level)\n return robustness_tests\n\n\ndef additive_white_gaussian_noise(signal, noise_level):\n # SNR = 10 * log((RMS of signal)^2 / (RMS of noise)^2)\n # RMS_s = np.sqrt(np.mean(signal*signal))\n # RMS_n = np.sqrt(RMS_s*RMS_s / (np.power(10, SNR/10)))\n noise = np.random.normal(0, noise_level, signal.shape[0])\n return signal + noise\n\n\ndef audio_structured_dropout(sig, p, step=10):\n # each consecutive time steps are chosen with probability p to be dropped\n res = [sig[i] for i in range(len(sig))]\n for i in range(len(res)-step+1):\n if (res[i] != 0) and np.random.random_sample() < p:\n for j in range(step):\n res[i+j] = 0\n return res\n\n\ndef audio_random_dropout(sig, p):\n return audio_structured_dropout(sig, 1, p)\n\n\n##############################################################################\n# Time-Series\ndef timeseries_robustness(tests, noise_level=0.3, noise=True, rand_drop=True, struct_drop=True, modality_map=None):\n robust_tests = np.array(tests)\n if noise:\n robust_tests = white_noise(robust_tests, noise_level)\n if rand_drop:\n robust_tests = random_drop(robust_tests, noise_level)\n if struct_drop:\n robust_tests = structured_drop(robust_tests, noise_level, modality_map)\n return robust_tests\n\n\n# add noise sampled from zero-mean Gaussian with standard deviation p at every time step\ndef white_noise(data, p):\n for i in range(len(data)):\n for time in range(len(data[i])):\n data[i][time] += np.random.normal(0, p)\n return data\n\n# each entry is dropped independently with probability p\n\n\ndef random_drop(data, p):\n for i in range(len(data)):\n for time in range(len(data[i])):\n for feature in range(len(data[i][time])):\n if np.random.random_sample() < p:\n data[i][time][feature] = 0\n # else:\n # result = dict()\n # for time in data:\n # for feature in data[time]:\n # if np.random.random_sample() < p:\n # result[time][feature] = np.zeros(data[time][feature].shape)\n # else:\n # result[time][feature] = data[time][feature]\n return data\n\n\n# independently for each modality, each time step is chosen with probability p\n# at which all feature dimensions are dropped\ndef structured_drop(data, p, modality_map):\n for i in range(len(data)):\n for time in range(len(data[i])):\n if np.random.random_sample() < p:\n data[i][time] = np.zeros(data[i][time].shape)\n # else:\n # result = dict()\n # for time in data:\n # for modality in modality_map.keys():\n # if np.random.random_sample() < p:\n # for feature in modality_map[modality]:\n # result[time][feature] = np.zeros(data[time][feature].shape)\n # else:\n # for feature in modality_map[modality]:\n # result[time][feature] = data[time][feature]\n return data\n\n\n##############################################################################\n# Tabular\ndef add_tabular_noise(tests, noise_level=0.3, drop=True, swap=True):\n robust_tests = np.array(tests)\n if drop:\n robust_tests = drop_entry(robust_tests, noise_level)\n if swap:\n robust_tests = swap_entry(robust_tests, noise_level)\n return robust_tests\n\n\ndef drop_entry(data, p):\n for i in range(len(data)):\n for j in range(len(data[i])):\n if np.random.random_sample() < p:\n data[i][j] = 0\n else:\n data[i][j] = data[i][j]\n return data\n\n\ndef swap_entry(data, p):\n for i in range(len(data)):\n for j in range(1, len(data[i])):\n if np.random.random_sample() < p:\n data[i][j] = data[i][j-1]\n data[i][j-1] = data[i][j]\n return data\n\n\nif __name__ == '__main__':\n print('='*5 + 'Multi Affect' + '='*5)\n print('1. CMU-MOSI, Aligned')\n print('2. CMU-MOSI, Unaligned')\n print('3. CMU-MOSEI, Aligned')\n print('4. CMU-MOSEI, Unaligned')\n print('5. CMU-POM, Aligned')\n print('6. CMU-POM, Unaligned')\n print('7. UR-Funny')\n print('8. Sarcasm')\n print('9. Deception')\n\n opt = int(input('Input option: '))\n print('='*22)\n if opt == 1:\n data = read_h5_data_set('./mosi/mosi.hdf5')\n modality_map = {'vision': ['FACET_4.2', 'OpenFace_1'], 'text': [\n 'words'], 'vocal': ['COVAREP', 'OpenSmile_emobase2010']}\n elif opt == 2:\n print(\"To be implemented!\")\n # data = read_h5_data_set('./mosi/mosi_unalign.hdf5')\n elif opt == 3:\n data = read_h5_data_set('./mosei/mosei.hdf5')\n modality_map = {'vision': ['OpenFace_2'],\n 'text': ['words'], 'vocal': ['COVAREP']}\n elif opt == 4:\n print(\"To be implemented!\")\n # data = read_h5_data_set('./mosei/mosei_unalign.hdf5')\n elif opt == 5:\n data = read_h5_data_set('./pom/pom.hdf5')\n modality_map = {'vision': ['FACET_4.2', 'OpenFace2'], 'text': [\n 'words'], 'vocal': ['COVAREP']}\n elif opt == 6:\n print(\"To be implemented!\")\n # data = read_h5_data_set('./pom/pom_unalign.hdf5')\n elif opt == 7:\n data = read_pkl_data_set('./urfunny/urfunny.pkl')\n # time = data[list(data.keys())[0]]\n # k = data[list(data[time].keys())[0]]\n \n elif opt == 8:\n print(\"To be implemented!\")\n # display_sarcasm_data_set('./sarcasm/sarcasm.pkl')\n elif opt == 9:\n print(\"To be implemented!\")\n # display_pkl_data_set('./deception/deception.pkl')\n else:\n print('Wrong Input!')\n",
"from unimodals.common_models import GRU, MLP\nfrom robustness.all_in_one import general_train, general_test\nfrom get_data_robust import get_dataloader\nfrom fusions.common_fusions import ConcatEarly\nfrom training_structures.Simple_Early_Fusion import train, test\nimport torch\nimport sys\nimport os\nsys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))\n\n\nsys.path.append('/home/pliang/multibench/MultiBench/datasets/affect')\n\n# Support mosi/mosi_unaligned/mosei/mosei_unaligned\ntraindata, validdata, robust_text, robust_vision, robust_audio, robust_timeseries = get_dataloader(\n '../../../affect/processed/mosi_data.pkl', '../../../affect/mosi', 'mosi')\n\n# mosi\n# encoders=GRU(325,512,dropout=True,has_padding=True).cuda()\n# head=MLP(512,256, 1).cuda()\n\n# mosei\nencoders = GRU(409, 800, dropout=True, has_padding=True).cuda()\nhead = MLP(800, 400, 1).cuda()\n# encoders=[GRU(35,70,dropout=True,has_padding=True).cuda(), \\\n# GRU(74,150,dropout=True,has_padding=True).cuda(),\\\n# GRU(300,600,dropout=True,has_padding=True).cuda()]\n# head=MLP(820,400,1).cuda()\n# iemocap\n'''\nencoders=[GRU(35,70,dropout=True,has_padding=True).cuda(), \\\n GRU(74,150,dropout=True,has_padding=True).cuda(),\\\n GRU(300,600,dropout=True,has_padding=True).cuda()]\nhead=MLP(820,400,4).cuda()\n'''\nfusion = ConcatEarly().cuda()\n\n# Support simple early_fusion and early_fusion with removing bias\n# mosi/mosei\n\n\ndef trainprocess(filename):\n train(encoders, fusion, head, traindata, validdata, 1000, True, True, task=\"regression\", optimtype=torch.optim.AdamW,\n lr=1e-5, save=filename, weight_decay=0.01, criterion=torch.nn.L1Loss(), regularization=False)\n\n\nfilename = general_train(trainprocess, 'mosi_early_fusion')\n# iemocap\n'''\ntrain(encoders,fusion,head,traindata,validdata,1000,True,True, \\\n optimtype=torch.optim.AdamW,lr=1e-4,save='best.pt', \\\n weight_decay=0.01,regularization=False)\n'''\n\n\ndef testprocess(model, robustdata):\n return test(model, robustdata, True, torch.nn.L1Loss(), \"regression\")\n\n\ngeneral_test(testprocess, filename, [\n robust_text, robust_vision, robust_audio, robust_timeseries])\n# test(model,testdata,True,)\n",
"import sys\nimport os\nimport torch \nfrom torch import nn\n\nsys.path.append(os.getcwd())\n\nfrom unimodals.common_models import VGG16, VGG16Slim, DAN, Linear, MLP, VGG11Slim, VGG11Pruned, VGG16Pruned # noqa\nfrom private_test_scripts.all_in_one import all_in_one_train, all_in_one_test # noqa\nfrom memory_profiler import memory_usage # noqa\nfrom datasets.enrico.get_data import get_dataloader # noqa\nfrom fusions.common_fusions import Concat # noqa\nfrom training_structures.unimodal import train, test # noqa\n\n\n\ndls, weights = get_dataloader('datasets/enrico/dataset')\ntraindata, validdata, testdata = dls\nmodalnum = 1\nencoder = VGG11Slim(16, dropout=True, dropoutp=0.2,\n freeze_features=True).cuda()\nhead = Linear(16, 20).cuda()\n# head = MLP(16, 32, 20, dropout=False).cuda()\n\nallmodules = [encoder, head]\n\n\ndef trainprocess():\n train(encoder, head, traindata, validdata, 50, optimtype=torch.optim.Adam,\n lr=0.0001, weight_decay=0, modalnum=modalnum)\n\n\nall_in_one_train(trainprocess, allmodules)\n\n\nmodel = torch.load('best.pt').cuda()\ntest(encoder, head, testdata, dataset='enrico', modalnum=modalnum)\n",
"from unimodals.common_models import GRU, MLP\nfrom get_data import get_dataloader\nfrom fusions.common_fusions import ConcatEarly\nfrom training_structures.Simple_Early_Fusion import train, test\nimport torch\nimport sys\nimport os\nsys.path.append(os.getcwd())\n\n\ntraindata, validdata, testdata = get_dataloader(\n '../affect/processed/humor_data.pkl')\n\n# humor 371 81 300\nencoders = GRU(752, 1128, dropout=True, has_padding=True).cuda()\nhead = MLP(1128, 512, 1).cuda()\n# encoders=[GRU(35,70,dropout=True,has_padding=True).cuda(), \\\n# GRU(74,150,dropout=True,has_padding=True).cuda(),\\\n# GRU(300,600,dropout=True,has_padding=True).cuda()]\n# head=MLP(820,400,1).cuda()\n\nfusion = ConcatEarly().cuda()\n\n# Support simple early_fusion and early_fusion with removing bias\ntrain(encoders, fusion, head, traindata, validdata, 1000, True, True,\n task=\"classification\", optimtype=torch.optim.AdamW, lr=1e-5, save='humor_ef_best.pt',\n weight_decay=0.01, criterion=torch.nn.MSELoss(), regularization=False)\n\nprint(\"Testing:\")\nmodel = torch.load('humor_ef_best.pt').cuda()\ntest(model, testdata, True, torch.nn.L1Loss(), \"classification\")\n# test(model,testdata,True,)\n",
"from unimodals.common_models import MLP, VGG16, MaxOut_MLP, Linear\nfrom robustness.all_in_one import general_train, general_test\nfrom get_data_robust import get_dataloader, get_dataloader_robust\nfrom fusions.common_fusions import Concat\nfrom training_structures.Contrastive_Learning import train, test\nimport torch\nimport sys\nimport os\nsys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))\n\n\nsys.path.append('/home/pliang/multibench/MultiBench/datasets/imdb')\n\ntraindata, validdata = get_dataloader(\n '../../../video/multimodal_imdb.hdf5', batch_size=128, vgg=True)\nrobustdata = get_dataloader_robust(\n '../../../video/mmimdb', '../../../video/multimodal_imdb.hdf5', batch_size=128)\n\nencoders = [MaxOut_MLP(512, 512, 300, linear_layer=False),\n MaxOut_MLP(512, 1024, 4096, 512, False)]\n#encoders=[MLP(300, 512, 512), MLP(4096, 1000, 512)]\n#encoders=[MLP(300, 512, 512), VGG16(512)]\nhead = Linear(1024, 23).cuda()\nrefiner = MLP(1024, 3072, 4396).cuda()\n#refiner = MLP(1024,2048,1024).cuda()\nfusion = Concat().cuda()\n\n\ndef trainprocess(filename):\n train(encoders, fusion, head, refiner, traindata, validdata, 1000, early_stop=True, task=\"multilabel\",\n save=filename, optimtype=torch.optim.AdamW, lr=1e-2, weight_decay=0.01, criterion=torch.nn.BCEWithLogitsLoss())\n\n\nfilename = general_train(trainprocess, 'mmimdb_contrast')\n\n\ndef testprocess(model, robustdata):\n return test(model, robustdata, criterion=torch.nn.BCEWithLogitsLoss(), task=\"multilabel\")\n\n\ngeneral_test(testprocess, filename, robustdata, multi_measure=True)\n",
"from private_test_scripts.all_in_one import all_in_one_train, all_in_one_test\nfrom objective_functions.recon import elbo_loss, sigmloss1dcentercrop\nfrom unimodals.MVAE import LeNetEncoder, DeLeNet\nfrom training_structures.MVAE_mixed import train_MVAE, test_MVAE\nfrom datasets.avmnist.get_data import get_dataloader\nimport torch\nfrom torch import nn\nfrom unimodals.common_models import MLP\nfrom fusions.MVAE import ProductOfExperts\nimport sys\nimport os\nsys.path.append(os.getcwd())\n\n\ntraindata, validdata, testdata = get_dataloader(\n '/data/yiwei/avmnist/_MFAS/avmnist')\n\nclasses = 10\nn_latent = 200\nfuse = ProductOfExperts((1, 40, n_latent))\n\n\nchannels = 6\nencoders = [LeNetEncoder(1, channels, 3, n_latent).cuda(\n), LeNetEncoder(1, channels, 5, n_latent).cuda()]\ndecoders = [DeLeNet(1, channels, 3, n_latent).cuda(),\n DeLeNet(1, channels, 5, n_latent).cuda()]\nhead = MLP(n_latent, 40, classes).cuda()\nelbo = elbo_loss([sigmloss1dcentercrop(28, 34),\n sigmloss1dcentercrop(112, 130)], [1.0, 1.0], 0.0)\n\n\ndef trpr():\n train_MVAE(encoders, decoders, head, fuse, traindata, validdata, elbo, 20)\n\n\n# all_in_one_train(trpr,[encoders[0],encoders[1],decoders[0],decoders[1],head])\nmvae = torch.load('best1.pt')\nhead = torch.load('best2.pt')\n\n\ndef tepr():\n test_MVAE(mvae, head, testdata)\n\n\nall_in_one_test(tepr, [encoders[0], encoders[1], head])\n",
"# NOTE dataloader needs to be implemented\n# Please use special/kinetics_gradient_blend.py for now\nimport sys\nimport os\nimport torch\nimport torchvision\n\nsys.path.append(os.getcwd())\n\nfrom unimodals.common_models import ResNetLSTMEnc, MLP\nfrom datasets.kinetics.get_data import get_dataloader\nfrom fusions.common_fusions import Concat\nfrom training_structures.gradient_blend import train, test\n\n\n\nfilename = 'best3.pt'\ntraindata, validdata, testdata = get_dataloader(sys.argv[1])\nr50 = torchvision.models.resnet50(pretrained=True)\nr50.conv1 = torch.nn.Conv2d(\n 1, 64, kernel_size=7, stride=2, padding=3, bias=False)\naudio_encoder = torch.nn.Sequential(r50, MLP(1000, 200, 64)).cuda()\nencoders = [ResNetLSTMEnc(64).cuda(), audio_encoder.cuda()]\nmult_head = MLP(64+64, 200, 5).cuda()\nuni_head = [MLP(64, 200, 5).cuda(), MLP(64, 200, 5).cuda()]\n\nfusion = Concat().cuda()\n\ntrain(encoders, mult_head, uni_head, fusion, traindata, validdata, 300,\n gb_epoch=10, optimtype=torch.optim.SGD, lr=0.01, savedir=filename)\n\nprint(\"Testing:\")\nmodel = torch.load(filename).cuda()\ntest(model, testdata)\n",
"# From https://github.com/brentyi/multimodalfilter/blob/master/scripts/push_task/train_push.py\n\nfrom private_test_scripts.all_in_one import all_in_one_train, all_in_one_test\nfrom training_structures.Supervised_Learning import train, test\nfrom fusions.common_fusions import ConcatWithLinear\nfrom unimodals.gentle_push.head import Head\nfrom unimodals.common_models import Sequential, Transpose, Reshape, MLP\nfrom robustness.all_in_one import general_train, general_test\nfrom datasets.gentle_push.data_loader import SubsequenceDataset, PushTask\nfrom torch.utils.data import DataLoader\nimport unimodals.gentle_push.layers as layers\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch\nimport fannypack\nimport datetime\nimport argparse\nimport sys\nimport os\nsys.path.insert(0, os.getcwd())\n\n\nTask = PushTask\nmodalities = ['gripper_pos']\n\n# Parse args\nparser = argparse.ArgumentParser()\nTask.add_dataset_arguments(parser)\nargs = parser.parse_args()\ndataset_args = Task.get_dataset_args(args)\n\nfannypack.data.set_cache_path('datasets/gentle_push/cache')\n\n# Load trajectories into memory\ntrain_trajectories = Task.get_train_trajectories(**dataset_args)\nval_trajectories = Task.get_eval_trajectories(**dataset_args)\nprop_robust_trajectories = Task.get_test_trajectories(\n prop_noise=True, **dataset_args)\n\ntrain_loader = DataLoader(\n SubsequenceDataset(train_trajectories, 16, modalities),\n batch_size=32,\n shuffle=True,\n drop_last=True,\n)\nval_loader = DataLoader(\n SubsequenceDataset(val_trajectories, 16, modalities),\n batch_size=32,\n shuffle=True,\n)\n\nprop_robust_loader = []\nfor i in range(len(prop_robust_trajectories)):\n prop_robust_loader.append(DataLoader(\n SubsequenceDataset(prop_robust_trajectories[i], 16, modalities),\n batch_size=32,\n shuffle=False,\n ))\n\nencoders = [\n Sequential(Transpose(0, 1), layers.observation_pos_layers(64)),\n]\nfusion = ConcatWithLinear(64, 64, concat_dim=2)\nhead = Sequential(Head(), Transpose(0, 1))\nallmodules = [*encoders, fusion, head]\noptimtype = optim.Adam\nloss_state = nn.MSELoss()\n\n\ndef trainprocess(filename):\n train(encoders, fusion, head,\n train_loader, val_loader,\n 20,\n task='regression',\n save=filename,\n optimtype=optimtype,\n objective=loss_state,\n lr=0.00001)\n\n\nfilename = general_train(trainprocess, 'gentle_push_unimodal_pos')\n\n\ndef testprocess(model, testdata):\n return test(model, testdata, task='regression', criterion=loss_state)\n\n\ngeneral_test(testprocess, filename, [prop_robust_loader])\n",
"from unimodals.common_models import LeNet, MLP, Constant\nimport torch\nfrom torch import nn\nfrom datasets.avmnist.get_data_robust import get_dataloader\nfrom fusions.common_fusions import Concat\nfrom training_structures.Simple_Late_Fusion import train, test\nimport sys\nimport os\nsys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))\n\ntraindata, validdata, testdata, robustdata = get_dataloader(\n '../../../../yiwei/avmnist/_MFAS/avmnist')\nchannels = 6\nencoders = [LeNet(1, channels, 3).cuda(), LeNet(1, channels, 5).cuda()]\nhead = MLP(channels*40, 100, 10).cuda()\n\nfusion = Concat().cuda()\n\ntrain(encoders, fusion, head, traindata, validdata, 30, optimtype=torch.optim.SGD,\n lr=0.1, weight_decay=0.0001, save='avmnist_simple_late_fusion_best.pt')\n\nmodel = torch.load('avmnist_simple_late_fusion_best.pt').cuda()\nprint(\"Testing:\")\ntest(model, robustdata)\n\nprint(\"Robustness testing:\")\ntest(model, testdata)\n",
"import torch\nimport sys\nimport os\nfrom torch.utils.data import DataLoader\n\nsys.path.append(os.getcwd())\n#r3d = torchvision.models.video.r3d_18(pretrained=True)\n# model=torch.nn.Sequential(r3d,torch.load('best1.pt')).cuda()\nmodel = torch.load('best2.pt').cuda()\noptim = torch.optim.Adam(model.parameters(), lr=0.0001)\ndatas = torch.load('/home/pliang/yiwei/kinetics_small/valid/batch0.pdt')\ncriterion = torch.nn.CrossEntropyLoss()\n\nepochs = 15\nvalid_dataloader = DataLoader(datas, shuffle=False, batch_size=45)\nbestvaloss = 1000\n# a=input()\nfor ep in range(epochs):\n totalloss = 0.0\n total = 0\n for i in range(24):\n print(\"epoch \"+str(ep)+\" subiter \"+str(i))\n datas = torch.load(\n '/home/pliang/yiwei/kinetics_small/train/batch'+str(i)+'.pdt')\n train_dataloader = DataLoader(datas, shuffle=True, batch_size=45)\n for j in train_dataloader:\n optim.zero_grad()\n out = model(j[0].cuda())\n \n loss = criterion(out, j[1].cuda())\n loss.backward()\n optim.step()\n totalloss += loss*len(j[0])\n total += len(j[0])\n print(\"Epoch \"+str(ep)+\" train loss: \"+str(totalloss/total))\n with torch.no_grad():\n total = 0\n correct = 0\n totalloss = 0.0\n for j in valid_dataloader:\n out = model(j[0].cuda())\n loss = criterion(out, j[1].cuda())\n totalloss += loss\n for ii in range(len(out)):\n total += 1\n if out[ii].tolist().index(max(out[ii])) == j[1][ii]:\n correct += 1\n valoss = totalloss/total\n print(\"Valid loss: \"+str(totalloss/total) +\n \" acc: \"+str(float(correct)/total))\n if valoss < bestvaloss:\n print(\"Saving best\")\n bestvaloss = valoss\n torch.save(model, 'best16.pt')\n\nprint('testing')\nvalid_dataloader = None\ndatas = torch.load('/home/pliang/yiwei/kinetics_small/test/batch0.pdt')\ntest_dataloader = DataLoader(datas, shuffle=False, batch_size=45)\nwith torch.no_grad():\n total = 0\n correct = 0\n totalloss = 0.0\n for j in test_dataloader:\n out = model(j[0].cuda())\n loss = criterion(out, j[1].cuda())\n totalloss += loss\n for ii in range(len(out)):\n total += 1\n if out[ii].tolist().index(max(out[ii])) == j[1][ii]:\n correct += 1\n print(\"Test loss: \"+str(totalloss/total) +\n \" acc: \"+str(float(correct)/total))\n",
"# From https://github.com/brentyi/multimodalfilter/blob/master/scripts/push_task/train_push.py\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch\nimport fannypack\nimport datetime\nimport argparse\nimport sys\nimport os\n\nsys.path.insert(0, os.getcwd())\n\nfrom training_structures.Supervised_Learning import train, test # noqa\nfrom fusions.common_fusions import ConcatWithLinear # noqa\nfrom unimodals.gentle_push.head import GentlePushLateLSTM # noqa\nfrom unimodals.common_models import Sequential, Transpose, Reshape, MLP, Identity # noqa\nfrom datasets.gentle_push.data_loader import PushTask # noqa\nimport unimodals.gentle_push.layers as layers # noqa\n\n\nTask = PushTask\n\n# Parse args\nparser = argparse.ArgumentParser()\nTask.add_dataset_arguments(parser)\nargs = parser.parse_args()\ndataset_args = Task.get_dataset_args(args)\n\nfannypack.data.set_cache_path('datasets/gentle_push/cache')\n\ntrain_loader, val_loader, test_loader = Task.get_dataloader(\n 16, batch_size=32, drop_last=True)\n\nencoders = [\n Sequential(Transpose(0, 1), layers.observation_pos_layers(\n 64), GentlePushLateLSTM(64, 256), Transpose(0, 1)),\n Sequential(Transpose(0, 1), layers.observation_sensors_layers(\n 64), GentlePushLateLSTM(64, 256), Transpose(0, 1)),\n Sequential(Transpose(0, 1), Reshape([-1, 1, 32, 32]), layers.observation_image_layers(\n 64), Reshape([16, -1, 64]), GentlePushLateLSTM(64, 256), Transpose(0, 1)),\n Sequential(Transpose(0, 1), layers.control_layers(64),\n GentlePushLateLSTM(64, 256), Transpose(0, 1)),\n]\nfusion = ConcatWithLinear(256 * 4, 2, concat_dim=2)\nhead = Identity()\noptimtype = optim.Adam\nloss_state = nn.MSELoss()\n\ntrain(encoders, fusion, head,\n train_loader, val_loader,\n 20,\n task='regression',\n optimtype=optimtype,\n objective=loss_state,\n lr=0.00001)\n\nmodel = torch.load('best.pt').cuda()\ntest(model, test_loader, dataset='gentle push',\n task='regression', criterion=loss_state)\n",
"from unimodals.common_models import LeNet, MLP, Constant\nimport torch\nfrom torch import nn\nfrom datasets.avmnist.get_data import get_dataloader\nfrom fusions.common_fusions import Concat\nfrom training_structures.Simple_Late_Fusion import train, test\nimport sys\nimport os\nsys.path.append(os.getcwd())\n\ntraindata, validdata, testdata = get_dataloader(\n '/data/yiwei/avmnist/_MFAS/avmnist')\nchannels = 6\nencoders = [LeNet(1, channels, 3).cuda(), LeNet(1, channels, 5).cuda()]\nhead = MLP(channels*40, 100, 10).cuda()\n\nfusion = Concat().cuda()\n\ntrain(encoders, fusion, head, traindata, validdata, 30,\n optimtype=torch.optim.SGD, lr=0.1, weight_decay=0.0001)\n\nprint(\"Testing:\")\nmodel = torch.load('best.pt').cuda()\ntest(model, testdata)\n"
] |
[
[
"torch.load"
],
[
"numpy.isnan",
"torch.utils.data.DataLoader",
"numpy.std",
"numpy.average",
"numpy.isinf"
],
[
"numpy.concatenate",
"numpy.array",
"torch.FloatTensor",
"numpy.zeros"
],
[
"numpy.random.choice",
"numpy.arange",
"numpy.random.random_sample",
"numpy.random.shuffle",
"numpy.ceil",
"numpy.random.normal",
"numpy.random.sample",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
],
[
"torch.nn.L1Loss"
],
[
"torch.load"
],
[
"torch.nn.MSELoss",
"torch.nn.L1Loss",
"torch.load"
],
[
"torch.nn.BCEWithLogitsLoss"
],
[
"torch.load"
],
[
"torch.nn.Conv2d",
"torch.load"
],
[
"torch.nn.MSELoss"
],
[
"torch.load"
],
[
"torch.nn.CrossEntropyLoss",
"torch.load",
"torch.utils.data.DataLoader",
"torch.no_grad",
"torch.save"
],
[
"torch.nn.MSELoss",
"torch.load"
],
[
"torch.load"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mehsoy/walltime-prediction-tools
|
[
"23e382b3d4a6c10b7ce05cefa99b8917c515f3b6",
"23e382b3d4a6c10b7ce05cefa99b8917c515f3b6",
"23e382b3d4a6c10b7ce05cefa99b8917c515f3b6"
] |
[
"helpers/tools.py",
"results-collection/tpot-collection/DAS2-fs2-2003-1.swf.gz.tpot.py",
"results-collection/tpot-collection/CTC-SP2-1995-2.swf.gz.tpot.py"
] |
[
"import glob, os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\ndef get_initial_df(workload):\n filename = \"workloads/\" + workload\n #if workload == \"SDSC\":\n # filename = \"workloads/SDSC.swf\"\n #if workload == \"CTC\":\n # filename = \"workloads/CTC.swf\"\n print(filename)\n df = pd.read_csv(filename, compression='gzip',\n sep=\"\\s+|\\t+|\\s+\\t+|\\t+\\s+\", comment=';',\n header = None,\n names=['JobId', \"SubmitTime\", 'WaitTime', 'RunTime','TaskCount', 'CPUTime',\n 'UsedMEM', 'TaskReq', 'ReqWallTime', 'RequestedMemory',\n 'Status', 'User', 'Group', 'Exe', 'Class', 'Partition',\n 'prejob', 'thinktime'],\n engine='python')\n #print(df.memory_usage(index=True, deep=False))\n return df\n\ndef get_tt_data(df):\n \"\"\"\n Returns training and test for given workload\n X_train, X_test are pandas dataframes\n\n y_* are 1d numpy array\n :param workload:\n :return: X_train, X_test, y_train, y_test\n \"\"\"\n\n\n\n # Drop fields\n df = df.drop('CPUTime', axis=1)\n df = df.drop('UsedMEM', axis=1)\n df = df.drop('Status', axis=1)\n\n\n df['User'] = df['User'].astype('category')\n df['Group'] = df['Group'].astype('category')\n df['Class'] = df['Class'].astype('category')\n df['Partition'] = df['Partition'].astype('category')\n # df['Status'] = df['Status'].astype('category')\n df['Exe'] = df['Exe'].astype('category')\n # dummy = df.to_numpy()\n\n y = df.pop('RunTime').values\n X_train, X_test, y_train, y_test = train_test_split(df, y, random_state=42)\n\n return X_train, X_test, y_train, y_test\n\ndef fix_times(workload,df):\n \"\"\"\n converting times back to timesteps and adding starttime\n :param workload: Name of the owrkload to pick right UnixstarTime. Extracted from swf file.\n df: swf loaded into pandas dataframe\n :return: df\n \"\"\"\n if workload == \"ANL-Intrepid-2009-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"CEA-Curie-2011-2.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"CIEMAT-Euler-2008-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"CTC-SP2-1995-2.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"CTC-SP2-1996-3.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"DAS2-fs0-2003-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"DAS2-fs1-2003-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"DAS2-fs2-2003-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"DAS2-fs3-2003-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"DAS2-fs4-2003-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"HPC2N-2002-2.2-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"Intel-NetbatchA-2012-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"Intel-NetbatchB-2012-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"Intel-NetbatchC-2012-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"Intel-NetbatchD-2012-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"KIT-FH2-2016-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"KTH-SP2-1996-2.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"LANL-CM5-1994-4.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"LANL-O2K-1999-2.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"LCG-2005-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"LLNL-Atlas-2006-2.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"LLNL-T3D-1996-2.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"LLNL-Thunder-2007-1.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"LLNL-uBGL-2006-2.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"LPC-EGEE-2004-1.2-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"METACENTRUM-2009-2.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"METACENTRUM-2013-3.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"NASA-iPSC-1993-3.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"OSC-Clust-2000-3.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"PIK-IPLEX-2009-1.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"RICC-2010-2.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"Sandia-Ross-2001-1.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"SDSC-BLUE-2000-4.2-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"SDSC-DS-2004-2.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"SDSC-Par-1995-3.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"SDSC-Par-1996-3.1-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"SDSC-SP2-1998-4.2-cln.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"SHARCNET-2005-2.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"SHARCNET-Whale-2006-2.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"UniLu-Gaia-2014-2.swf.gz\":\n UnixStartTime = 1231135224\n if workload == \"fh1_workload.swf.gz\":\n UnixStartTime = 1451615127\n\n df['SubmitTime'] = df['SubmitTime'] + UnixStartTime\n df['StartTime'] = df['SubmitTime'] + df['WaitTime']\n #df['SubmitTime'] = pd.to_datetime(df['SubmitTime'], unit='s')\n #df['StartTime'] = pd.to_datetime(df['StartTime'], unit='s')\n return df\n\ndef drop_large_workloads(workload_list):\n unwanted_workloads = set(['CIEMAT-Euler-2008-1.swf.gz',\n 'Intel-NetbatchA-2012-1.swf.gz',\n 'Intel-NetbatchB-2012-1.swf.gz',\n 'Intel-NetbatchC-2012-1.swf.gz',\n 'Intel-NetbatchD-2012-1.swf.gz',\n 'METACENTRUM-2013-3.swf.gz',\n 'SHARCNET-2005-2.swf.gz'\n ])\n workloads = [x for x in workload_list if x not in unwanted_workloads]\n return workloads\n\ndef mean_absolute_percentage_error(y_true, y_pred):\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n y_true_zeros = np.nonzero(y_true == 0)[0]\n y_pred_zeros = np.nonzero(y_pred == 0)[0]\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\ndef MASE(training_series, testing_series, prediction_series):\n \"\"\"\n Computes the MEAN-ABSOLUTE SCALED ERROR forcast error for univariate time series prediction.\n\n See \"Another look at measures of forecast accuracy\", Rob J Hyndman\n\n parameters:\n training_series: the series used to train the model, 1d numpy array\n testing_series: the test series to predict, 1d numpy array or float\n prediction_series: the prediction of testing_series, 1d numpy array (same size as testing_series) or float\n absolute: \"squares\" to use sum of squares and root the result, \"absolute\" to use absolute values.\n\n \"\"\"\n print\n \"Needs to be tested.\"\n n = training_series.shape[0]\n d = np.abs(np.diff(training_series)).sum() / (n - 1)\n\n errors = np.abs(testing_series - prediction_series)\n return errors.mean() / d\n\ndef walltime_lambda_deviation(y_true, y_pred, y_request):\n \"\"\"\n Computes the lambda deviation\n\n Mehmet Soysal\n\n parameters:\n y_true: true values wall clock time a.k.a real run-time of the jobs\n y_pred: predicted wall time values\n y_request: requested wall time by the user (a.k.a useless estimates by the user ;) )\n returns: numpy array lambda values\n\n \"\"\"\n walltime_lam = np.abs(y_pred - y_true).mean() / np.abs(y_request - y_true).mean()\n\n\n return walltime_lam\n\ndef split_dates(df, column):\n hour_of_day = range(0, 24)\n day_of_week = range(0,7)\n\n if column == \"SubmitTime\":\n #df['Day_SubmitTime'] = pd.DatetimeIndex(pd.to_datetime(df[column],unit='s')).day\n #df['day_of_week'] = pd.Series(day_of_week, dtype=\"category\")\n df['SubmitTime_TS'] = df['SubmitTime'].copy()\n df['SubmitTime'] = pd.to_datetime(df['SubmitTime'], unit='s')\n df['Weekday_SubmitTime'] = pd.Categorical(pd.Series(pd.DatetimeIndex(pd.to_datetime(df[column],unit='s')).weekday, dtype=\"category\") , categories=day_of_week)\n df['Hour_SubmitTime'] = pd.Categorical(pd.Series(pd.DatetimeIndex(pd.to_datetime(df[column],unit='s')).hour, dtype=\"category\") , categories=hour_of_day)\n if column == \"StartTime\":\n df['StartTime_TS'] = df['StartTime'].copy()\n df['StartTime'] = pd.to_datetime(df['StartTime'], unit='s')\n df['Weekday_StartTime'] = pd.Categorical(pd.Series(pd.DatetimeIndex(pd.to_datetime(df[column],unit='s')).weekday, dtype=\"category\") , categories=day_of_week)\n df['Hour_StartTime'] = pd.Categorical(pd.Series(pd.DatetimeIndex(pd.to_datetime(df[column],unit='s')).hour, dtype=\"category\") , categories=hour_of_day)\n\n\n return df\n\ndef get_all_workloads():\n #os.chdir(\"workloads/\")\n\n workloads =[]\n for file in glob.glob(\"workloads/*.gz\"):\n workloads.append(file.split(\"/\")[1])\n # workloads = [\"ANL-Intrepid-2009-1.swf.gz\",\"CEA-Curie-2011-2.1-cln.swf.gz\",\"CIEMAT-Euler-2008-1.swf.gz\",\n # \"CTC-SP2-1995-2.swf.gz\",\"CTC-SP2-1996-3.1-cln.swf.gz\",\"DAS2-fs0-2003-1.swf.gz\",\n # \"DAS2-fs1-2003-1.swf.gz\",\"DAS2-fs2-2003-1.swf.gz\",\"DAS2-fs3-2003-1.swf.gz\",\n # \"DAS2-fs4-2003-1.swf.gz\",\"HPC2N-2002-2.2-cln.swf.gz\",\"Intel-NetbatchA-2012-1.swf.gz\",\n # \"Intel-NetbatchB-2012-1.swf.gz\",\"Intel-NetbatchC-2012-1.swf.gz\",\"Intel-NetbatchD-2012-1.swf.gz\",\n # \"KIT-FH2-2016-1.swf.gz\",\"KTH-SP2-1996-2.1-cln.swf.gz\",\"LANL-CM5-1994-4.1-cln.swf.gz\",\n # \"LANL-O2K-1999-2.swf.gz\",\"LCG-2005-1.swf.gz\",\"LLNL-Atlas-2006-2.1-cln.swf.gz\",\n # \"LLNL-T3D-1996-2.swf.gz\",\"LLNL-Thunder-2007-1.1-cln.swf.gz\",\"LLNL-uBGL-2006-2.swf.gz\",\n # \"LPC-EGEE-2004-1.2-cln.swf.gz\",\"METACENTRUM-2009-2.swf.gz\",\"METACENTRUM-2013-3.swf.gz\",\n # \"NASA-iPSC-1993-3.1-cln.swf.gz\",\"OSC-Clust-2000-3.1-cln.swf.gz\",\"PIK-IPLEX-2009-1.swf.gz\",\n # \"RICC-2010-2.swf.gz\",\"Sandia-Ross-2001-1.1-cln.swf.gz\",\"SDSC-BLUE-2000-4.2-cln.swf.gz\",\n # \"SDSC-DS-2004-2.1-cln.swf.gz\",\"SDSC-Par-1995-3.1-cln.swf.gz\",\"SDSC-Par-1996-3.1-cln.swf.gz\",\n # \"SDSC-SP2-1998-4.2-cln.swf.gz\",\"SHARCNET-2005-2.swf.gz\",\"SHARCNET-Whale-2006-2.swf.gz\",\n # \"UniLu-Gaia-2014-2.swf.gz\"]\n\n return workloads\n\n\ndef coeff_determination(y_true, y_pred):\n from keras import backend as K\n SS_res = K.sum(K.square( y_true-y_pred ))\n SS_tot = K.sum(K.square( y_true - K.mean(y_true) ) )\n return ( 1 - SS_res/(SS_tot + K.epsilon()) )\n\ndef my_r2_score(y_true, y_pred):\n ssres = np.sum(np.square(y_true - y_pred))\n sstot = np.sum(np.square(y_true - np.mean(y_true)))\n return 1 - ssres / sstot\n\n",
"import numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import ElasticNetCV, RidgeCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.pipeline import make_pipeline, make_union\nfrom sklearn.tree import DecisionTreeRegressor\nfrom tpot.builtins import StackingEstimator\n\n# NOTE: Make sure that the class is labeled 'target' in the data file\ntpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64)\nfeatures = tpot_data.drop('target', axis=1).values\ntraining_features, testing_features, training_target, testing_target = \\\n train_test_split(features, tpot_data['target'].values, random_state=None)\n\n# Average CV score on the training set was:-467.1549141263793\nexported_pipeline = make_pipeline(\n StackingEstimator(estimator=RidgeCV()),\n StackingEstimator(estimator=DecisionTreeRegressor(max_depth=8, min_samples_leaf=5, min_samples_split=18)),\n StackingEstimator(estimator=ElasticNetCV(l1_ratio=0.9500000000000001, tol=0.0001)),\n StackingEstimator(estimator=KNeighborsRegressor(n_neighbors=14, p=1, weights=\"distance\")),\n KNeighborsRegressor(n_neighbors=1, p=1, weights=\"distance\")\n)\n\nexported_pipeline.fit(training_features, training_target)\nresults = exported_pipeline.predict(testing_features)\n",
"import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor\nfrom sklearn.linear_model import ElasticNetCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import make_pipeline, make_union\nfrom tpot.builtins import StackingEstimator\n\n# NOTE: Make sure that the class is labeled 'target' in the data file\ntpot_data = pd.read_csv('PATH/TO/DATA/FILE', sep='COLUMN_SEPARATOR', dtype=np.float64)\nfeatures = tpot_data.drop('target', axis=1).values\ntraining_features, testing_features, training_target, testing_target = \\\n train_test_split(features, tpot_data['target'].values, random_state=None)\n\n# Average CV score on the training set was:-6272.049750287444\nexported_pipeline = make_pipeline(\n StackingEstimator(estimator=RandomForestRegressor(bootstrap=False, max_features=0.4, min_samples_leaf=8, min_samples_split=10, n_estimators=100)),\n StackingEstimator(estimator=ElasticNetCV(l1_ratio=0.45, tol=0.0001)),\n GradientBoostingRegressor(alpha=0.75, learning_rate=0.5, loss=\"lad\", max_depth=5, max_features=0.25, min_samples_leaf=4, min_samples_split=18, n_estimators=100, subsample=0.7500000000000001)\n)\n\nexported_pipeline.fit(training_features, training_target)\nresults = exported_pipeline.predict(testing_features)\n"
] |
[
[
"numpy.square",
"pandas.read_csv",
"pandas.to_datetime",
"numpy.abs",
"numpy.nonzero",
"sklearn.model_selection.train_test_split",
"numpy.mean",
"numpy.diff",
"numpy.array"
],
[
"pandas.read_csv",
"sklearn.tree.DecisionTreeRegressor",
"sklearn.linear_model.ElasticNetCV",
"sklearn.model_selection.train_test_split",
"sklearn.neighbors.KNeighborsRegressor",
"sklearn.linear_model.RidgeCV"
],
[
"sklearn.ensemble.RandomForestRegressor",
"pandas.read_csv",
"sklearn.linear_model.ElasticNetCV",
"sklearn.model_selection.train_test_split",
"sklearn.ensemble.GradientBoostingRegressor"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
abitrolly/lightwood
|
[
"ee0c095f594c5d491196401b59344702f346bc9c"
] |
[
"lightwood/encoders/image/helpers/img_to_vec.py"
] |
[
"import torch\r\nimport torch.nn as nn\r\nimport torchvision.models as models\r\nimport torchvision.transforms as transforms\r\n\r\nclass ChannelPoolAdaptiveAvg1d(torch.nn.AdaptiveAvgPool1d):\r\n def forward(self, input):\r\n n, c = input.size()\r\n input = input.view(n,c,1).permute(0,2,1)\r\n pooled = torch.nn.functional.adaptive_avg_pool1d(input, self.output_size)\r\n _, _, c = pooled.size()\r\n pooled = pooled.permute(0,2,1)\r\n return pooled.view(n,c)\r\n\r\nclass Img2Vec():\r\n\r\n def __init__(self, cuda=False, model='resnet-18', layer='default', layer_output_size=512):\r\n \"\"\" Img2Vec\r\n :param cuda: If set to True, will run forward pass on GPU\r\n :param model: String name of requested model\r\n :param layer: String or Int depending on model. See more docs: https://github.com/christiansafka/img2vec.git\r\n :param layer_output_size: Int depicting the output size of the requested layer\r\n \"\"\"\r\n self.device = torch.device(\"cuda\" if cuda else \"cpu\")\r\n self.layer_output_size = layer_output_size\r\n self.model_name = model\r\n\r\n self.model, self.extraction_layer = self._get_model_and_layer(model, layer)\r\n\r\n self.model = self.model.to(self.device)\r\n\r\n self.model.eval()\r\n\r\n self.scaler = transforms.Scale((224, 224))\r\n self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\r\n std=[0.229, 0.224, 0.225])\r\n self.to_tensor = transforms.ToTensor()\r\n\r\n def get_vec(self, img, tensor=False):\r\n \"\"\" Get vector embedding from PIL image\r\n :param img: PIL Image\r\n :param tensor: If True, get_vec will return a FloatTensor instead of Numpy array\r\n :returns: Numpy ndarray\r\n \"\"\"\r\n image = self.normalize(self.to_tensor(self.scaler(img))).unsqueeze(0).to(self.device)\r\n\r\n if self.model_name in ('alexnet', 'mobilenet', 'resnext-50-small'):\r\n my_embedding = torch.zeros(1, self.layer_output_size)\r\n elif self.model_name in ('resnet-18', 'resnext-50'):\r\n my_embedding = torch.zeros(1, self.layer_output_size)\r\n\r\n def copy_data(m, i, o):\r\n my_embedding.copy_(o.data)\r\n\r\n h = self.extraction_layer.register_forward_hook(copy_data)\r\n h_x = self.model(image)\r\n h.remove()\r\n\r\n if tensor:\r\n return my_embedding\r\n else:\r\n if self.model_name in ('alexnet', 'mobilenet', 'resnext-50-small'):\r\n return my_embedding.numpy()[0, :]\r\n elif self.model_name in ('resnet-18', 'resnext-50'):\r\n return my_embedding.numpy()[0, :, 0, 0]\r\n\r\n def _get_model_and_layer(self, model_name, layer):\r\n \"\"\" Internal method for getting layer from model\r\n :param model_name: model name such as 'resnet-18'\r\n :param layer: layer as a string for resnet-18 or int for alexnet\r\n :returns: pytorch model, selected layer\r\n \"\"\"\r\n\r\n if model_name == 'resnext-50-small':\r\n model = models.resnext50_32x4d(pretrained=True)\r\n if layer == 'default':\r\n #b = torch.nn.AvgPool2d(kernel_size=(8,8),stride=(4,4))\r\n #a = torch.nn.AvgPool2d(kernel_size=(2,2),stride=2)\r\n #model.avgpool = b\r\n #model.fc = nn.Identity()\r\n #layer = model.avgpool\r\n model.fc = ChannelPoolAdaptiveAvg1d(output_size=512)\r\n layer = model.fc\r\n self.layer_output_size = 512\r\n else:\r\n layer = model._modules.get(layer)\r\n\r\n return model, layer\r\n\r\n if model_name == 'resnext-50':\r\n model = models.resnext50_32x4d(pretrained=True)\r\n if layer == 'default':\r\n layer = model._modules.get('avgpool')\r\n self.layer_output_size = 2048\r\n else:\r\n layer = model._modules.get(layer)\r\n\r\n return model, layer\r\n\r\n if model_name == 'resnet-18':\r\n model = models.resnet18(pretrained=True)\r\n if layer == 'default':\r\n layer = model._modules.get('avgpool')\r\n self.layer_output_size = 512\r\n else:\r\n layer = model._modules.get(layer)\r\n\r\n return model, layer\r\n\r\n # @TODO: Fix or remove, this is both slow and inaccurate, not sure where we'd use it\r\n if model_name == 'alexnet':\r\n model = models.alexnet(pretrained=True)\r\n if layer == 'default':\r\n layer = model.classifier[-2]\r\n self.layer_output_size = 4096\r\n else:\r\n layer = model.classifier[-layer]\r\n\r\n return model, layer\r\n\r\n # @TODO: Fix or remove, this is slow and not quite as accurate as resnet18, it's a failed experiment trying to end the encoder with the output from an FC rather than output from the pooling layer, might work on it later, if 1 month from now it stays the same, just remove it\r\n if model_name == 'mobilenet':\r\n model = models.mobilenet_v2(pretrained=True)\r\n if layer == 'default':\r\n layer = model._modules.get('classifier')\r\n self.layer_output_size = 1000\r\n else:\r\n layer = model._modules.get(layer)\r\n\r\n return model, layer\r\n\r\n else:\r\n raise KeyError('Model %s was not found' % model_name)\r\n"
] |
[
[
"torch.nn.functional.adaptive_avg_pool1d",
"torch.device",
"torch.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
puat133/MCMC-MultiSPDE
|
[
"2beca39f32c0cdd7664baeacd495b193850d8e7d"
] |
[
"Legacy/optimizerTest.py"
] |
[
"import numpy as np\nimport numba as nb\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport importlib\n# from numba.typed import List\n# from numba.typed import List\nimport mcmc.util as util\nimport mcmc.fourier as fourier\nimport mcmc.L as L\nimport mcmc.layer as layer\nimport mcmc.randomGenerator as randomGenerator\nimport mcmc.pCN as pCN\nimport mcmc.measurement as meas\nimport mcmc.optimizer as optm\nimport mcmc.simulationResults as simRes\n# import scipy as scp\nimport time\n\nn_layers=2\nn_samples = 100000\nn = 2**6\nbeta = 1\nnum = 8*n\nkappa = 1e17\nsigma_0 = 5e6\nsigma_v = 1e2\nsigma_scaling= 1e-8\nevaluation_interval = 50\nprintProgress=True\nseed=1\nburn_percentage = 50.0\nd = 1\nnu = 2 - d/2\nalpha = nu + d/2\nt_start = 0.0\nt_end = 1.0\nbeta_0 = (sigma_0**2)*(2**d * np.pi**(d/2))* 1.1283791670955126#<-- this numerical value is scp.special.gamma(alpha))/scp.special.gamma(nu)\nbeta_v = beta_0*(sigma_v/sigma_0)**2\nsqrtBeta_v = np.sqrt(beta_v)\nsqrtBeta_0 = np.sqrt(beta_0)\n\nf = fourier.FourierAnalysis(n,num,t_start,t_end)\n# self.fourier = f\n\nrandom_gen = randomGenerator.RandomGenerator(f.fourier_basis_number)\n# self.random_gen = rg\n\n\nLuReal = (1/sqrtBeta_0)*(f.Dmatrix*kappa**(-nu) - kappa**(2-nu)*f.Imatrix)\nLu = LuReal + 1j*np.zeros(LuReal.shape)\n\nuStdev = -1/np.diag(Lu)\nuStdev = uStdev[f.fourier_basis_number-1:]\nuStdev[0] /= 2 #scaled\n\nmeas_std = 0.1\nmeasurement = meas.Measurement(num,meas_std,t_start,t_end)\n# pcn = pCN.pCN(n_layers,rg,measurement,f,beta)\npcn = pCN.pCN(n_layers,random_gen,measurement,f,beta)\n\n\n#initialize Layers\n# n_layers = 2\n# Layers = List()\ntyped_list_status = importlib.util.find_spec('numba.typed.typedlist')\nif typed_list_status is None:\n Layers = []\nelse:\n from numba.typed.typedlist import List\n Layers = List()\n# factor = 1e-8\nfor i in range(n_layers):\n if i==0:\n init_sample = np.linalg.solve(Lu,random_gen.construct_w())[f.fourier_basis_number-1:]\n lay = layer.Layer(True,sqrtBeta_0,i,n_samples,pcn,init_sample)\n lay.stdev = uStdev\n lay.current_sample_scaled_norm = util.norm2(lay.current_sample/lay.stdev)#ToDO: Modify this\n lay.new_sample_scaled_norm = lay.current_sample_scaled_norm\n else:\n \n if i == n_layers-1:\n \n lay = layer.Layer(False,sqrtBeta_v,i,n_samples,pcn,Layers[i-1].current_sample)\n wNew = pcn.random_gen.construct_w()\n eNew = np.random.randn(pcn.measurement.num_sample)\n wBar = np.concatenate((eNew,wNew))\n \n LBar = np.vstack((pcn.H,lay.LMat.current_L))\n\n #update v\n lay.current_sample_symmetrized, res, rnk, s = np.linalg.lstsq(LBar,pcn.yBar-wBar,rcond=-1)#,rcond=None)\n lay.current_sample = lay.current_sample_symmetrized[pcn.fourier.fourier_basis_number-1:]\n else:\n lay = layer.Layer(False,sqrtBeta_v*np.sqrt(sigma_scaling),i,n_samples,pcn,Layers[i-1].current_sample)\n lay.update_current_sample()\n #TODO: toggle this if pcn.one_step_one_element is not used\n # lay.samples_history = np.empty((lay.n_samples*f.fourier_basis_number, f.fourier_basis_number), dtype=np.complex128)\n\n Layers.append(lay)\n\n\n#allowable methods: ‘Nelder-Mead’,‘Powell’,‘COBYLA’,‘trust-constr’, '‘L-BFGS-B'\nmethod = 'L-BFGS-B'\noptimizer = optm.Optimizer(Layers,method=method,max_iter=1000000)\nopt_Result = optimizer.optimize()\nuHalf_all = optm.xToUHalf(opt_Result.x)\nLayers[0].new_sample = uHalf_all[0:n]\nLayers[0].update_current_sample()\nfor i in range(1,len(Layers)):\n if i== len(Layers)-1:\n wNew = util.symmetrize(uHalf_all[n*(i-1):n*i])\n eNew = np.random.randn(Layers[i].pcn.measurement.num_sample)\n wBar = np.concatenate((eNew,wNew))\n \n LBar = np.vstack((Layers[i].pcn.H,Layers[i].LMat.current_L))\n Layers[i].new_sample_symmetrized, res, rnk, s = np.linalg.lstsq(LBar,Layers[i].pcn.yBar-wBar )#,rcond=None)\n Layers[i].new_sample = Layers[i].new_sample_symmetrized[Layers[i].pcn.fourier.fourier_basis_number-1:]\n else:\n uHalf_i = uHalf_all[n*(i-1):n*i]\n Layers[i].new_sample = uHalf_i\n Layers[i].new_sample = uHalf_all[n*(i-1):i*n]\n Layers[i].update_current_sample()\n # negLogPost += 0.5*Layers[i].current_sample_scaled_norm\n # negLogPost -= Layers[i].current_log_L_det\nplt.figure()\nplt.plot(measurement.t,f.inverseFourierLimited(Layers[-1].current_sample))\nplt.figure()\nplt.plot(measurement.t,np.exp(-f.inverseFourierLimited(Layers[0].current_sample)))\nplt.show()"
] |
[
[
"numpy.diag",
"numpy.sqrt",
"numpy.concatenate",
"numpy.linalg.lstsq",
"numpy.random.randn",
"matplotlib.pyplot.show",
"numpy.zeros",
"numpy.vstack",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
vikatelis/baselines
|
[
"668abf167f54317dca7795588c61f1055a4d017f"
] |
[
"baselines/a2c/utils.py"
] |
[
"import os\nimport numpy as np\nimport tensorflow as tf\nfrom collections import deque\n\ndef sample(logits):\n noise = tf.random_uniform(tf.shape(logits))\n return tf.argmax(logits - tf.log(-tf.log(noise)), 1)\n\ndef cat_entropy(logits):\n a0 = logits - tf.reduce_max(logits, 1, keepdims=True)\n ea0 = tf.exp(a0)\n z0 = tf.reduce_sum(ea0, 1, keepdims=True)\n p0 = ea0 / z0\n return tf.reduce_sum(p0 * (tf.log(z0) - a0), 1)\n\ndef cat_entropy_softmax(p0):\n return - tf.reduce_sum(p0 * tf.log(p0 + 1e-6), axis = 1)\n\ndef ortho_init(scale=1.0):\n def _ortho_init(shape, dtype, partition_info=None):\n #lasagne ortho init for tf\n shape = tuple(shape)\n if len(shape) == 2:\n flat_shape = shape\n elif len(shape) == 4: # assumes NHWC\n flat_shape = (np.prod(shape[:-1]), shape[-1])\n else:\n raise NotImplementedError\n a = np.random.normal(0.0, 1.0, flat_shape)\n u, _, v = np.linalg.svd(a, full_matrices=False)\n q = u if u.shape == flat_shape else v # pick the one with the correct shape\n q = q.reshape(shape)\n return (scale * q[:shape[0], :shape[1]]).astype(np.float32)\n return _ortho_init\n\ndef conv(x, scope, *, nf, rf, stride, pad='VALID', init_scale=1.0, data_format='NHWC', one_dim_bias=False):\n if data_format == 'NHWC':\n channel_ax = 3\n strides = [1, stride, stride, 1]\n bshape = [1, 1, 1, nf]\n elif data_format == 'NCHW':\n channel_ax = 1\n strides = [1, 1, stride, stride]\n bshape = [1, nf, 1, 1]\n else:\n raise NotImplementedError\n bias_var_shape = [nf] if one_dim_bias else [1, nf, 1, 1]\n nin = x.get_shape()[channel_ax].value\n wshape = [rf, rf, nin, nf]\n with tf.variable_scope(scope):\n w = tf.get_variable(\"w\", wshape, initializer=ortho_init(init_scale))\n b = tf.get_variable(\"b\", bias_var_shape, initializer=tf.constant_initializer(0.0))\n if not one_dim_bias and data_format == 'NHWC':\n b = tf.reshape(b, bshape)\n return tf.nn.conv2d(x, w, strides=strides, padding=pad, data_format=data_format) + b\n\ndef fc(x, scope, nh, *, init_scale=1.0, init_bias=0.0):\n with tf.variable_scope(scope):\n nin = x.get_shape()[1].value\n w = tf.get_variable(\"w\", [nin, nh], initializer=ortho_init(init_scale))\n print(\"w is \"+str(w))\n b = tf.get_variable(\"b\", [nh], initializer=tf.constant_initializer(init_bias))\n return tf.matmul(x, w)+b\n\ndef batch_to_seq(h, nbatch, nsteps, flat=False):\n if flat:\n h = tf.reshape(h, [nbatch, nsteps])\n else:\n h = tf.reshape(h, [nbatch, nsteps, -1])\n return [tf.squeeze(v, [1]) for v in tf.split(axis=1, num_or_size_splits=nsteps, value=h)]\n\ndef seq_to_batch(h, flat = False):\n shape = h[0].get_shape().as_list()\n if not flat:\n assert(len(shape) > 1)\n nh = h[0].get_shape()[-1].value\n return tf.reshape(tf.concat(axis=1, values=h), [-1, nh])\n else:\n return tf.reshape(tf.stack(values=h, axis=1), [-1])\n\ndef lstm(xs, ms, s, scope, nh, init_scale=1.0):\n nbatch, nin = [v.value for v in xs[0].get_shape()]\n with tf.variable_scope(scope):\n wx = tf.get_variable(\"wx\", [nin, nh*4], initializer=ortho_init(init_scale))\n wh = tf.get_variable(\"wh\", [nh, nh*4], initializer=ortho_init(init_scale))\n b = tf.get_variable(\"b\", [nh*4], initializer=tf.constant_initializer(0.0))\n\n c, h = tf.split(axis=1, num_or_size_splits=2, value=s)\n for idx, (x, m) in enumerate(zip(xs, ms)):\n c = c*(1-m)\n h = h*(1-m)\n z = tf.matmul(x, wx) + tf.matmul(h, wh) + b\n i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z)\n i = tf.nn.sigmoid(i)\n f = tf.nn.sigmoid(f)\n o = tf.nn.sigmoid(o)\n u = tf.tanh(u)\n c = f*c + i*u\n h = o*tf.tanh(c)\n xs[idx] = h\n s = tf.concat(axis=1, values=[c, h])\n return xs, s\n\ndef _ln(x, g, b, e=1e-5, axes=[1]):\n u, s = tf.nn.moments(x, axes=axes, keep_dims=True)\n x = (x-u)/tf.sqrt(s+e)\n x = x*g+b\n return x\n\ndef lnlstm(xs, ms, s, scope, nh, init_scale=1.0):\n nbatch, nin = [v.value for v in xs[0].get_shape()]\n with tf.variable_scope(scope):\n wx = tf.get_variable(\"wx\", [nin, nh*4], initializer=ortho_init(init_scale))\n gx = tf.get_variable(\"gx\", [nh*4], initializer=tf.constant_initializer(1.0))\n bx = tf.get_variable(\"bx\", [nh*4], initializer=tf.constant_initializer(0.0))\n\n wh = tf.get_variable(\"wh\", [nh, nh*4], initializer=ortho_init(init_scale))\n gh = tf.get_variable(\"gh\", [nh*4], initializer=tf.constant_initializer(1.0))\n bh = tf.get_variable(\"bh\", [nh*4], initializer=tf.constant_initializer(0.0))\n\n b = tf.get_variable(\"b\", [nh*4], initializer=tf.constant_initializer(0.0))\n\n gc = tf.get_variable(\"gc\", [nh], initializer=tf.constant_initializer(1.0))\n bc = tf.get_variable(\"bc\", [nh], initializer=tf.constant_initializer(0.0))\n\n c, h = tf.split(axis=1, num_or_size_splits=2, value=s)\n for idx, (x, m) in enumerate(zip(xs, ms)):\n c = c*(1-m)\n h = h*(1-m)\n z = _ln(tf.matmul(x, wx), gx, bx) + _ln(tf.matmul(h, wh), gh, bh) + b\n i, f, o, u = tf.split(axis=1, num_or_size_splits=4, value=z)\n i = tf.nn.sigmoid(i)\n f = tf.nn.sigmoid(f)\n o = tf.nn.sigmoid(o)\n u = tf.tanh(u)\n c = f*c + i*u\n h = o*tf.tanh(_ln(c, gc, bc))\n xs[idx] = h\n s = tf.concat(axis=1, values=[c, h])\n return xs, s\n\ndef conv_to_fc(x):\n nh = np.prod([v.value for v in x.get_shape()[1:]])\n x = tf.reshape(x, [-1, nh])\n return x\n\ndef discount_with_dones(rewards, dones, gamma):\n discounted = []\n r = 0\n for reward, done in zip(rewards[::-1], dones[::-1]):\n r = reward + gamma*r*(1.-done) # fixed off by one bug\n discounted.append(r)\n return discounted[::-1]\n\ndef find_trainable_variables(key):\n return tf.trainable_variables(key)\n\ndef make_path(f):\n return os.makedirs(f, exist_ok=True)\n\ndef constant(p):\n return 1\n\ndef linear(p):\n return 1-p\n\ndef middle_drop(p):\n eps = 0.75\n if 1-p<eps:\n return eps*0.1\n return 1-p\n\ndef double_linear_con(p):\n p *= 2\n eps = 0.125\n if 1-p<eps:\n return eps\n return 1-p\n\ndef double_middle_drop(p):\n eps1 = 0.75\n eps2 = 0.25\n if 1-p<eps1:\n if 1-p<eps2:\n return eps2*0.5\n return eps1*0.1\n return 1-p\n\nschedules = {\n 'linear':linear,\n 'constant':constant,\n 'double_linear_con': double_linear_con,\n 'middle_drop': middle_drop,\n 'double_middle_drop': double_middle_drop\n}\n\nclass Scheduler(object):\n\n def __init__(self, v, nvalues, schedule):\n self.n = 0.\n self.v = v\n self.nvalues = nvalues\n self.schedule = schedules[schedule]\n\n def value(self):\n current_value = self.v*self.schedule(self.n/self.nvalues)\n self.n += 1.\n return current_value\n\n def value_steps(self, steps):\n return self.v*self.schedule(steps/self.nvalues)\n\n\nclass EpisodeStats:\n def __init__(self, nsteps, nenvs):\n self.episode_rewards = []\n for i in range(nenvs):\n self.episode_rewards.append([])\n self.lenbuffer = deque(maxlen=40) # rolling buffer for episode lengths\n self.rewbuffer = deque(maxlen=40) # rolling buffer for episode rewards\n self.nsteps = nsteps\n self.nenvs = nenvs\n\n def feed(self, rewards, masks):\n rewards = np.reshape(rewards, [self.nenvs, self.nsteps])\n masks = np.reshape(masks, [self.nenvs, self.nsteps])\n for i in range(0, self.nenvs):\n for j in range(0, self.nsteps):\n self.episode_rewards[i].append(rewards[i][j])\n if masks[i][j]:\n l = len(self.episode_rewards[i])\n s = sum(self.episode_rewards[i])\n self.lenbuffer.append(l)\n self.rewbuffer.append(s)\n self.episode_rewards[i] = []\n\n def mean_length(self):\n if self.lenbuffer:\n return np.mean(self.lenbuffer)\n else:\n return 0 # on the first params dump, no episodes are finished\n\n def mean_reward(self):\n if self.rewbuffer:\n return np.mean(self.rewbuffer)\n else:\n return 0\n\n\n# For ACER\ndef get_by_index(x, idx):\n assert(len(x.get_shape()) == 2)\n assert(len(idx.get_shape()) == 1)\n idx_flattened = tf.range(0, x.shape[0]) * x.shape[1] + idx\n y = tf.gather(tf.reshape(x, [-1]), # flatten input\n idx_flattened) # use flattened indices\n return y\n\ndef check_shape(ts,shapes):\n i = 0\n for (t,shape) in zip(ts,shapes):\n assert t.get_shape().as_list()==shape, \"id \" + str(i) + \" shape \" + str(t.get_shape()) + str(shape)\n i += 1\n\ndef avg_norm(t):\n return tf.reduce_mean(tf.sqrt(tf.reduce_sum(tf.square(t), axis=-1)))\n\ndef gradient_add(g1, g2, param):\n print([g1, g2, param.name])\n assert (not (g1 is None and g2 is None)), param.name\n if g1 is None:\n return g2\n elif g2 is None:\n return g1\n else:\n return g1 + g2\n\ndef q_explained_variance(qpred, q):\n _, vary = tf.nn.moments(q, axes=[0, 1])\n _, varpred = tf.nn.moments(q - qpred, axes=[0, 1])\n check_shape([vary, varpred], [[]] * 2)\n return 1.0 - (varpred / vary)\n"
] |
[
[
"tensorflow.concat",
"tensorflow.reduce_sum",
"tensorflow.stack",
"tensorflow.tanh",
"numpy.mean",
"tensorflow.nn.conv2d",
"numpy.linalg.svd",
"numpy.reshape",
"tensorflow.nn.moments",
"tensorflow.squeeze",
"tensorflow.square",
"tensorflow.trainable_variables",
"tensorflow.matmul",
"tensorflow.nn.sigmoid",
"tensorflow.shape",
"tensorflow.exp",
"tensorflow.split",
"tensorflow.reduce_max",
"tensorflow.range",
"tensorflow.reshape",
"tensorflow.constant_initializer",
"numpy.random.normal",
"tensorflow.log",
"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"
]
}
] |
PoCFrance/security-pool-2018
|
[
"acabc082808ade8ceccc395736a337059c0650de"
] |
[
"ai/corrections/ml_d01/ex04.py"
] |
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.linspace(-5, 3, 30)\ny = 1 + np.exp(-x)\nplt.xlim(-5, 3)\nplt.plot(x, y)\nplt.show()\n"
] |
[
[
"numpy.linspace",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"numpy.exp",
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ethem-kinginthenorth/cloud-ml-examples
|
[
"e434d2bdbf2adf058dc436f992a56585537dc8ab"
] |
[
"gcp/docker/infrastructure/rapids_lib.py"
] |
[
"# os\nimport sys, os, time, logging\n\n# CPU DS stack\nimport pandas as pd\nimport numpy as np\nimport sklearn\n\n# GPU DS stack [ rapids ]\nimport gcsfs\n\n# scaling library\nimport dask\n\n# data ingestion [ CPU ]\nfrom pyarrow import orc as pyarrow_orc\n\n# ML models\nfrom sklearn import ensemble\nimport xgboost\n\n# data set splits\nfrom sklearn.model_selection import train_test_split as sklearn_train_test_split\n\n# device query\n##hack\ntry:\n import cudf, cuml\n from cuml.preprocessing.model_selection import train_test_split as cuml_train_test_split\n import pynvml\n import cupy\nexcept:\n print(\"Caught import failures -- probably missing GPU\")\n\n# memory query\nimport psutil\n\n# i/o\nimport logging, json, pprint\n\ndefault_sagemaker_paths = {\n 'base': '/opt/ml',\n 'code': '/opt/ml/code',\n 'data': '/opt/ml/input',\n 'train_data': '/opt/ml/input/data/training',\n 'hyperparams': '/opt/ml/input/config/hyperparameters.json',\n 'model': '/opt/ml/model',\n 'output': '/opt/ml/output',\n}\n\n\nclass RapidsCloudML(object):\n\n def __init__(self, cloud_type='AWS',\n model_type='XGBoost',\n data_type='ORC',\n compute_type='single-GPU',\n n_workers=-1,\n verbose_estimator=False,\n CSP_paths=default_sagemaker_paths):\n\n self.CSP_paths = CSP_paths\n self.cloud_type = cloud_type\n self.model_type = model_type\n self.data_type = data_type\n self.compute_type = compute_type\n self.verbose_estimator = verbose_estimator\n self.n_workers = self.parse_compute(n_workers)\n self.query_memory()\n\n def _read_orc(self, filename):\n if ('CPU' in self.compute_type):\n if (filename.startswith('gs://')):\n fs = gcsfs.GCSFileSystem()\n with fs.open(filename, mode='rb') as file:\n dataset = pyarrow_orc.ORCFile(file).read().to_pandas()\n else:\n with open(filename, mode='rb') as file:\n dataset = pyarrow_orc.ORCFile(file).read().to_pandas()\n\n elif ('GPU' in self.compute_type):\n dataset = cudf.read_orc(filename)\n\n return dataset\n\n def _read_csv(self, filename, col_labels):\n if ('CPU' in self.compute_type):\n dataset = pd.read_csv(filename, names=col_labels)\n elif ('GPU' in self.compute_type):\n dataset = cudf.read_csv(filename, names=col_labels)\n\n return dataset\n\n def load_data(self, filename='dataset.orc', col_labels=None, y_label='ArrDelayBinary'):\n target_filename = self.CSP_paths['train_data'] + '/' + filename\n self.log_to_file(f'\\n> loading dataset from {target_filename}...\\n')\n\n with PerfTimer() as ingestion_timer:\n if 'ORC' in self.data_type:\n dataset = self._read_orc(target_filename)\n elif 'CSV' in self.data_type:\n dataset = self._read_csv(target_filename, names=col_labels)\n\n self.log_to_file(f'ingestion completed in {ingestion_timer.duration}')\n self.log_to_file(f'dataset descriptors: {dataset.shape}\\n {dataset.dtypes}\\n {dataset.columns}\\n')\n\n return dataset, col_labels, y_label, ingestion_timer.duration\n\n def split_data(self, dataset, y_label, train_size=.8, random_state=0, shuffle=True):\n \"\"\"\n split dataset into train and test subset\n NOTE: assumes the first column of the dataset is the classification labels\n ! in the case of sklearn, we manually filter this column in the split call\n ! in the case of cuml, the filtering happens internally\n \"\"\"\n self.log_to_file('\\tsplitting train and test data')\n start_time = time.perf_counter()\n\n with PerfTimer() as split_timer:\n if 'CPU' in self.compute_type:\n X_train, X_test, y_train, y_test = sklearn_train_test_split(dataset.loc[:, dataset.columns != y_label],\n dataset[y_label], train_size=train_size,\n shuffle=shuffle, random_state=random_state)\n elif 'GPU' in self.compute_type:\n X_train, X_test, y_train, y_test = cuml_train_test_split(X=dataset, y=y_label, train_size=train_size,\n shuffle=shuffle, random_state=random_state)\n\n self.log_to_file(f'\\t> split completed in {split_timer.duration}')\n return X_train, X_test, y_train, y_test, split_timer.duration\n\n def train_model(self, X_train, y_train, model_params):\n self.log_to_file(f'\\ttraining {self.model_type} estimator w/ hyper-params')\n pprint.pprint(model_params, indent=10)\n print(f\"model type: {self.model_type}\\n compute type: {self.compute_type}\\n dataset dtype: {type(X_train)}\")\n\n try:\n if self.model_type == 'XGBoost':\n trained_model, training_time = self.fit_xgboost(X_train, y_train, model_params)\n elif self.model_type == 'RandomForest':\n trained_model, training_time = self.fit_random_forest(X_train, y_train, model_params)\n\n except Exception as error:\n self.log_to_file('!error during model training: ' + str(error))\n raise\n\n self.log_to_file(f'\\t> finished training in {training_time:.4f} s')\n return trained_model, training_time\n\n # train dlmc.xgboost model\n def fit_xgboost(self, X_train, y_train, model_params):\n with PerfTimer() as train_timer:\n train_DMatrix = xgboost.DMatrix(data=X_train, label=y_train)\n trained_model = xgboost.train(dtrain=train_DMatrix,\n params=model_params,\n num_boost_round=model_params['num_boost_round'],\n verbose_eval=self.verbose_estimator)\n return trained_model, train_timer.duration\n\n # fit_xgboost_multi_GPU ()\n # fit_random_forest_multi_GPU ()\n\n # train cuml.random-forest model\n def fit_random_forest(self, X_train, y_train, model_params):\n if 'CPU' in self.compute_type:\n rf_model = sklearn.ensemble.RandomForestClassifier(n_estimators=model_params['n_estimators'],\n max_depth=model_params['max_depth'],\n max_features=model_params['max_features'],\n n_jobs=int(self.n_workers),\n verbose=self.verbose_estimator)\n elif 'GPU' in self.compute_type:\n rf_model = cuml.ensemble.RandomForestClassifier(n_estimators=model_params['n_estimators'],\n max_depth=model_params['max_depth'],\n n_bins=model_params['n_bins'],\n max_features=model_params['max_features'],\n verbose=self.verbose_estimator)\n with PerfTimer() as train_timer:\n trained_model = rf_model.fit(X_train, y_train)\n\n return trained_model, train_timer.duration\n\n def evaluate_test_perf(self, trained_model, X_test, y_test):\n self.log_to_file(f'\\tinferencing on test set')\n with PerfTimer() as inference_timer:\n try:\n if self.model_type == 'XGBoost':\n test_DMatrix = xgboost.DMatrix(data=X_test, label=y_test)\n test_accuracy = 1 - float(trained_model.eval(test_DMatrix).split(':')[1])\n\n elif self.model_type == 'RandomForest':\n # y_test = cudf.DataFrame({'label': y_test.astype('int32') })\n test_accuracy = trained_model.score(X_test, y_test.astype('int32'))\n\n except Exception as error:\n self.log_to_file('!error during inference: ' + str(error))\n raise\n\n self.log_to_file(f'\\t> finished inference in {inference_timer.duration:.4f} s')\n return test_accuracy, inference_timer.duration\n\n # TODO: FIL inference [ ? ]\n # evaluate_perf_FIL(self, trained_model, X_test, y_test ):\n\n # TODO: global_best_model.save()\n def save_best_model(self, global_best_model=None):\n pass\n\n # ------------------------------------------------------\n # end of data science logic\n # ------------------------------------------------------\n\n def parse_compute(self, n_workers=None):\n if 'CPU' in self.compute_type or 'GPU' in self.compute_type:\n available_devices = self.query_compute()\n if n_workers == -1:\n n_workers = available_devices\n assert (n_workers <= available_devices)\n self.log_to_file(f'compute type: {self.compute_type}, n_workers: {n_workers}')\n else:\n raise Exception('unsupported compute type')\n return n_workers\n\n def query_compute(self):\n available_devices = None\n if 'CPU' in self.compute_type:\n available_devices = os.cpu_count()\n self.log_to_file(f'detected {available_devices} CPUs')\n elif 'GPU' in self.compute_type:\n available_devices = cupy.cuda.runtime.getDeviceCount()\n self.log_to_file(f'detected {available_devices} GPUs')\n return available_devices\n\n # TODO: enumerate all visible GPUs [ ? ]\n def query_memory(self):\n def print_device_memory(memory, device_ID=-1):\n memory_free_GB = np.array(memory.free) / np.array(10e8)\n memory_used_GB = np.array(memory.used) / np.array(10e8)\n memory_total_GB = np.array(memory.total) / np.array(10e8)\n if device_ID != -1:\n self.log_to_file(f'device ID = {device_ID}')\n self.log_to_file(f'memory free, used, total: {memory_free_GB}, {memory_used_GB}, {memory_total_GB}')\n\n if 'CPU' in self.compute_type:\n print_device_memory(psutil.virtual_memory())\n\n elif 'GPU' in self.compute_type:\n pynvml.nvmlInit()\n for iGPU in range(self.n_workers):\n handle = pynvml.nvmlDeviceGetHandleByIndex(iGPU)\n print_device_memory(pynvml.nvmlDeviceGetMemoryInfo(handle))\n\n def set_up_logging(self):\n logging_path = self.CSP_paths['output'] + '/log.txt'\n logging.basicConfig(filename=logging_path,\n level=logging.INFO)\n\n def log_to_file(self, text):\n logging.info(text)\n print(text)\n\n def environment_check(self):\n self.check_dirs()\n\n if self.cloud_type == 'AWS':\n try:\n self.list_files('/opt/ml')\n self.log_to_file(os.environ['SM_NUM_GPUS'])\n self.log_to_file(os.environ['SM_TRAINING_ENV'])\n self.log_to_file(os.environ['SM_CHANNEL_TRAIN'])\n self.log_to_file(os.environ['SM_HPS'])\n except:\n pass\n else:\n pass\n\n def check_dirs(self):\n self.log_to_file('\\n> checking for sagemaker paths...\\n')\n\n directories_to_check = self.CSP_paths\n for iDir, val in directories_to_check.items():\n self.log_to_file(f'{val}, exists : {os.path.exists(val)}')\n\n self.log_to_file(f'working directory = {os.getcwd()}')\n\n def list_files(self, startpath):\n print(f'\\n> listing contents of {startpath}\\n')\n for root, dirs, files in os.walk(startpath):\n level = root.replace(startpath, '').count(os.sep)\n indent = ' ' * 4 * (level)\n print('{}{}/'.format(indent, os.path.basename(root)))\n subindent = ' ' * 4 * (level + 1)\n for f in files:\n print('{}{}'.format(subindent, f))\n\n\n# perf_counter = highest available timer resolution\nclass PerfTimer:\n def __init__(self):\n self.start = None\n self.duration = None\n\n def __enter__(self):\n self.start = time.perf_counter()\n return self\n\n def __exit__(self, *args):\n self.duration = time.perf_counter() - self.start\n\n\n'''\nhttps://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier.fit\n\nn_estimators=100,\ncriterion='gini',\nmax_depth=None,\nmin_samples_split=2,\nmin_samples_leaf=1,\nmin_weight_fraction_leaf=0.0,\nmax_features='auto',\nmax_leaf_nodes=None,\nmin_impurity_decrease=0.0,\nmin_impurity_split=None,\nbootstrap=True,\noob_score=False,\nn_jobs=None,\nrandom_state=None,\nverbose=0,\nwarm_start=False,\nclass_weight=None,\nccp_alpha=0.0,\nmax_samples=None\n\n'''\n"
] |
[
[
"numpy.array",
"pandas.read_csv",
"sklearn.model_selection.train_test_split"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
migkapa/lanefinding
|
[
"48a86986e72c063eaa8e49139f63cc0c0d2de916"
] |
[
"P1.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\n# # Self-Driving Car Engineer Nanodegree\n# \n# \n# ## Project: **Finding Lane Lines on the Road** \n# ***\n# In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip \"raw-lines-example.mp4\" (also contained in this repository) to see what the output should look like after using the helper functions below. \n# \n# Once you have a result that looks roughly like \"raw-lines-example.mp4\", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.\n# \n# In addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a [write up template](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_template.md) that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the [rubric points](https://review.udacity.com/#!/rubrics/322/view) for this project.\n# \n# ---\n# Let's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the \"play\" button above) to display the image.\n# \n# **Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the \"Kernel\" menu above and selecting \"Restart & Clear Output\".**\n# \n# ---\n\n# **The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.**\n# \n# ---\n# \n# <figure>\n# <img src=\"examples/line-segments-example.jpg\" width=\"380\" alt=\"Combined Image\" />\n# <figcaption>\n# <p></p> \n# <p style=\"text-align: center;\"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> \n# </figcaption>\n# </figure>\n# <p></p> \n# <figure>\n# <img src=\"examples/laneLines_thirdPass.jpg\" width=\"380\" alt=\"Combined Image\" />\n# <figcaption>\n# <p></p> \n# <p style=\"text-align: center;\"> Your goal is to connect/average/extrapolate line segments to get output like this</p> \n# </figcaption>\n# </figure>\n\n# **Run the cell below to import some packages. If you get an `import error` for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.** \n\n# ## Import Packages\n\n# In[102]:\n\n\n#importing some useful packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# ## Read in an Image\n\n# In[103]:\n\n\n#reading in an image\nimage_solidwr = mpimg.imread('test_images/solidWhiteRight.jpg')\n\n#printing out some stats and plotting\nprint('This image is:', type(image), 'with dimensions:', image.shape)\nplt.imshow(image_solidwr) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')\n\n\n# ## Ideas for Lane Detection Pipeline\n\n# **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**\n# \n# `cv2.inRange()` for color selection \n# `cv2.fillPoly()` for regions selection \n# `cv2.line()` to draw lines on an image given endpoints \n# `cv2.addWeighted()` to coadd / overlay two images\n# `cv2.cvtColor()` to grayscale or change color\n# `cv2.imwrite()` to output images to file \n# `cv2.bitwise_and()` to apply a mask to an image\n# \n# **Check out the OpenCV documentation to learn about these and discover even more awesome functionality!**\n\n# ## Helper Functions\n\n# Below are some helper functions to help get you started. They should look familiar from the lesson!\n\n# In[104]:\n\n\nimport math\n\ndef grayscale(img):\n \"\"\"Applies the Grayscale transform\n This will return an image with only one color channel\n but NOTE: to see the returned image as grayscale\n (assuming your grayscaled image is called 'gray')\n you should call plt.imshow(gray, cmap='gray')\"\"\"\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # Or use BGR2GRAY if you read an image with cv2.imread()\n # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \ndef canny(img, low_threshold, high_threshold):\n \"\"\"Applies the Canny transform\"\"\"\n return cv2.Canny(img, low_threshold, high_threshold)\n\ndef gaussian_blur(img, kernel_size):\n \"\"\"Applies a Gaussian Noise kernel\"\"\"\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\ndef region_of_interest(img, vertices):\n \"\"\"\n Applies an image mask.\n \n Only keeps the region of the image defined by the polygon\n formed from `vertices`. The rest of the image is set to black.\n `vertices` should be a numpy array of integer points.\n \"\"\"\n #defining a blank mask to start with\n mask = np.zeros_like(img) \n \n #defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n \n #filling pixels inside the polygon defined by \"vertices\" with the fill color \n cv2.fillPoly(mask, vertices, ignore_mask_color)\n \n #returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\ndef extrapolate_draw(img, x, y, color, thickness):\n if len(x)==0:\n return\n \n m, b = np.polyfit(x, y, 1)\n \n y1 = img.shape[0] \n x1 = int((y1 - b)/m)\n y2 = 330 \n x2 = int((y2 - b)/m)\n \n cv2.line(img, (x1,y1), (x2,y2), color, thickness) \n\ndef draw_lines(img, lines, color=[255, 0, 0], thickness=10):\n \"\"\"\n NOTE: this is the function you might want to use as a starting point once you want to \n average/extrapolate the line segments you detect to map out the full\n extent of the lane (going from the result shown in raw-lines-example.mp4\n to that shown in P1_example.mp4). \n \n Think about things like separating line segments by their \n slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left\n line vs. the right line. Then, you can average the position of each of \n the lines and extrapolate to the top and bottom of the lane.\n \n This function draws `lines` with `color` and `thickness`. \n Lines are drawn on the image inplace (mutates the image).\n If you want to make the lines semi-transparent, think about combining\n this function with the weighted_img() function below\n \"\"\"\n leftx = []\n lefty = []\n rightx = []\n righty = []\n \n for line in lines:\n for x1,y1,x2,y2 in line:\n \n slope = ((y2 - y1)/(x2 - x1))\n \n if(slope <= 0):\n leftx.append(x1)\n leftx.append(x2)\n lefty.append(y1)\n lefty.append(y2)\n else:\n rightx.append(x1)\n rightx.append(x2)\n righty.append(y1)\n righty.append(y2)\n \n extrapolate_draw(img, leftx, lefty, color, thickness)\n extrapolate_draw(img, rightx, righty, color, thickness)\n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n \"\"\"\n `img` should be the output of a Canny transform.\n \n Returns an image with hough lines drawn.\n \"\"\"\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)\n line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n draw_lines(line_img, lines)\n return line_img\n\n# Python 3 has support for cool math symbols.\n\ndef weighted_img(img, initial_img, α=0.8, β=1., γ=0.):\n \"\"\"\n `img` is the output of the hough_lines(), An image with lines drawn on it.\n Should be a blank image (all black) with lines drawn on it.\n \n `initial_img` should be the image before any processing.\n \n The result image is computed as follows:\n \n initial_img * α + img * β + γ\n NOTE: initial_img and img must be the same shape!\n \"\"\"\n return cv2.addWeighted(initial_img, α, img, β, γ)\n\n\n# ## Build a Lane Finding Pipeline\n# \n# \n\n# Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.\n# \n# Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.\n\n# In[120]:\n\n\n# TODO: Build your pipeline that will draw lane lines on the test_images\n# then save them to the test_images_output directory.\n\ndef lane_finding(img):\n # grayscale conversion\n gray_img = grayscale(img)\n \n # define kernel size and apply a gaussian blur\n kernel_size = 5\n gray_img_blur = gaussian_blur(gray_img, kernel_size)\n \n # Canny edge detector\n low_threshold = 40\n high_threshold = 80\n edges = canny(gray_img_blur, low_threshold, high_threshold)\n \n # region of interest \n vertices = np.array([[(0,image.shape[0]),(450, 320), (490, 320), (image.shape[1],image.shape[0])]], dtype=np.int32) # we define a polygon for masking\n region_masking = region_of_interest(edges, vertices)\n \n # apply Hough on edge detected in the region of interest\n \n # the Hough transform parameters\n rho = 1 # distance resolution in pixels of the Hough grid\n theta = np.pi/180 # angular resolution in radians of the Hough grid\n threshold = 40 # minimum number of votes (intersections in Hough grid cell)\n min_line_len = 30 #minimum number of pixels making up a line\n max_line_gap = 300 # maximum gap in pixels between connectable line segments\n lines = hough_lines(region_masking, rho, theta, threshold, min_line_len, max_line_gap)\n \n # drawing line on top\n lines_edges = weighted_img(lines, img)\n \n return lines_edges\n\n\n# looping through each image in test_images directory\nimport os\nfor test_image in os.listdir(\"test_images/\") :\n \n # reading the image\n img = mpimg.imread('test_images/' + test_image)\n \n final_img = lane_finding(img);\n \n #display the image\n plt.imshow(final_img, cmap='gray')\n plt.show()\n\n\n# ## Test on Videos\n# \n# You know what's cooler than drawing lanes over images? Drawing lanes over video!\n# \n# We can test our solution on two provided videos:\n# \n# `solidWhiteRight.mp4`\n# \n# `solidYellowLeft.mp4`\n# \n# **Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.**\n# \n# **If you get an error that looks like this:**\n# ```\n# NeedDownloadError: Need ffmpeg exe. \n# You can download it by calling: \n# imageio.plugins.ffmpeg.download()\n# ```\n# **Follow the instructions in the error message and check out [this forum post](https://discussions.udacity.com/t/project-error-of-test-on-videos/274082) for more troubleshooting tips across operating systems.**\n\n# In[121]:\n\n\n# Import everything needed to edit/save/watch video clips\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\n\n\n# In[122]:\n\n\ndef process_image(img):\n # NOTE: The output you return should be a color image (3 channel) for processing video below\n # TODO: put your pipeline here,\n # you should return the final output (image where lines are drawn on lanes)\n \n result = lane_finding(img)\n\n return result\n\n\n# Let's try the one with the solid white lane on the right first ...\n\n# In[123]:\n\n\nwhite_output = 'test_videos_output/solidWhiteRight.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n##clip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\").subclip(0,5)\nclip1 = VideoFileClip(\"test_videos/solidWhiteRight.mp4\")\nwhite_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!\nget_ipython().run_line_magic('time', 'white_clip.write_videofile(white_output, audio=False)')\n\n\n# Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.\n\n# In[124]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(white_output))\n\n\n# ## Improve the draw_lines() function\n# \n# **At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video \"P1_example.mp4\".**\n# \n# **Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.**\n\n# Now for the one with the solid yellow lane on the left. This one's more tricky!\n\n# In[125]:\n\n\nyellow_output = 'test_videos_output/solidYellowLeft.mp4'\n## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video\n## To do so add .subclip(start_second,end_second) to the end of the line below\n## Where start_second and end_second are integer values representing the start and end of the subclip\n## You may also uncomment the following line for a subclip of the first 5 seconds\n# clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)\nclip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')\nyellow_clip = clip2.fl_image(process_image)\nget_ipython().run_line_magic('time', 'yellow_clip.write_videofile(yellow_output, audio=False)')\n\n\n# In[126]:\n\n\nHTML(\"\"\"\n<video width=\"960\" height=\"540\" controls>\n <source src=\"{0}\">\n</video>\n\"\"\".format(yellow_output))\n\n"
] |
[
[
"matplotlib.pyplot.imshow",
"numpy.polyfit",
"matplotlib.image.imread",
"numpy.zeros_like",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.show"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sdjsngs/Cross-Epoch-Learning-for-Weakly-Supervised-Anomaly-Detection-in-Surveillance-Videos
|
[
"f734db8d440f2974cb6b4234b30da6856ef62ce3"
] |
[
"net/dataset/loader.py"
] |
[
"\"\"\"\nload dataset\n\"\"\"\nimport torch\nfrom torch.utils.data import DataLoader\nfrom .build import build_dataset\n\n\ndef construct_loader(mode,cfg,):\n \"\"\"\n consturct data loader\n :param cfg:\n :param mode:\n :return:\n \"\"\"\n assert mode in [\"train\",\"test\",\"update_epoch\"]\n if mode in [\"train\"]:\n dataset_name=cfg.TRAIN.DATASET\n batch_size=cfg.TRAIN.BATCH_SIZE\n shuffle=True\n drop_last = True\n elif mode in [\"test\"]:\n dataset_name=cfg.TEST.DATASET\n batch_size=cfg.TEST.BATCH_SIZE\n shuffle=False\n drop_last=False\n elif mode in [\"update_epoch\"]:\n # update dataset only normal video return\n dataset_name=cfg.MEMORY_BANK.DATASET\n batch_size=cfg.MEMORY_BANK.BATCH_SIZE\n shuffle=False\n drop_last=False\n # get dataset in torch.util.data.Dataset\n dataset=build_dataset(dataset_name,mode,cfg)\n\n loader=torch.utils.data.DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=cfg.DATA_LOADER.NUM_WORKERS,\n pin_memory=cfg.DATA_LOADER.PIN_MEMORY,\n drop_last=drop_last,\n\n )\n return loader\n\n"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Qointum/pypy
|
[
"c0ed88efbc135a75a535f4534ca1f3baf0bf39d8"
] |
[
"pypy/module/micronumpy/test/test_flagsobj.py"
] |
[
"from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest\n\n\nclass AppTestFlagsObj(BaseNumpyAppTest):\n def test_init(self):\n import numpy as np\n a = np.array([1,2,3])\n assert a.flags['C'] is True\n b = type(a.flags)()\n assert b is not a.flags\n assert b['C'] is True\n s = str(b)\n assert s == '%s' %(' C_CONTIGUOUS : True\\n F_CONTIGUOUS : True'\n '\\n OWNDATA : True\\n WRITEABLE : False'\n '\\n ALIGNED : True\\n UPDATEIFCOPY : False')\n a = np.array(2)\n assert a.flags.owndata\n\n def test_repr(self):\n import numpy as np\n a = np.array([1,2,3])\n assert repr(type(a.flags)) == \"<type 'numpy.flagsobj'>\"\n\n def test_array_flags(self):\n import numpy as np\n a = np.array([1,2,3])\n assert a.flags.c_contiguous == True\n assert a.flags['W'] == True\n assert a.flags.fnc == False\n assert a.flags.forc == True\n assert a.flags['FNC'] == False\n assert a.flags['FORC'] == True\n raises(KeyError, \"a.flags['blah']\")\n raises(KeyError, \"a.flags['C_CONTIGUOUS'] = False\")\n raises((TypeError, AttributeError), \"a.flags.c_contiguous = False\")\n\n def test_scalar_flags(self):\n import numpy as np\n a = np.int32(2)\n assert a.flags.c_contiguous == True\n\n def test_compare(self):\n import numpy as np\n a = np.array([1,2,3])\n b = np.array([4,5,6,7])\n assert a.flags == b.flags\n assert not a.flags != b.flags\n"
] |
[
[
"numpy.array",
"numpy.int32"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NatLee/models
|
[
"0c9253b4a0b34935cf78bd13e6520bbeee2f5f92"
] |
[
"official/core/base_task.py"
] |
[
"# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Defines the base task abstraction.\"\"\"\nimport abc\nfrom typing import Optional\n\nfrom absl import logging\nimport tensorflow as tf\n\nfrom official.core import config_definitions\nfrom official.modeling import optimization\nfrom official.modeling import performance\n\nOptimizationConfig = optimization.OptimizationConfig\nRuntimeConfig = config_definitions.RuntimeConfig\n\n\nclass Task(tf.Module, metaclass=abc.ABCMeta):\n \"\"\"A single-replica view of training procedure.\n\n Tasks provide artifacts for training/validation procedures, including\n loading/iterating over Datasets, training/validation steps, calculating the\n loss and customized metrics with reduction.\n \"\"\"\n\n # Special keys in train/validate step returned logs.\n loss = \"loss\"\n\n def __init__(self,\n params,\n logging_dir: Optional[str] = None,\n name: Optional[str] = None):\n \"\"\"Task initialization.\n\n Args:\n params: the task configuration instance, which can be any of dataclass,\n ConfigDict, namedtuple, etc.\n logging_dir: a string pointing to where the model, summaries etc. will be\n saved. You can also write additional stuff in this directory.\n name: the task name.\n \"\"\"\n super().__init__(name=name)\n self._task_config = params\n self._logging_dir = logging_dir\n\n @property\n def task_config(self):\n return self._task_config\n\n @property\n def logging_dir(self) -> str:\n return self._logging_dir\n\n @classmethod\n def create_optimizer(cls, optimizer_config: OptimizationConfig,\n runtime_config: Optional[RuntimeConfig] = None):\n \"\"\"Creates an TF optimizer from configurations.\n\n Args:\n optimizer_config: the parameters of the Optimization settings.\n runtime_config: the parameters of the runtime.\n\n Returns:\n A tf.optimizers.Optimizer object.\n \"\"\"\n opt_factory = optimization.OptimizerFactory(optimizer_config)\n optimizer = opt_factory.build_optimizer(opt_factory.build_learning_rate())\n # Configuring optimizer when loss_scale is set in runtime config. This helps\n # avoiding overflow/underflow for float16 computations.\n if runtime_config and runtime_config.loss_scale:\n optimizer = performance.configure_optimizer(\n optimizer,\n use_float16=runtime_config.mixed_precision_dtype == \"float16\",\n loss_scale=runtime_config.loss_scale)\n\n return optimizer\n\n def initialize(self, model: tf.keras.Model):\n \"\"\"[Optional] A callback function used as CheckpointManager's init_fn.\n\n This function will be called when no checkpoint is found for the model.\n If there is a checkpoint, the checkpoint will be loaded and this function\n will not be called. You can use this callback function to load a pretrained\n checkpoint, saved under a directory other than the model_dir.\n\n Args:\n model: The keras.Model built or used by this task.\n \"\"\"\n ckpt_dir_or_file = self.task_config.init_checkpoint\n logging.info(\"Trying to load pretrained checkpoint from %s\",\n ckpt_dir_or_file)\n if tf.io.gfile.isdir(ckpt_dir_or_file):\n ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file)\n if not ckpt_dir_or_file:\n return\n\n if hasattr(model, \"checkpoint_items\"):\n checkpoint_items = model.checkpoint_items\n else:\n checkpoint_items = dict(model=model)\n ckpt = tf.train.Checkpoint(**checkpoint_items)\n status = ckpt.read(ckpt_dir_or_file)\n status.expect_partial().assert_existing_objects_matched()\n logging.info(\"Finished loading pretrained checkpoint from %s\",\n ckpt_dir_or_file)\n\n def build_model(self) -> tf.keras.Model:\n \"\"\"[Optional] Creates model architecture.\n\n Returns:\n A model instance.\n \"\"\"\n\n @abc.abstractmethod\n def build_inputs(self,\n params,\n input_context: Optional[tf.distribute.InputContext] = None):\n \"\"\"Returns a dataset or a nested structure of dataset functions.\n\n Dataset functions define per-host datasets with the per-replica batch size.\n With distributed training, this method runs on remote hosts.\n\n Args:\n params: hyperparams to create input pipelines, which can be any of\n dataclass, ConfigDict, namedtuple, etc.\n input_context: optional distribution input pipeline context.\n\n Returns:\n A nested structure of per-replica input functions.\n \"\"\"\n\n def build_losses(self, labels, model_outputs, aux_losses=None) -> tf.Tensor:\n \"\"\"Standard interface to compute losses.\n\n Args:\n labels: optional label tensors.\n model_outputs: a nested structure of output tensors.\n aux_losses: auxiliary loss tensors, i.e. `losses` in keras.Model.\n\n Returns:\n The total loss tensor.\n \"\"\"\n del model_outputs, labels\n\n if aux_losses is None:\n losses = [tf.constant(0.0, dtype=tf.float32)]\n else:\n losses = aux_losses\n total_loss = tf.add_n(losses)\n return total_loss\n\n def build_metrics(self, training: bool = True):\n \"\"\"Gets streaming metrics for training/validation.\"\"\"\n del training\n return []\n\n def process_metrics(self, metrics, labels, model_outputs):\n \"\"\"Process and update metrics.\n\n Called when using custom training loop API.\n\n Args:\n metrics: a nested structure of metrics objects. The return of function\n self.build_metrics.\n labels: a tensor or a nested structure of tensors.\n model_outputs: a tensor or a nested structure of tensors. For example,\n output of the keras model built by self.build_model.\n \"\"\"\n for metric in metrics:\n metric.update_state(labels, model_outputs)\n\n def process_compiled_metrics(self, compiled_metrics, labels, model_outputs):\n \"\"\"Process and update compiled_metrics.\n\n call when using compile/fit API.\n\n Args:\n compiled_metrics: the compiled metrics (model.compiled_metrics).\n labels: a tensor or a nested structure of tensors.\n model_outputs: a tensor or a nested structure of tensors. For example,\n output of the keras model built by self.build_model.\n \"\"\"\n compiled_metrics.update_state(labels, model_outputs)\n\n def train_step(self,\n inputs,\n model: tf.keras.Model,\n optimizer: tf.keras.optimizers.Optimizer,\n metrics=None):\n \"\"\"Does forward and backward.\n\n With distribution strategies, this method runs on devices.\n\n Args:\n inputs: a dictionary of input tensors.\n model: the model, forward pass definition.\n optimizer: the optimizer for this training step.\n metrics: a nested structure of metrics objects.\n\n Returns:\n A dictionary of logs.\n \"\"\"\n if isinstance(inputs, tuple) and len(inputs) == 2:\n features, labels = inputs\n else:\n features, labels = inputs, inputs\n with tf.GradientTape() as tape:\n outputs = model(features, training=True)\n # Computes per-replica loss.\n if model.compiled_loss:\n loss = model.compiled_loss(\n labels, outputs, regularization_losses=model.losses)\n loss += self.build_losses(\n labels=labels, model_outputs=outputs, aux_losses=None)\n else:\n loss = self.build_losses(\n labels=labels, model_outputs=outputs, aux_losses=model.losses)\n # Scales loss as the default gradients allreduce performs sum inside the\n # optimizer.\n scaled_loss = loss / tf.distribute.get_strategy().num_replicas_in_sync\n\n # For mixed precision, when a LossScaleOptimizer is used, the loss is\n # scaled to avoid numeric underflow.\n if isinstance(optimizer,\n tf.keras.mixed_precision.LossScaleOptimizer):\n scaled_loss = optimizer.get_scaled_loss(scaled_loss)\n\n tvars = model.trainable_variables\n grads = tape.gradient(scaled_loss, tvars)\n\n if isinstance(optimizer,\n tf.keras.mixed_precision.LossScaleOptimizer):\n grads = optimizer.get_unscaled_gradients(grads)\n optimizer.apply_gradients(list(zip(grads, tvars)))\n logs = {self.loss: loss}\n if metrics:\n self.process_metrics(metrics, labels, outputs)\n if model.compiled_metrics:\n self.process_compiled_metrics(model.compiled_metrics, labels, outputs)\n logs.update({m.name: m.result() for m in metrics or []})\n logs.update({m.name: m.result() for m in model.metrics})\n return logs\n\n def validation_step(self, inputs, model: tf.keras.Model, metrics=None):\n \"\"\"Validation step.\n\n With distribution strategies, this method runs on devices.\n\n Args:\n inputs: a dictionary of input tensors.\n model: the keras.Model.\n metrics: a nested structure of metrics objects.\n\n Returns:\n A dictionary of logs.\n \"\"\"\n if isinstance(inputs, tuple) and len(inputs) == 2:\n features, labels = inputs\n else:\n features, labels = inputs, inputs\n outputs = self.inference_step(features, model)\n loss = self.build_losses(\n labels=labels, model_outputs=outputs, aux_losses=model.losses)\n logs = {self.loss: loss}\n if metrics:\n self.process_metrics(metrics, labels, outputs)\n if model.compiled_metrics:\n self.process_compiled_metrics(model.compiled_metrics, labels, outputs)\n logs.update({m.name: m.result() for m in metrics or []})\n logs.update({m.name: m.result() for m in model.metrics})\n return logs\n\n def inference_step(self, inputs, model: tf.keras.Model):\n \"\"\"Performs the forward step.\n\n With distribution strategies, this method runs on devices.\n\n Args:\n inputs: a dictionary of input tensors.\n model: the keras.Model.\n\n Returns:\n Model outputs.\n \"\"\"\n return model(inputs, training=False)\n\n def aggregate_logs(self, state, step_logs):\n \"\"\"Optional aggregation over logs returned from a validation step.\"\"\"\n pass\n\n def reduce_aggregated_logs(self,\n aggregated_logs,\n global_step: Optional[tf.Tensor] = None):\n \"\"\"Optional reduce of aggregated logs over validation steps.\"\"\"\n return {}\n"
] |
[
[
"tensorflow.io.gfile.isdir",
"tensorflow.train.latest_checkpoint",
"tensorflow.constant",
"tensorflow.train.Checkpoint",
"tensorflow.distribute.get_strategy",
"tensorflow.add_n",
"tensorflow.GradientTape"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.13",
"2.3",
"2.4",
"2.9",
"2.5",
"2.2",
"2.10"
]
}
] |
WillAdams-afk/Corona
|
[
"04f28216deca8856eea0c796f214735ad9726866",
"04f28216deca8856eea0c796f214735ad9726866"
] |
[
"scripts/adjust_regional_meta.py",
"scripts/add_priorities_to_meta.py"
] |
[
"\"\"\"\r\nAdd column to metadata to denote 'focal' samples based on supplied region\r\nRewrite location, division and country for non-focal samples to be region\r\nRewrite division_exposure and country_exposure for non-focal samples to be region_exposure\r\n\"\"\"\r\n\r\nimport argparse\r\nimport pandas as pd\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(\r\n description=\"Add column to metadata to denote 'focal' samples based on supplied region\",\r\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\r\n )\r\n parser.add_argument(\"--metadata\", type = str, required=True, help=\"metadata\")\r\n parser.add_argument(\"--region\", type=str, required=False, help=\"focal region\")\r\n parser.add_argument(\"--country\", type=str, required=False, help=\"focal country\")\r\n parser.add_argument(\"--division\", type=str, required=False, help=\"focal division\")\r\n parser.add_argument(\"--location\", type=str, required=False, help=\"focal location\")\r\n parser.add_argument(\"--composite\", type=str, required=False, help=\"composite sampling\")\r\n parser.add_argument(\"--output\", type=str, required=True, help=\"adjusted metadata\")\r\n args = parser.parse_args()\r\n\r\n region_list = [\"Asia\", \"Africa\", \"Europe\", \"North America\", \"Oceania\", \"South America\"]\r\n\r\n metadata = pd.read_csv(args.metadata, delimiter='\\t')\r\n\r\n # if in region list, then do the fixing\r\n if args.region in region_list:\r\n focal_region = args.region\r\n else: # otherwise just write out metadata as is, and proceed\r\n metadata.to_csv(args.output, index=False, sep=\"\\t\")\r\n exit()\r\n\r\n print(\"Adjusting metadata for focal region\", args.region)\r\n\r\n\r\n metadata.insert(12, 'focal', True)\r\n\r\n metadata.loc[metadata.region != focal_region, 'focal'] = False\r\n metadata.loc[metadata.region != focal_region, 'location'] = \"\"\r\n metadata.loc[metadata.region != focal_region, 'division'] = metadata.region\r\n metadata.loc[metadata.region != focal_region, 'country'] = metadata.region\r\n metadata.loc[metadata.region != focal_region, 'division_exposure'] = metadata.region_exposure\r\n metadata.loc[metadata.region != focal_region, 'country_exposure'] = metadata.region_exposure\r\n metadata.loc[(metadata.region == focal_region) & (metadata.region_exposure != focal_region), 'division_exposure'] = metadata.region_exposure\r\n metadata.loc[(metadata.region == focal_region) & (metadata.region_exposure != focal_region), 'country_exposure'] = metadata.region_exposure\r\n metadata.loc[(metadata.region == focal_region) & (metadata.division_exposure.isna()), 'division_exposure'] = metadata.division\r\n metadata.loc[(metadata.region == focal_region) & (metadata.country_exposure.isna()), 'country_exposure'] = metadata.country\r\n\r\n metadata.to_csv(args.output, index=False, sep=\"\\t\")\r\n",
"\"\"\"\r\nAdd column to metadata with the priorities of 'context' sequences\r\nrelative to the 'focal' samples\r\n\"\"\"\r\n\r\nimport argparse\r\nimport pandas as pd\r\nimport csv\r\nimport json\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(\r\n description=\"Add columns for priorities of sequences relative to diff focal regions\",\r\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\r\n )\r\n parser.add_argument(\"--metadata\", type = str, required=True, help=\"metadata\")\r\n parser.add_argument(\"--priorities\", type=str, nargs=\"+\", required=True, help=\"priorities files\")\r\n parser.add_argument(\"--config\", type=str, help=\"config file to modify\")\r\n parser.add_argument(\"--output-meta\", type=str, required=True, help=\"adjusted metadata\")\r\n parser.add_argument(\"--output-config\", type=str, help=\"modified config\")\r\n args = parser.parse_args()\r\n\r\n metadata = pd.read_csv(args.metadata, sep='\\t')\r\n with open(args.config) as fh:\r\n input_json = json.load(fh)\r\n\r\n for priority_file in args.priorities:\r\n p_f = priority_file.replace(\".tsv\", \"\")\r\n region = p_f.split(\"_\")[2]\r\n column_name = \"\".join([\"priorities_\",region])\r\n \r\n with open(priority_file, 'r') as f:\r\n reader = csv.reader(f, delimiter='\\t')\r\n priors = {r[0]: r[1] for r in reader if len(r)>1}\r\n\r\n assign_priors = [priors[st] if st in priors else \"\" for st in metadata.strain]\r\n\r\n metadata.insert(11, column_name, assign_priors)\r\n input_json['colorings'].append({'key': column_name, 'type': 'continuous'})\r\n\r\n metadata.to_csv(args.output_meta, index=False, sep=\"\\t\")\r\n\r\n with open(args.output_config, 'w') as fh:\r\n json.dump(input_json, fh, indent=2)\r\n "
] |
[
[
"pandas.read_csv"
],
[
"pandas.read_csv"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
AIDEmeProject/AIDEme-Web
|
[
"1a802a19edf03b8fddcea950ff91e749283e7d18"
] |
[
"api/src/routes/create_labeled_set.py"
] |
[
"# Copyright 2019 École Polytechnique\n#\n# Authorship\n# Luciano Di Palma <[email protected]>\n# Enhui Huang <[email protected]>\n# Le Ha Vy Nguyen <[email protected]>\n# Laurent Cetinsoy <[email protected]>\n#\n# Disclaimer\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n# TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n\nimport numpy as np\n\nfrom aideme.explore import LabeledSet\n\n\ndef create_labeled_set(labeled_points):\n if \"labels\" in labeled_points[0]:\n return LabeledSet(\n labels=[np.prod(point[\"labels\"]) for point in labeled_points],\n partial=[point[\"labels\"] for point in labeled_points],\n index=[point[\"id\"] for point in labeled_points],\n )\n\n return LabeledSet(\n labels=[point[\"label\"] for point in labeled_points],\n index=[point[\"id\"] for point in labeled_points],\n )\n"
] |
[
[
"numpy.prod"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ttk21/lab_04
|
[
"b9c2f8f941c76218b4c0fd7ad1580e844c4c0104"
] |
[
"ex2-map-estimation.py"
] |
[
"import numpy as np\nimport visgeom as vg\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport scipy.linalg\nfrom pylie import SO3, SE3\nfrom optim import gauss_newton\n\n\"\"\"Example 2 - MAP estimation\"\"\"\n\n\nclass NoisyPointAlignmentBasedPoseEstimatorObjective:\n \"\"\"Implements linearisation of the covariance weighted objective function\"\"\"\n\n def __init__(self, x_w, x_o, covs):\n if x_w.shape[0] != 3 or x_w.shape != x_o.shape:\n raise TypeError('Matrices with corresponding points must have same size')\n\n self.x_w = x_w\n self.x_o = x_o\n self.num_points = x_w.shape[1]\n\n if len(covs) != self.num_points:\n raise TypeError('Must have a covariance matrix for each point observation')\n\n # Compute square root of information matrices.\n self.sqrt_inv_covs = [None] * self.num_points\n for i in range(self.num_points):\n self.sqrt_inv_covs[i] = scipy.linalg.sqrtm(scipy.linalg.inv(covs[i]))\n\n def linearise(self, T_wo):\n A = np.zeros((3 * self.num_points, 6))\n b = np.zeros((3 * self.num_points, 1))\n T_wo_inv = T_wo.inverse()\n\n # Enter the submatrices from each measurement:\n for i in range(self.num_points):\n A[3 * i:3 * (i + 1), :] = self.sqrt_inv_covs[i] @ \\\n T_wo_inv.jac_action_Xx_wrt_X(self.x_w[:, [i]]) @ T_wo.jac_inverse_X_wrt_X()\n b[3 * i:3 * (i + 1)] = self.sqrt_inv_covs[i] @ (self.x_o[:, [i]] - T_wo_inv * self.x_w[:, [i]])\n\n return A, b, b.T.dot(b)\n\n\ndef main():\n # World box.\n points_w = vg.utils.generate_box()\n\n # True observer pose.\n true_pose_wo = SE3((SO3.rot_z(np.pi), np.array([[3, 0, 0]]).T))\n\n # Observed box with noise.\n points_o = vg.utils.generate_box(pose=true_pose_wo.inverse().to_tuple())\n num_points = points_o.shape[1]\n point_covariances = [np.diag(np.array([1e-1, 1e-1, 1e-1]) ** 2)] * num_points\n for c in range(num_points):\n points_o[:, [c]] = points_o[:, [c]] + np.random.multivariate_normal(np.zeros(3), point_covariances[c]).reshape(\n -1, 1)\n\n # Perturb observer pose and use as initial state.\n init_pose_wo = true_pose_wo + 10 * np.random.randn(6, 1)\n\n # Estimate pose in the world frame from point correspondences.\n model = NoisyPointAlignmentBasedPoseEstimatorObjective(points_w, points_o, point_covariances)\n x, cost, A, b = gauss_newton(init_pose_wo, model)\n cov_x_final = np.linalg.inv(A.T @ A)\n\n # Print covariance.\n with np.printoptions(precision=3, suppress=True):\n print('Covariance:')\n print(cov_x_final)\n\n # Visualize (press a key to jump to the next iteration).\n # Use Qt 5 backend in visualisation.\n matplotlib.use('qt5agg')\n\n # Create figure and axis.\n fig = plt.figure()\n ax = plt.axes(projection='3d')\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n\n # Plot box and true state\n vg.plot_pose(ax, true_pose_wo.to_tuple(), scale=1, alpha=0.4)\n vg.utils.plot_as_box(ax, points_w, alpha=0.4)\n\n # Plot initial state (to run axis equal first time).\n ax.set_title('Cost: ' + str(cost[0]))\n artists = vg.plot_pose(ax, x[0].to_tuple(), scale=1)\n artists.extend(vg.utils.plot_as_box(ax, x[0] * points_o))\n vg.plot.axis_equal(ax)\n plt.draw()\n\n while True:\n if plt.waitforbuttonpress():\n break\n\n # Plot iterations\n for i in range(1, len(x)):\n for artist in artists:\n artist.remove()\n\n ax.set_title('Cost: ' + str(cost[i]))\n artists = vg.plot_pose(ax, x[i].to_tuple(), scale=1)\n artists.extend(vg.utils.plot_as_box(ax, x[i] * points_o))\n plt.draw()\n while True:\n if plt.waitforbuttonpress():\n break\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.printoptions",
"numpy.linalg.inv",
"matplotlib.use",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.axes",
"numpy.random.randn",
"matplotlib.pyplot.waitforbuttonpress",
"numpy.array",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
thunderhoser/WaveTF
|
[
"6e3f2b04334a0a51476ad316e6d97965ce009f4b"
] |
[
"wavetf/_haar_conv.py"
] |
[
"# Copyright 2020 CRS4 (http://www.crs4.it/)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom wavetf._base_wavelets import DirWaveLayer1D, InvWaveLayer1D, DirWaveLayer2D, InvWaveLayer2D\n\n########################################################################\n# 1D wavelet\n########################################################################\n\n########################################################################\n# Direct wavelet transform\n## input: (b, x, c) --> output: (b, nx, 2*c)\n\nclass HaarWaveLayer1D(DirWaveLayer1D):\n \"\"\"1D direct Haar trasform\"\"\"\n ########################################################################\n ## Init (with wavelet kernels)\n ########################################################################\n def __init__(self, **kwargs):\n ## Haar kernel\n s2 = math.sqrt(2) * .5 # 1/sqrt(2)\n self.haar_ker = tf.constant([s2, s2, s2, -s2], shape=(2,2), dtype=tf.float64)\n ## call constructor\n super(DirWaveLayer1D, self).__init__(**kwargs)\n ########################################################################\n ## Haar wavelet\n ########################################################################\n def haar_0(self, t1):\n ## t1: (b, c, x) with (x % 2) == 0\n return t1 # out: (b, c, 2*nx)\n def haar_1(self, t1):\n ## t1: (b, c, x) with (x % 2) == 1\n # anti-symmetric-reflect padding, a.k.a. asym in matlab\n col1_xb = 2.0 * t1[:,:,-1:]\n col1_b = col1_xb - t1[:,:,-2:-1] # 2*x_{n-1} - x_{n-2}\n s1 = tf.concat([t1, col1_b], axis=-1) # out: (b, c, 2*nx)\n return s1\n def kernel_function(self, input):\n # choose float precision accordingly to input\n haar_ker = tf.cast(self.haar_ker, tf.float32) if (input.dtype==tf.float32) else self.haar_ker\n mod_x = self.ox % 2\n # input: (b, x, c)\n t1 = tf.transpose(input, perm=[0, 2, 1]) # out: (b, c, x)\n ## prepare data\n if (mod_x == 0) :\n s1 = self.haar_0(t1)\n else :\n s1 = self.haar_1(t1)\n ## s1: (b, c, 2*nx)\n s1 = tf.reshape(s1, [self.bs, self.cn, 2*self.nx, 1]) # out: (b, c, 2*nx, 1)\n # build kernels and apply to rows\n k1l = tf.reshape(haar_ker[:,0], (2, 1, 1))\n k1h = tf.reshape(haar_ker[:,1], (2, 1, 1))\n rl = tf.nn.conv1d(s1, k1l, stride=2, padding='VALID')\n rh = tf.nn.conv1d(s1, k1h, stride=2, padding='VALID')\n r = tf.concat((rl, rh), axis=-1) # out: (b, c, nx, 2)\n # r = tf.reshape(r, [self.bs, self.cn, self.nx, 2]) # out: (b, c, nx, 2)\n r = tf.transpose(r, [0, 2, 3, 1]) # out: (b, nx, 2, c)\n r = tf.reshape(r, [self.bs, self.nx, 2*self.cn]) # out: (b, nx, 2*c)\n return r\n\n########################################################################\n# Inverse wavelet transforms\n## input: (b, x, 2*c) --> output: (b, 2*x, c)\n## (with input[b,x,:c] being the channels for L wavelet)\n\nclass InvHaarWaveLayer1D(InvWaveLayer1D):\n \"\"\"1D inverse Haar trasform\"\"\"\n ########################################################################\n ## Init (with wavelet kernels)\n ########################################################################\n def __init__(self, **kwargs):\n ## Haar kernel\n s2 = math.sqrt(2) * .5 # 1/sqrt(2)\n self.haar_ker = tf.constant([s2, s2, s2, -s2], shape=(2,2), dtype=tf.float64)\n ## call constructor\n super(InvWaveLayer1D, self).__init__(**kwargs)\n ########################################################################\n ## Haar wavelet\n ########################################################################\n def kernel_function(self, input):\n # input: (b, nx, 2*c)\n # choose float precision accordingly to input\n haar_ker = tf.cast(self.haar_ker, tf.float32) if (input.dtype==tf.float32) else self.haar_ker\n t1 = tf.reshape(input, [self.bs, self.ox, self.cn])\n # out: (b, ox, c)\n t1 = tf.transpose(t1, perm=[0, 2, 1]) # out: (b, c, ox)\n t1 = tf.reshape(t1, [self.bs, self.cn, self.ox, 1]) # out: (b, c, ox, 1)\n # apply kernel to rows\n k1l = tf.reshape(haar_ker[:,0], (2, 1, 1))\n k1h = tf.reshape(haar_ker[:,1], (2, 1, 1))\n rl = tf.nn.conv1d(t1, k1l, stride=2, padding='VALID')\n rh = tf.nn.conv1d(t1, k1h, stride=2, padding='VALID')\n r = tf.concat((rl, rh), axis=-1) # out: (b, c, qx, 4)\n r = tf.reshape(r, [self.bs, self.cn, self.ox]) # out: (b, c, ox)\n r = tf.transpose(r, [0, 2, 1]) # out: (b, ox, c)\n return r\n\n \n########################################################################\n# 2D wavelet\n########################################################################\n\n########################################################################\n# Direct wavelet transform\n########################################################################\n## apply wavelet transform to each channel of the input tensor\n## input: (b, x, y, c) --> output: (b, nx, ny, 4*c)\n## (with outpuy[b,x,y,:c] being the channels for LL wavelet)\n \nclass HaarWaveLayer2D(DirWaveLayer2D):\n \"\"\"2D direct Haar trasform\"\"\"\n ########################################################################\n ## Init (with wavelet kernels)\n ########################################################################\n def __init__(self, **kwargs):\n ## Haar kernel\n s2 = math.sqrt(2) * .5 # 1/sqrt(2)\n self.haar_ker = tf.constant([s2, s2, s2, -s2], shape=(2,2), dtype=tf.float64)\n ## call constructor\n super(DirWaveLayer2D, self).__init__(**kwargs)\n ########################################################################\n ## Haar wavelet\n ########################################################################\n def haar_0(self, t1):\n ## t1: (..., z) with (z % 2) == 0\n return t1 # out: (..., 2*nz)\n def haar_1(self, t1):\n ## t1: (..., z) with (z % 2) == 1\n # anti-symmetric-reflect padding, a.k.a. asym in matlab\n col1_xb = 2.0 * t1[... , -1:]\n col1_b = col1_xb - t1[... , -2:-1] # 2*x_{n-1} - x_{n-2}\n s1 = tf.concat([t1, col1_b], axis=-1) # out: (..., 2*nz)\n return s1\n def kernel_function(self, input):\n # input: (b, x, y, c)\n # choose float precision accordingly to input\n haar_ker = tf.cast(self.haar_ker, tf.float32) if (input.dtype==tf.float32) else self.haar_ker\n mod_x = self.ox % 2\n mod_y = self.oy % 2\n ## pass 1: transform rows\n t1 = tf.transpose(input, perm=[0, 3, 1, 2]) # out: (b, c, ox, oy)\n if (mod_y == 0) :\n s1 = self.haar_0(t1)\n else :\n s1 = self.haar_1(t1)\n ## s1: (b, c, ox, 2*ny)\n s1 = tf.reshape(s1, [self.bs, self.cn*self.ox, 2*self.ny, 1])\n ## s1: (b, c*ox, 2*ny, 1)\n # build kernels and apply to rows\n k1l = tf.reshape(haar_ker[:,0], (2, 1, 1))\n k1h = tf.reshape(haar_ker[:,1], (2, 1, 1))\n rl = tf.nn.conv1d(s1, k1l, stride=2, padding='VALID')\n rh = tf.nn.conv1d(s1, k1h, stride=2, padding='VALID')\n s1 = tf.concat((rl, rh), axis=-1) # out: (b, c*ox, ny, 2)\n s1 = tf.reshape(s1, [self.bs, self.cn, self.ox, self.ny, 2])\n # out: (b, c, ox, ny, 2_y)\n ## transform columns\n t2 = tf.transpose(s1, perm=[0, 1, 3, 4, 2]) # out: (b, c, ny, 2_y, ox)\n if (mod_x == 0) :\n s2 = self.haar_0(t2)\n else :\n s2 = self.haar_1(t2)\n ## s2: (b, c, ny, 2_y, 2*nx)\n s2 = tf.reshape(s2, [self.bs, self.cn*self.ny*2, 2*self.nx, 1])\n # out: (b, c*ny*2_y, 2*nx, 1)\n # build kernels and apply kernel to columns\n rl = tf.nn.conv1d(s2, k1l, stride=2, padding='VALID')\n rh = tf.nn.conv1d(s2, k1h, stride=2, padding='VALID')\n r = tf.concat((rl, rh), axis=-1) # out: (b, c*ny*2_y, nx, 2_x)\n r = tf.reshape(r, [self.bs, self.cn, self.ny, 2, self.nx, 2])\n # out: (b, c, ny, 2_y, nx, 2_x)\n r = tf.transpose(r, perm=[0, 4, 2, 3, 5, 1]) # out: (b, nx, ny, 2_y, 2_x, c)\n r = tf.reshape(r, [self.bs, self.nx, self.ny, 4*self.cn])\n # out: (b, ny, nx, 4*c)\n return r\n\n########################################################################\n# Inverse wavelet transform\n########################################################################\n## input: (b, x, y, 4*c) --> output: (b, 2*x, 2*y, c)\n## (with input[b,x,y,:c] being the channels for LL wavelet)\n\nclass InvHaarWaveLayer2D(InvWaveLayer2D):\n \"\"\"2D inverse Haar trasform\"\"\"\n ########################################################################\n ## Init (with wavelet kernels)\n ########################################################################\n def __init__(self, **kwargs):\n ## Haar kernel\n s2 = math.sqrt(2) * .5 # 1/sqrt(2)\n self.haar_ker = tf.constant([s2, s2, s2, -s2], shape=(2,2), dtype=tf.float64)\n ## call constructor\n super(InvWaveLayer2D, self).__init__(**kwargs)\n ########################################################################\n ## Inverse Haar wavelet\n ########################################################################\n def kernel_function(self, input):\n # input: (b, nx, ny, 4*c)\n # choose float precision accordingly to input\n haar_ker = tf.cast(self.haar_ker, tf.float32) if (input.dtype==tf.float32) else self.haar_ker\n t1 = tf.reshape(input, [self.bs, self.nx, self.ny, 2, 2, self.cn])\n # out: (b, x, y, 2_y, 2_x, c)\n t1 = tf.transpose(t1, perm=[0, 5, 2, 3, 1, 4])\n # out: (b, c, y, 2_y, x, 2_x)\n t1 = tf.reshape(t1, [self.bs, self.cn*self.oy, self.ox, 1])\n # out: (b, c*oy, ox, 1)\n # apply kernel to x\n k1l = tf.reshape(haar_ker[:,0], (2, 1, 1))\n k1h = tf.reshape(haar_ker[:,1], (2, 1, 1))\n rl = tf.nn.conv1d(t1, k1l, stride=2, padding='VALID')\n rh = tf.nn.conv1d(t1, k1h, stride=2, padding='VALID')\n s1 = tf.concat((rl, rh), axis=-1) # out: (b, c*oy, qx, 4)\n s1 = tf.reshape(s1, [self.bs, self.cn, self.oy, self.ox])\n # out: (b, c, oy, ox)\n s1 = tf.transpose(s1, perm=[0, 1, 3, 2]) # out: (b, c, ox, oy)\n s1 = tf.reshape(s1, [self.bs, self.cn*self.ox, self.oy, 1])\n # out: (b, c*ox, oy, 1)\n # apply kernel to y\n rl = tf.nn.conv1d(s1, k1l, stride=2, padding='VALID')\n rh = tf.nn.conv1d(s1, k1h, stride=2, padding='VALID')\n r = tf.concat((rl, rh), axis=-1) # out: (b, c*ox, qy, 4)\n r = tf.reshape(r, [self.bs, self.cn, self.ox, self.oy])\n # out: (b, c, ox, oy)\n r = tf.transpose(r, [0, 2, 3, 1]) # out: (b, ox, oy, c)\n return r\n\n"
] |
[
[
"tensorflow.transpose",
"tensorflow.concat",
"tensorflow.constant",
"tensorflow.reshape",
"tensorflow.cast",
"tensorflow.nn.conv1d"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
martijnberger/OpenGL-tests
|
[
"cd259d923a70c22566fa3dc140764b409181cfc5"
] |
[
"pyglfw/test-opengl-2.1.py"
] |
[
"__author__ = 'Martijn Berger'\n\nimport OpenGL.GL as gl\nimport numpy as np\nimport ctypes\nimport glfw\n\nNULL = ctypes.c_void_p(0)\n\nvertex_data = np.array([-1,-1, -1,+1, +1,-1, +1,+1 ], dtype=np.float32)\n\ncolor_data = np.array([1,0,0,1, 0,1,0,1, 0,0,1,1, 1,1,0,1], dtype=np.float32)\n\ndef main():\n # Initialize the library\n if not glfw.init():\n return\n # Create a windowed mode window and its OpenGL context\n window = glfw.create_window(640, 480, \"OpenGL 2.1\", None, None)\n if not window:\n glfw.terminate()\n return\n\n # Make the window's context current\n glfw.make_context_current(window)\n\n # Loop until the user closes the window\n while not glfw.window_should_close(window):\n # Render here, e.g. using pyOpenGL\n gl.glClear(gl.GL_COLOR_BUFFER_BIT)\n\n gl.glColorPointer(4, gl.GL_FLOAT, 0, color_data)\n gl.glEnableClientState(gl.GL_COLOR_ARRAY)\n gl.glVertexPointer(2, gl.GL_FLOAT, 0, vertex_data)\n gl.glEnableClientState(gl.GL_VERTEX_ARRAY)\n\n gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)\n\n # Swap front and back buffers\n glfw.swap_buffers(window)\n\n # Poll for and process events\n glfw.poll_events()\n\n glfw.terminate()\n\nif __name__ == \"__main__\":\n main()\n\n\n\n"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
dariovins/pandas
|
[
"ea2e26ae7d700d7fd363ea5bfc05d2fe3fb8a5ee"
] |
[
"pandas/core/indexes/range.py"
] |
[
"from datetime import timedelta\nimport operator\nfrom sys import getsizeof\nfrom typing import Optional, Union\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs import index as libindex\nimport pandas.compat as compat\nfrom pandas.compat.numpy import function as nv\nfrom pandas.util._decorators import Appender, cache_readonly\n\nfrom pandas.core.dtypes.common import (\n ensure_platform_int,\n ensure_python_int,\n is_integer,\n is_integer_dtype,\n is_list_like,\n is_scalar,\n is_timedelta64_dtype,\n)\nfrom pandas.core.dtypes.generic import ABCTimedeltaIndex\n\nfrom pandas.core import ops\nimport pandas.core.common as com\nfrom pandas.core.construction import extract_array\nimport pandas.core.indexes.base as ibase\nfrom pandas.core.indexes.base import Index, _index_shared_docs\nfrom pandas.core.indexes.numeric import Int64Index\nfrom pandas.core.ops.common import unpack_zerodim_and_defer\n\nfrom pandas.io.formats.printing import pprint_thing\n\n\nclass RangeIndex(Int64Index):\n \"\"\"\n Immutable Index implementing a monotonic integer range.\n\n RangeIndex is a memory-saving special case of Int64Index limited to\n representing monotonic ranges. Using RangeIndex may in some instances\n improve computing speed.\n\n This is the default index type used\n by DataFrame and Series when no explicit index is provided by the user.\n\n Parameters\n ----------\n start : int (default: 0), or other RangeIndex instance\n If int and \"stop\" is not given, interpreted as \"stop\" instead.\n stop : int (default: 0)\n step : int (default: 1)\n name : object, optional\n Name to be stored in the index.\n copy : bool, default False\n Unused, accepted for homogeneity with other index types.\n\n Attributes\n ----------\n start\n stop\n step\n\n Methods\n -------\n from_range\n\n See Also\n --------\n Index : The base pandas Index type.\n Int64Index : Index of int64 data.\n \"\"\"\n\n _typ = \"rangeindex\"\n _engine_type = libindex.Int64Engine\n _range: range\n\n # check whether self._data has been called\n _cached_data: Optional[np.ndarray] = None\n # --------------------------------------------------------------------\n # Constructors\n\n def __new__(\n cls, start=None, stop=None, step=None, dtype=None, copy=False, name=None,\n ):\n\n cls._validate_dtype(dtype)\n\n # RangeIndex\n if isinstance(start, RangeIndex):\n name = start.name if name is None else name\n start = start._range\n return cls._simple_new(start, dtype=dtype, name=name)\n\n # validate the arguments\n if com.all_none(start, stop, step):\n raise TypeError(\"RangeIndex(...) must be called with integers\")\n\n start = ensure_python_int(start) if start is not None else 0\n\n if stop is None:\n start, stop = 0, start\n else:\n stop = ensure_python_int(stop)\n\n step = ensure_python_int(step) if step is not None else 1\n if step == 0:\n raise ValueError(\"Step must not be zero\")\n\n rng = range(start, stop, step)\n return cls._simple_new(rng, dtype=dtype, name=name)\n\n @classmethod\n def from_range(cls, data, name=None, dtype=None):\n \"\"\"\n Create RangeIndex from a range object.\n\n Returns\n -------\n RangeIndex\n \"\"\"\n if not isinstance(data, range):\n raise TypeError(\n \"{0}(...) must be called with object coercible to a \"\n \"range, {1} was passed\".format(cls.__name__, repr(data))\n )\n\n cls._validate_dtype(dtype)\n return cls._simple_new(data, dtype=dtype, name=name)\n\n @classmethod\n def _simple_new(cls, values, name=None, dtype=None):\n result = object.__new__(cls)\n\n # handle passed None, non-integers\n if values is None:\n # empty\n values = range(0, 0, 1)\n elif not isinstance(values, range):\n return Index(values, dtype=dtype, name=name)\n\n result._range = values\n result.name = name\n\n result._reset_identity()\n return result\n\n # --------------------------------------------------------------------\n\n @cache_readonly\n def _constructor(self):\n \"\"\" return the class to use for construction \"\"\"\n return Int64Index\n\n @property\n def _data(self):\n \"\"\"\n An int array that for performance reasons is created only when needed.\n\n The constructed array is saved in ``_cached_data``. This allows us to\n check if the array has been created without accessing ``_data`` and\n triggering the construction.\n \"\"\"\n if self._cached_data is None:\n self._cached_data = np.arange(\n self.start, self.stop, self.step, dtype=np.int64\n )\n return self._cached_data\n\n @cache_readonly\n def _int64index(self):\n return Int64Index._simple_new(self._data, name=self.name)\n\n def _get_data_as_items(self):\n \"\"\" return a list of tuples of start, stop, step \"\"\"\n rng = self._range\n return [(\"start\", rng.start), (\"stop\", rng.stop), (\"step\", rng.step)]\n\n def __reduce__(self):\n d = self._get_attributes_dict()\n d.update(dict(self._get_data_as_items()))\n return ibase._new_Index, (self.__class__, d), None\n\n # --------------------------------------------------------------------\n # Rendering Methods\n\n def _format_attrs(self):\n \"\"\"\n Return a list of tuples of the (attr, formatted_value)\n \"\"\"\n attrs = self._get_data_as_items()\n if self.name is not None:\n attrs.append((\"name\", ibase.default_pprint(self.name)))\n return attrs\n\n def _format_data(self, name=None):\n # we are formatting thru the attributes\n return None\n\n def _format_with_header(self, header, na_rep=\"NaN\", **kwargs):\n return header + list(map(pprint_thing, self._range))\n\n # --------------------------------------------------------------------\n _deprecation_message = (\n \"RangeIndex.{} is deprecated and will be \"\n \"removed in a future version. Use RangeIndex.{} \"\n \"instead\"\n )\n\n @cache_readonly\n def start(self):\n \"\"\"\n The value of the `start` parameter (``0`` if this was not supplied).\n \"\"\"\n # GH 25710\n return self._range.start\n\n @property\n def _start(self):\n \"\"\"\n The value of the `start` parameter (``0`` if this was not supplied).\n\n .. deprecated:: 0.25.0\n Use ``start`` instead.\n \"\"\"\n warnings.warn(\n self._deprecation_message.format(\"_start\", \"start\"),\n DeprecationWarning,\n stacklevel=2,\n )\n return self.start\n\n @cache_readonly\n def stop(self):\n \"\"\"\n The value of the `stop` parameter.\n \"\"\"\n return self._range.stop\n\n @property\n def _stop(self):\n \"\"\"\n The value of the `stop` parameter.\n\n .. deprecated:: 0.25.0\n Use ``stop`` instead.\n \"\"\"\n # GH 25710\n warnings.warn(\n self._deprecation_message.format(\"_stop\", \"stop\"),\n DeprecationWarning,\n stacklevel=2,\n )\n return self.stop\n\n @cache_readonly\n def step(self):\n \"\"\"\n The value of the `step` parameter (``1`` if this was not supplied).\n \"\"\"\n # GH 25710\n return self._range.step\n\n @property\n def _step(self):\n \"\"\"\n The value of the `step` parameter (``1`` if this was not supplied).\n\n .. deprecated:: 0.25.0\n Use ``step`` instead.\n \"\"\"\n # GH 25710\n warnings.warn(\n self._deprecation_message.format(\"_step\", \"step\"),\n DeprecationWarning,\n stacklevel=2,\n )\n return self.step\n\n @cache_readonly\n def nbytes(self) -> int:\n \"\"\"\n Return the number of bytes in the underlying data.\n \"\"\"\n rng = self._range\n return getsizeof(rng) + sum(\n getsizeof(getattr(rng, attr_name))\n for attr_name in [\"start\", \"stop\", \"step\"]\n )\n\n def memory_usage(self, deep: bool = False) -> int:\n \"\"\"\n Memory usage of my values\n\n Parameters\n ----------\n deep : bool\n Introspect the data deeply, interrogate\n `object` dtypes for system-level memory consumption\n\n Returns\n -------\n bytes used\n\n Notes\n -----\n Memory usage does not include memory consumed by elements that\n are not components of the array if deep=False\n\n See Also\n --------\n numpy.ndarray.nbytes\n \"\"\"\n return self.nbytes\n\n @property\n def dtype(self) -> np.dtype:\n return np.dtype(np.int64)\n\n @property\n def is_unique(self) -> bool:\n \"\"\" return if the index has unique values \"\"\"\n return True\n\n @cache_readonly\n def is_monotonic_increasing(self) -> bool:\n return self._range.step > 0 or len(self) <= 1\n\n @cache_readonly\n def is_monotonic_decreasing(self) -> bool:\n return self._range.step < 0 or len(self) <= 1\n\n @property\n def has_duplicates(self) -> bool:\n return False\n\n def __contains__(self, key: Union[int, np.integer]) -> bool:\n hash(key)\n try:\n key = ensure_python_int(key)\n except TypeError:\n return False\n return key in self._range\n\n @Appender(_index_shared_docs[\"get_loc\"])\n def get_loc(self, key, method=None, tolerance=None):\n if is_integer(key) and method is None and tolerance is None:\n new_key = int(key)\n try:\n return self._range.index(new_key)\n except ValueError:\n raise KeyError(key)\n return super().get_loc(key, method=method, tolerance=tolerance)\n\n @Appender(_index_shared_docs[\"get_indexer\"])\n def get_indexer(self, target, method=None, limit=None, tolerance=None):\n if com.any_not_none(method, tolerance, limit) or not is_list_like(target):\n return super().get_indexer(\n target, method=method, tolerance=tolerance, limit=limit\n )\n\n if self.step > 0:\n start, stop, step = self.start, self.stop, self.step\n else:\n # GH 28678: work on reversed range for simplicity\n reverse = self._range[::-1]\n start, stop, step = reverse.start, reverse.stop, reverse.step\n\n target_array = np.asarray(target)\n if not (is_integer_dtype(target_array) and target_array.ndim == 1):\n # checks/conversions/roundings are delegated to general method\n return super().get_indexer(target, method=method, tolerance=tolerance)\n\n locs = target_array - start\n valid = (locs % step == 0) & (locs >= 0) & (target_array < stop)\n locs[~valid] = -1\n locs[valid] = locs[valid] / step\n\n if step != self.step:\n # We reversed this range: transform to original locs\n locs[valid] = len(self) - 1 - locs[valid]\n return ensure_platform_int(locs)\n\n def tolist(self):\n return list(self._range)\n\n @Appender(_index_shared_docs[\"_shallow_copy\"])\n def _shallow_copy(self, values=None, **kwargs):\n if values is None:\n name = kwargs.get(\"name\", self.name)\n return self._simple_new(self._range, name=name)\n else:\n kwargs.setdefault(\"name\", self.name)\n return self._int64index._shallow_copy(values, **kwargs)\n\n @Appender(ibase._index_shared_docs[\"copy\"])\n def copy(self, name=None, deep=False, dtype=None, **kwargs):\n self._validate_dtype(dtype)\n if name is None:\n name = self.name\n return self.from_range(self._range, name=name)\n\n def _minmax(self, meth):\n no_steps = len(self) - 1\n if no_steps == -1:\n return np.nan\n elif (meth == \"min\" and self.step > 0) or (meth == \"max\" and self.step < 0):\n return self.start\n\n return self.start + self.step * no_steps\n\n def min(self, axis=None, skipna=True, *args, **kwargs):\n \"\"\"The minimum value of the RangeIndex\"\"\"\n nv.validate_minmax_axis(axis)\n nv.validate_min(args, kwargs)\n return self._minmax(\"min\")\n\n def max(self, axis=None, skipna=True, *args, **kwargs):\n \"\"\"The maximum value of the RangeIndex\"\"\"\n nv.validate_minmax_axis(axis)\n nv.validate_max(args, kwargs)\n return self._minmax(\"max\")\n\n def argsort(self, *args, **kwargs):\n \"\"\"\n Returns the indices that would sort the index and its\n underlying data.\n\n Returns\n -------\n argsorted : numpy array\n\n See Also\n --------\n numpy.ndarray.argsort\n \"\"\"\n nv.validate_argsort(args, kwargs)\n\n if self._range.step > 0:\n return np.arange(len(self))\n else:\n return np.arange(len(self) - 1, -1, -1)\n\n def equals(self, other):\n \"\"\"\n Determines if two Index objects contain the same elements.\n \"\"\"\n if isinstance(other, RangeIndex):\n return self._range == other._range\n return super().equals(other)\n\n def intersection(self, other, sort=False):\n \"\"\"\n Form the intersection of two Index objects.\n\n Parameters\n ----------\n other : Index or array-like\n sort : False or None, default False\n Sort the resulting index if possible\n\n .. versionadded:: 0.24.0\n\n .. versionchanged:: 0.24.1\n\n Changed the default to ``False`` to match the behaviour\n from before 0.24.0.\n\n Returns\n -------\n intersection : Index\n \"\"\"\n self._validate_sort_keyword(sort)\n\n if self.equals(other):\n return self._get_reconciled_name_object(other)\n\n if not isinstance(other, RangeIndex):\n return super().intersection(other, sort=sort)\n\n if not len(self) or not len(other):\n return self._simple_new(None)\n\n first = self._range[::-1] if self.step < 0 else self._range\n second = other._range[::-1] if other.step < 0 else other._range\n\n # check whether intervals intersect\n # deals with in- and decreasing ranges\n int_low = max(first.start, second.start)\n int_high = min(first.stop, second.stop)\n if int_high <= int_low:\n return self._simple_new(None)\n\n # Method hint: linear Diophantine equation\n # solve intersection problem\n # performance hint: for identical step sizes, could use\n # cheaper alternative\n gcd, s, t = self._extended_gcd(first.step, second.step)\n\n # check whether element sets intersect\n if (first.start - second.start) % gcd:\n return self._simple_new(None)\n\n # calculate parameters for the RangeIndex describing the\n # intersection disregarding the lower bounds\n tmp_start = first.start + (second.start - first.start) * first.step // gcd * s\n new_step = first.step * second.step // gcd\n new_range = range(tmp_start, int_high, new_step)\n new_index = self._simple_new(new_range)\n\n # adjust index to limiting interval\n new_start = new_index._min_fitting_element(int_low)\n new_range = range(new_start, new_index.stop, new_index.step)\n new_index = self._simple_new(new_range)\n\n if (self.step < 0 and other.step < 0) is not (new_index.step < 0):\n new_index = new_index[::-1]\n if sort is None:\n new_index = new_index.sort_values()\n return new_index\n\n def _min_fitting_element(self, lower_limit):\n \"\"\"Returns the smallest element greater than or equal to the limit\"\"\"\n no_steps = -(-(lower_limit - self.start) // abs(self.step))\n return self.start + abs(self.step) * no_steps\n\n def _max_fitting_element(self, upper_limit):\n \"\"\"Returns the largest element smaller than or equal to the limit\"\"\"\n no_steps = (upper_limit - self.start) // abs(self.step)\n return self.start + abs(self.step) * no_steps\n\n def _extended_gcd(self, a, b):\n \"\"\"\n Extended Euclidean algorithms to solve Bezout's identity:\n a*x + b*y = gcd(x, y)\n Finds one particular solution for x, y: s, t\n Returns: gcd, s, t\n \"\"\"\n s, old_s = 0, 1\n t, old_t = 1, 0\n r, old_r = b, a\n while r:\n quotient = old_r // r\n old_r, r = r, old_r - quotient * r\n old_s, s = s, old_s - quotient * s\n old_t, t = t, old_t - quotient * t\n return old_r, old_s, old_t\n\n def _union(self, other, sort):\n \"\"\"\n Form the union of two Index objects and sorts if possible\n\n Parameters\n ----------\n other : Index or array-like\n\n sort : False or None, default None\n Whether to sort resulting index. ``sort=None`` returns a\n monotonically increasing ``RangeIndex`` if possible or a sorted\n ``Int64Index`` if not. ``sort=False`` always returns an\n unsorted ``Int64Index``\n\n .. versionadded:: 0.25.0\n\n Returns\n -------\n union : Index\n \"\"\"\n if not len(other) or self.equals(other) or not len(self):\n return super()._union(other, sort=sort)\n\n if isinstance(other, RangeIndex) and sort is None:\n start_s, step_s = self.start, self.step\n end_s = self.start + self.step * (len(self) - 1)\n start_o, step_o = other.start, other.step\n end_o = other.start + other.step * (len(other) - 1)\n if self.step < 0:\n start_s, step_s, end_s = end_s, -step_s, start_s\n if other.step < 0:\n start_o, step_o, end_o = end_o, -step_o, start_o\n if len(self) == 1 and len(other) == 1:\n step_s = step_o = abs(self.start - other.start)\n elif len(self) == 1:\n step_s = step_o\n elif len(other) == 1:\n step_o = step_s\n start_r = min(start_s, start_o)\n end_r = max(end_s, end_o)\n if step_o == step_s:\n if (\n (start_s - start_o) % step_s == 0\n and (start_s - end_o) <= step_s\n and (start_o - end_s) <= step_s\n ):\n return self.__class__(start_r, end_r + step_s, step_s)\n if (\n (step_s % 2 == 0)\n and (abs(start_s - start_o) <= step_s / 2)\n and (abs(end_s - end_o) <= step_s / 2)\n ):\n return self.__class__(start_r, end_r + step_s / 2, step_s / 2)\n elif step_o % step_s == 0:\n if (\n (start_o - start_s) % step_s == 0\n and (start_o + step_s >= start_s)\n and (end_o - step_s <= end_s)\n ):\n return self.__class__(start_r, end_r + step_s, step_s)\n elif step_s % step_o == 0:\n if (\n (start_s - start_o) % step_o == 0\n and (start_s + step_o >= start_o)\n and (end_s - step_o <= end_o)\n ):\n return self.__class__(start_r, end_r + step_o, step_o)\n return self._int64index._union(other, sort=sort)\n\n @Appender(_index_shared_docs[\"join\"])\n def join(self, other, how=\"left\", level=None, return_indexers=False, sort=False):\n if how == \"outer\" and self is not other:\n # note: could return RangeIndex in more circumstances\n return self._int64index.join(other, how, level, return_indexers, sort)\n\n return super().join(other, how, level, return_indexers, sort)\n\n def _concat_same_dtype(self, indexes, name):\n \"\"\"\n Concatenates multiple RangeIndex instances. All members of \"indexes\" must\n be of type RangeIndex; result will be RangeIndex if possible, Int64Index\n otherwise. E.g.:\n indexes = [RangeIndex(3), RangeIndex(3, 6)] -> RangeIndex(6)\n indexes = [RangeIndex(3), RangeIndex(4, 6)] -> Int64Index([0,1,2,4,5])\n \"\"\"\n start = step = next_ = None\n\n # Filter the empty indexes\n non_empty_indexes = [obj for obj in indexes if len(obj)]\n\n for obj in non_empty_indexes:\n rng: range = obj._range\n\n if start is None:\n # This is set by the first non-empty index\n start = rng.start\n if step is None and len(rng) > 1:\n step = rng.step\n elif step is None:\n # First non-empty index had only one element\n if rng.start == start:\n result = Int64Index(np.concatenate([x._values for x in indexes]))\n return result.rename(name)\n\n step = rng.start - start\n\n non_consecutive = (step != rng.step and len(rng) > 1) or (\n next_ is not None and rng.start != next_\n )\n if non_consecutive:\n result = Int64Index(np.concatenate([x._values for x in indexes]))\n return result.rename(name)\n\n if step is not None:\n next_ = rng[-1] + step\n\n if non_empty_indexes:\n # Get the stop value from \"next\" or alternatively\n # from the last non-empty index\n stop = non_empty_indexes[-1].stop if next_ is None else next_\n return RangeIndex(start, stop, step).rename(name)\n\n # Here all \"indexes\" had 0 length, i.e. were empty.\n # In this case return an empty range index.\n return RangeIndex(0, 0).rename(name)\n\n def __len__(self) -> int:\n \"\"\"\n return the length of the RangeIndex\n \"\"\"\n return len(self._range)\n\n @property\n def size(self) -> int:\n return len(self)\n\n def __getitem__(self, key):\n \"\"\"\n Conserve RangeIndex type for scalar and slice keys.\n \"\"\"\n if isinstance(key, slice):\n new_range = self._range[key]\n return self._simple_new(new_range, name=self.name)\n elif is_integer(key):\n new_key = int(key)\n try:\n return self._range[new_key]\n except IndexError:\n raise IndexError(\n \"index {key} is out of bounds for axis 0 \"\n \"with size {size}\".format(key=key, size=len(self))\n )\n elif is_scalar(key):\n raise IndexError(\n \"only integers, slices (`:`), \"\n \"ellipsis (`...`), numpy.newaxis (`None`) \"\n \"and integer or boolean \"\n \"arrays are valid indices\"\n )\n # fall back to Int64Index\n return super().__getitem__(key)\n\n @unpack_zerodim_and_defer(\"__floordiv__\")\n def __floordiv__(self, other):\n\n if is_integer(other) and other != 0:\n if len(self) == 0 or self.start % other == 0 and self.step % other == 0:\n start = self.start // other\n step = self.step // other\n stop = start + len(self) * step\n new_range = range(start, stop, step or 1)\n return self._simple_new(new_range, name=self.name)\n if len(self) == 1:\n start = self.start // other\n new_range = range(start, start + 1, 1)\n return self._simple_new(new_range, name=self.name)\n return self._int64index // other\n\n def all(self) -> bool:\n return 0 not in self._range\n\n def any(self) -> bool:\n return any(self._range)\n\n @classmethod\n def _add_numeric_methods_binary(cls):\n \"\"\" add in numeric methods, specialized to RangeIndex \"\"\"\n\n def _make_evaluate_binop(op, step=False):\n \"\"\"\n Parameters\n ----------\n op : callable that accepts 2 parms\n perform the binary op\n step : callable, optional, default to False\n op to apply to the step parm if not None\n if False, use the existing step\n \"\"\"\n\n @unpack_zerodim_and_defer(op.__name__)\n def _evaluate_numeric_binop(self, other):\n if isinstance(other, ABCTimedeltaIndex):\n # Defer to TimedeltaIndex implementation\n return NotImplemented\n elif isinstance(other, (timedelta, np.timedelta64)):\n # GH#19333 is_integer evaluated True on timedelta64,\n # so we need to catch these explicitly\n return op(self._int64index, other)\n elif is_timedelta64_dtype(other):\n # Must be an np.ndarray; GH#22390\n return op(self._int64index, other)\n\n other = extract_array(other, extract_numpy=True)\n attrs = self._get_attributes_dict()\n\n left, right = self, other\n\n try:\n # apply if we have an override\n if step:\n with np.errstate(all=\"ignore\"):\n rstep = step(left.step, right)\n\n # we don't have a representable op\n # so return a base index\n if not is_integer(rstep) or not rstep:\n raise ValueError\n\n else:\n rstep = left.step\n\n with np.errstate(all=\"ignore\"):\n rstart = op(left.start, right)\n rstop = op(left.stop, right)\n\n result = self.__class__(rstart, rstop, rstep, **attrs)\n\n # for compat with numpy / Int64Index\n # even if we can represent as a RangeIndex, return\n # as a Float64Index if we have float-like descriptors\n if not all(is_integer(x) for x in [rstart, rstop, rstep]):\n result = result.astype(\"float64\")\n\n return result\n\n except (ValueError, TypeError, ZeroDivisionError):\n # Defer to Int64Index implementation\n return op(self._int64index, other)\n # TODO: Do attrs get handled reliably?\n\n name = \"__{name}__\".format(name=op.__name__)\n return compat.set_function_name(_evaluate_numeric_binop, name, cls)\n\n cls.__add__ = _make_evaluate_binop(operator.add)\n cls.__radd__ = _make_evaluate_binop(ops.radd)\n cls.__sub__ = _make_evaluate_binop(operator.sub)\n cls.__rsub__ = _make_evaluate_binop(ops.rsub)\n cls.__mul__ = _make_evaluate_binop(operator.mul, step=operator.mul)\n cls.__rmul__ = _make_evaluate_binop(ops.rmul, step=ops.rmul)\n cls.__truediv__ = _make_evaluate_binop(operator.truediv, step=operator.truediv)\n cls.__rtruediv__ = _make_evaluate_binop(ops.rtruediv, step=ops.rtruediv)\n\n\nRangeIndex._add_numeric_methods()\n"
] |
[
[
"numpy.asarray",
"numpy.dtype",
"pandas.core.indexes.base.Index",
"numpy.concatenate",
"pandas.core.ops.common.unpack_zerodim_and_defer",
"pandas.core.common.any_not_none",
"numpy.arange",
"pandas.core.common.all_none",
"pandas.compat.set_function_name",
"pandas.core.indexes.base.default_pprint",
"pandas.core.dtypes.common.is_list_like",
"pandas.core.dtypes.common.is_integer_dtype",
"pandas.util._decorators.Appender",
"pandas.core.dtypes.common.is_timedelta64_dtype",
"pandas.compat.numpy.function.validate_argsort",
"pandas.core.indexes.numeric.Int64Index._simple_new",
"pandas.core.dtypes.common.ensure_platform_int",
"numpy.errstate",
"pandas.compat.numpy.function.validate_minmax_axis",
"pandas.core.dtypes.common.is_scalar",
"pandas.compat.numpy.function.validate_max",
"pandas.core.dtypes.common.is_integer",
"pandas.compat.numpy.function.validate_min",
"pandas.core.dtypes.common.ensure_python_int",
"pandas.core.construction.extract_array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.0",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
vlad17/timedime
|
[
"90473c3026e040c02a1775325aed0cffa2b77da8"
] |
[
"timefly/tags.py"
] |
[
"\"\"\"\nHandling for the tags from calendar events.\n\"\"\"\n\nimport pandas as pd\n\n\ndef explode(df, min_support_count=None):\n \"\"\"\n Given a dataframe with a tags column that contains an iterable of tags,\n creates a new dataframe containing the (sparse) binary\n columns for each tag. The index is the same.\n\n Also, generates new tags identical to the \"summary\" column\n for all summaries that appear\n more than min_support_count times if that's not none.\n\n The index is preserved.\n \"\"\"\n # TODO: to avoid actually exploding memory, we could\n # do one tag at a time and explicitly construct the sparse vector.\n # probably need to switch from pandas to a dict.\n\n # just treat the summary as a tag itself too\n\n df = df.copy()\n df[\"tags\"] = df[[\"tags\", \"summary\"]].apply(\n lambda x: {y for y in x.tags.union(frozenset([x.summary])) if y},\n axis=1)\n\n exploded = df.tags.apply(lambda x: pd.Series({tag: True for tag in x}))\n exploded = exploded.fillna(False)\n return exploded\n\ndef df_filter(df, ef, tag=None, keep=True):\n \"\"\"\n No-op if the filter tag is set to None.format\n\n Otherwise, only includes the rows associated with the string tag,\n which must be a column in the exploded dataframe.\n\n if keep is false, removes the column associated with the tag.\n\n Returns the modified df, ef.\n \"\"\"\n if not tag:\n return df, ef\n\n chosen = ef[tag]\n df = df[chosen].copy()\n def remove_tag(s):\n s = set(s)\n s.remove(tag)\n return frozenset(s)\n df.loc[:, 'tags'] = df.tags.apply(remove_tag)\n ef = ef[chosen].drop(columns=tag)\n\n print('only keeping {:.2%} of rows matching {}'.format(chosen.mean(), tag))\n return df, ef\n"
] |
[
[
"pandas.Series"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
yohan-pg/stylegan2-ada-pytorch
|
[
"e1225b08d55ff5ca38e1646fa430d3c3c3bb3c68"
] |
[
"torch_utils/training_stats.py"
] |
[
"# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.\n#\n# NVIDIA CORPORATION and its licensors retain all intellectual property\n# and proprietary rights in and to this software, related documentation\n# and any modifications thereto. Any use, reproduction, disclosure or\n# distribution of this software and related documentation without an express\n# license agreement from NVIDIA CORPORATION is strictly prohibited.\n\n\"\"\"Facilities for reporting and collecting training statistics across\nmultiple processes and devices. The interface is designed to minimize\nsynchronization overhead as well as the amount of boilerplate in user\ncode.\"\"\"\n\nimport re\nimport numpy as np\nimport torch\nimport dnnlib\n\nfrom . import misc\n\n# ----------------------------------------------------------------------------\n\n_num_moments = 3 # [num_scalars, sum_of_scalars, sum_of_squares]\n_reduce_dtype = torch.float32 # Data type to use for initial per-tensor reduction.\n_counter_dtype = torch.float64 # Data type to use for the internal counters.\n_rank = 0 # Rank of the current process.\n_sync_device = (\n None # Device to use for multiprocess communication. None = single-process.\n)\n_sync_called = False # Has _sync() been called yet?\n_counters = (\n dict()\n) # Running counters on each device, updated by report(): name => device => torch.Tensor\n_cumulative = (\n dict()\n) # Cumulative counters on the CPU, updated by _sync(): name => torch.Tensor\n\n# ----------------------------------------------------------------------------\n\n\ndef init_multiprocessing(rank, sync_device):\n r\"\"\"Initializes `torch_utils.training_stats` for collecting statistics\n across multiple processes.\n\n This function must be called after\n `torch.distributed.init_process_group()` and before `Collector.update()`.\n The call is not necessary if multi-process collection is not needed.\n\n Args:\n rank: Rank of the current process.\n sync_device: PyTorch device to use for inter-process\n communication, or None to disable multi-process\n collection. Typically `torch.device('cuda', rank)`.\n \"\"\"\n global _rank, _sync_device\n assert not _sync_called\n _rank = rank\n _sync_device = sync_device\n\n\n# ----------------------------------------------------------------------------\n\n\[email protected]_function\ndef report(name, value):\n r\"\"\"Broadcasts the given set of scalars to all interested instances of\n `Collector`, across device and process boundaries.\n\n This function is expected to be extremely cheap and can be safely\n called from anywhere in the training loop, loss function, or inside a\n `torch.nn.Module`.\n\n Warning: The current implementation expects the set of unique names to\n be consistent across processes. Please make sure that `report()` is\n called at least once for each unique name by each process, and in the\n same order. If a given process has no scalars to broadcast, it can do\n `report(name, [])` (empty list).\n\n Args:\n name: Arbitrary string specifying the name of the statistic.\n Averages are accumulated separately for each unique name.\n value: Arbitrary set of scalars. Can be a list, tuple,\n NumPy array, PyTorch tensor, or Python scalar.\n\n Returns:\n The same `value` that was passed in.\n \"\"\"\n if name not in _counters:\n _counters[name] = dict()\n\n elems = torch.as_tensor(value)\n if elems.numel() == 0:\n return value\n\n elems = elems.detach().flatten().to(_reduce_dtype)\n moments = torch.stack(\n [\n torch.ones_like(elems).sum(),\n elems.sum(),\n elems.square().sum(),\n ]\n )\n assert moments.ndim == 1 and moments.shape[0] == _num_moments\n moments = moments.to(_counter_dtype)\n\n device = moments.device\n if device not in _counters[name]:\n _counters[name][device] = torch.zeros_like(moments)\n _counters[name][device].add_(moments)\n return value\n\n\n# ----------------------------------------------------------------------------\n\n\ndef report0(name, value):\n r\"\"\"Broadcasts the given set of scalars by the first process (`rank = 0`),\n but ignores any scalars provided by the other processes.\n See `report()` for further details.\n \"\"\"\n report(name, value if _rank == 0 else [])\n return value\n\n\n# ----------------------------------------------------------------------------\n\n\nclass Collector:\n r\"\"\"Collects the scalars broadcasted by `report()` and `report0()` and\n computes their long-term averages (mean and standard deviation) over\n user-defined periods of time.\n\n The averages are first collected into internal counters that are not\n directly visible to the user. They are then copied to the user-visible\n state as a result of calling `update()` and can then be queried using\n `mean()`, `std()`, `as_dict()`, etc. Calling `update()` also resets the\n internal counters for the next round, so that the user-visible state\n effectively reflects averages collected between the last two calls to\n `update()`.\n\n Args:\n regex: Regular expression defining which statistics to\n collect. The default is to collect everything.\n keep_previous: Whether to retain the previous averages if no\n scalars were collected on a given round\n (default: True).\n \"\"\"\n\n def __init__(self, regex=\".*\", keep_previous=True):\n self._regex = re.compile(regex)\n self._keep_previous = keep_previous\n self._cumulative = dict()\n self._moments = dict()\n self.update()\n self._moments.clear()\n\n def names(self):\n r\"\"\"Returns the names of all statistics broadcasted so far that\n match the regular expression specified at construction time.\n \"\"\"\n return [name for name in _counters if self._regex.fullmatch(name)]\n\n def update(self):\n r\"\"\"Copies current values of the internal counters to the\n user-visible state and resets them for the next round.\n\n If `keep_previous=True` was specified at construction time, the\n operation is skipped for statistics that have received no scalars\n since the last update, retaining their previous averages.\n\n This method performs a number of GPU-to-CPU transfers and one\n `torch.distributed.all_reduce()`. It is intended to be called\n periodically in the main training loop, typically once every\n N training steps.\n \"\"\"\n if not self._keep_previous:\n self._moments.clear()\n for name, cumulative in _sync(self.names()):\n if name not in self._cumulative:\n self._cumulative[name] = torch.zeros(\n [_num_moments], dtype=_counter_dtype\n )\n delta = cumulative - self._cumulative[name]\n self._cumulative[name].copy_(cumulative)\n if float(delta[0]) != 0:\n self._moments[name] = delta\n\n def _get_delta(self, name):\n r\"\"\"Returns the raw moments that were accumulated for the given\n statistic between the last two calls to `update()`, or zero if\n no scalars were collected.\n \"\"\"\n assert self._regex.fullmatch(name)\n if name not in self._moments:\n self._moments[name] = torch.zeros([_num_moments], dtype=_counter_dtype)\n return self._moments[name]\n\n def num(self, name):\n r\"\"\"Returns the number of scalars that were accumulated for the given\n statistic between the last two calls to `update()`, or zero if\n no scalars were collected.\n \"\"\"\n delta = self._get_delta(name)\n return int(delta[0])\n\n def mean(self, name):\n r\"\"\"Returns the mean of the scalars that were accumulated for the\n given statistic between the last two calls to `update()`, or NaN if\n no scalars were collected.\n \"\"\"\n delta = self._get_delta(name)\n if int(delta[0]) == 0:\n return float(\"nan\")\n return float(delta[1] / delta[0])\n\n def std(self, name):\n r\"\"\"Returns the standard deviation of the scalars that were\n accumulated for the given statistic between the last two calls to\n `update()`, or NaN if no scalars were collected.\n \"\"\"\n delta = self._get_delta(name)\n if int(delta[0]) == 0 or not np.isfinite(float(delta[1])):\n return float(\"nan\")\n if int(delta[0]) == 1:\n return float(0)\n mean = float(delta[1] / delta[0])\n raw_var = float(delta[2] / delta[0])\n return np.sqrt(max(raw_var - np.square(mean), 0))\n\n def as_dict(self):\n r\"\"\"Returns the averages accumulated between the last two calls to\n `update()` as an `dnnlib.EasyDict`. The contents are as follows:\n\n dnnlib.EasyDict(\n NAME = dnnlib.EasyDict(num=FLOAT, mean=FLOAT, std=FLOAT),\n ...\n )\n \"\"\"\n stats = dnnlib.EasyDict()\n for name in self.names():\n stats[name] = dnnlib.EasyDict(\n num=self.num(name), mean=self.mean(name), std=self.std(name)\n )\n return stats\n\n def __getitem__(self, name):\n r\"\"\"Convenience getter.\n `collector[name]` is a synonym for `collector.mean(name)`.\n \"\"\"\n return self.mean(name)\n\n\n# ----------------------------------------------------------------------------\n\n\ndef _sync(names):\n r\"\"\"Synchronize the global cumulative counters across devices and\n processes. Called internally by `Collector.update()`.\n \"\"\"\n if len(names) == 0:\n return []\n global _sync_called\n _sync_called = True\n\n # Collect deltas within current rank.\n deltas = []\n device = _sync_device if _sync_device is not None else torch.device(\"cpu\")\n for name in names:\n delta = torch.zeros([_num_moments], dtype=_counter_dtype, device=device)\n for counter in _counters[name].values():\n delta.add_(counter.to(device))\n counter.copy_(torch.zeros_like(counter))\n deltas.append(delta)\n deltas = torch.stack(deltas)\n\n # Sum deltas across ranks.\n if _sync_device is not None:\n torch.distributed.all_reduce(deltas)\n\n # Update cumulative values.\n deltas = deltas.cpu()\n for idx, name in enumerate(names):\n if name not in _cumulative:\n _cumulative[name] = torch.zeros([_num_moments], dtype=_counter_dtype)\n _cumulative[name].add_(deltas[idx])\n\n # Return name-value pairs.\n return [(name, _cumulative[name]) for name in names]\n\n\n# ----------------------------------------------------------------------------\n"
] |
[
[
"numpy.square",
"torch.zeros",
"torch.zeros_like",
"torch.stack",
"torch.device",
"torch.distributed.all_reduce",
"torch.ones_like",
"torch.as_tensor"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bartholmberg/OpenVINO-YoloV3
|
[
"7ea554d34880dfe86b2318938dd6b4a0aaf00979"
] |
[
"pbmodels/tensorboard_log_output_yolov3.py"
] |
[
"import tensorflow as tf\nfrom tensorflow.python.platform import gfile\n\nwith tf.Session() as sess:\n model_filename =\"frozen_yolo_v3.pb\"\n with gfile.FastGFile(model_filename, \"rb\") as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n g_in = tf.import_graph_def(graph_def)\n\n LOGDIR=\"logs/YoloV3\"\n train_writer = tf.summary.FileWriter(LOGDIR)\n train_writer.add_graph(sess.graph)\n\n"
] |
[
[
"tensorflow.import_graph_def",
"tensorflow.summary.FileWriter",
"tensorflow.Session",
"tensorflow.python.platform.gfile.FastGFile",
"tensorflow.GraphDef"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jianlingzhong/xonsh
|
[
"42e2d792117ceeb0ab7ec8f92fb1177b21388f84"
] |
[
"xontrib/mplhooks.py"
] |
[
"\"\"\"Matplotlib hooks, for what its worth.\"\"\"\nfrom io import BytesIO\nimport shutil\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom xonsh.tools import print_color, ON_WINDOWS\n\ntry:\n # Use iterm2_tools as an indicator for the iterm2 terminal emulator\n from iterm2_tools.images import display_image_bytes\nexcept ImportError:\n _use_iterm = False\nelse:\n _use_iterm = True\n\nXONTRIB_MPL_MINIMAL_DEFAULT = True\n\n\ndef _get_buffer(fig, **kwargs):\n b = BytesIO()\n fig.savefig(b, **kwargs)\n b.seek(0)\n return b\n\n\ndef figure_to_rgb_array(fig, shape=None):\n \"\"\"Converts figure to a numpy array\n\n Parameters\n ----------\n fig : matplotlib.figure.Figure\n the figure to be plotted\n shape : iterable\n with the shape of the output array. by default this attempts to use the\n pixel height and width of the figure\n\n\n Returns\n -------\n array : np.ndarray\n An RGBA array of the image represented by the figure.\n\n Note: the method will throw an exception if the given shape is wrong.\n \"\"\"\n array = np.frombuffer(_get_buffer(fig, dpi=fig.dpi, format='raw').read(), dtype='uint8')\n if shape is None:\n w, h = fig.canvas.get_width_height()\n shape = (h, w, 4)\n return array.reshape(*shape)\n\n\ndef figure_to_tight_array(fig, width, height, minimal=True):\n \"\"\"Converts figure to a numpy array of rgb values of tight value\n\n Parameters\n ----------\n fig : matplotlib.figure.Figure\n the figure to be plotted\n width : int\n pixel width of the final array\n height : int\n pixel height of the final array\n minimal : bool\n whether or not to reduce the output array to minimized margins/whitespace\n text is also eliminated\n\n Returns\n -------\n array : np.ndarray\n An RGBA array of the image represented by the figure.\n \"\"\"\n # store the properties of the figure in order to restore it\n w, h = fig.canvas.get_width_height()\n dpi_fig = fig.dpi\n if minimal:\n # perform reversible operations to produce an optimally tight layout\n dpi = dpi_fig\n subplotpars = {\n k: getattr(fig.subplotpars, k)\n for k in ['wspace', 'hspace', 'bottom', 'top', 'left', 'right']\n }\n\n # set the figure dimensions to the terminal size\n fig.set_size_inches(width/dpi, height/dpi, forward=True)\n width, height = fig.canvas.get_width_height()\n\n # remove all space between subplots\n fig.subplots_adjust(wspace=0, hspace=0)\n # move all subplots to take the entirety of space in the figure\n # leave only one line for top and bottom\n fig.subplots_adjust(bottom=1/height, top=1-1/height, left=0, right=1)\n\n # redeuce font size in order to reduce text impact on the image\n font_size = matplotlib.rcParams['font.size']\n matplotlib.rcParams.update({'font.size': 0})\n else:\n dpi = min([width * fig.dpi // w, height * fig.dpi // h])\n fig.dpi = dpi\n width, height = fig.canvas.get_width_height()\n\n # Draw the renderer and get the RGB buffer from the figure\n array = figure_to_rgb_array(fig, shape=(height, width, 4))\n\n if minimal:\n # cleanup after tight layout\n # clean up rcParams\n matplotlib.rcParams.update({'font.size': font_size})\n\n # reset the axis positions and figure dimensions\n fig.set_size_inches(w/dpi, h/dpi, forward=True)\n fig.subplots_adjust(**subplotpars)\n else:\n fig.dpi = dpi_fig\n\n return array\n\n\ndef buf_to_color_str(buf):\n \"\"\"Converts an RGB array to a xonsh color string.\"\"\"\n space = ' '\n pix = '{{bg#{0:02x}{1:02x}{2:02x}}} '\n pixels = []\n for h in range(buf.shape[0]):\n last = None\n for w in range(buf.shape[1]):\n rgb = buf[h, w]\n if last is not None and (last == rgb).all():\n pixels.append(space)\n else:\n pixels.append(pix.format(*rgb))\n last = rgb\n pixels.append('{NO_COLOR}\\n')\n pixels[-1] = pixels[-1].rstrip()\n return ''.join(pixels)\n\n\ndef display_figure_with_iterm2(fig):\n \"\"\"Displays a matplotlib figure using iterm2 inline-image escape sequence.\n\n Parameters\n ----------\n fig : matplotlib.figure.Figure\n the figure to be plotted\n \"\"\"\n print(display_image_bytes(_get_buffer(fig, format='png', dpi=fig.dpi).read()))\n\n\ndef show():\n '''Run the mpl display sequence by printing the most recent figure to console'''\n try:\n minimal = __xonsh_env__['XONTRIB_MPL_MINIMAL']\n except KeyError:\n minimal = XONTRIB_MPL_MINIMAL_DEFAULT\n fig = plt.gcf()\n if _use_iterm:\n display_figure_with_iterm2(fig)\n else:\n # Display the image using terminal characters to fit into the console\n w, h = shutil.get_terminal_size()\n if ON_WINDOWS:\n w -= 1 # @melund reports that win terminals are too thin\n h -= 1 # leave space for next prompt\n buf = figure_to_tight_array(fig, w, h, minimal)\n s = buf_to_color_str(buf)\n print_color(s)\n"
] |
[
[
"matplotlib.rcParams.update",
"matplotlib.pyplot.gcf"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
laurens-in/magenta
|
[
"cf80d19fc0c2e935821f284ebb64a8885f793717",
"cf80d19fc0c2e935821f284ebb64a8885f793717",
"cf80d19fc0c2e935821f284ebb64a8885f793717"
] |
[
"magenta/interfaces/midi/midi_hub_test.py",
"magenta/music/chord_symbols_lib_test.py",
"magenta/models/arbitrary_image_stylization/nza_model.py"
] |
[
"# Copyright 2019 The Magenta Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for midi_hub.\"\"\"\n\nimport collections\nimport threading\nimport time\n\nfrom magenta.common import concurrency\nfrom magenta.interfaces.midi import midi_hub\nfrom magenta.music import testing_lib\nfrom magenta.music.protobuf import music_pb2\nimport mido\nfrom six.moves import queue as Queue\nimport tensorflow.compat.v1 as tf\n\nNote = collections.namedtuple('Note', ['pitch', 'velocity', 'start', 'end'])\n\n\nclass MockMidiPort(mido.ports.BaseIOPort):\n\n def __init__(self):\n super(MockMidiPort, self).__init__()\n self.message_queue = Queue.Queue()\n\n def send(self, msg):\n msg.time = time.time()\n self.message_queue.put(msg)\n\n\nclass MidiHubTest(tf.test.TestCase):\n\n def setUp(self):\n self.maxDiff = None # pylint:disable=invalid-name\n self.capture_messages = [\n mido.Message(type='note_on', note=0, time=0.01),\n mido.Message(type='control_change', control=1, value=1, time=0.02),\n mido.Message(type='note_on', note=1, time=2.0),\n mido.Message(type='note_off', note=0, time=3.0),\n mido.Message(type='note_on', note=2, time=3.0),\n mido.Message(type='note_on', note=3, time=4.0),\n mido.Message(type='note_off', note=2, time=4.0),\n mido.Message(type='note_off', note=1, time=5.0),\n mido.Message(type='control_change', control=1, value=1, time=6.0),\n mido.Message(type='note_off', note=3, time=100)]\n\n self.port = MockMidiPort()\n self.midi_hub = midi_hub.MidiHub([self.port], [self.port],\n midi_hub.TextureType.POLYPHONIC)\n\n # Burn in Sleeper for calibration.\n for _ in range(5):\n concurrency.Sleeper().sleep(0.05)\n\n def tearDown(self):\n self.midi_hub.__del__()\n\n def send_capture_messages(self):\n for msg in self.capture_messages:\n self.port.callback(msg)\n\n def testMidiSignal_ValidityChecks(self):\n # Unsupported type.\n with self.assertRaises(midi_hub.MidiHubError):\n midi_hub.MidiSignal(type='sysex')\n with self.assertRaises(midi_hub.MidiHubError):\n midi_hub.MidiSignal(msg=mido.Message(type='sysex'))\n\n # Invalid arguments.\n with self.assertRaises(midi_hub.MidiHubError):\n midi_hub.MidiSignal()\n with self.assertRaises(midi_hub.MidiHubError):\n midi_hub.MidiSignal(type='note_on', value=1)\n with self.assertRaises(midi_hub.MidiHubError):\n midi_hub.MidiSignal(type='control', note=1)\n with self.assertRaises(midi_hub.MidiHubError):\n midi_hub.MidiSignal(msg=mido.Message(type='control_change'), value=1)\n\n # Non-inferrale type.\n with self.assertRaises(midi_hub.MidiHubError):\n midi_hub.MidiSignal(note=1, value=1)\n\n def testMidiSignal_Message(self):\n sig = midi_hub.MidiSignal(msg=mido.Message(type='note_on', note=1))\n self.assertEqual(\n r'^note_on channel=0 note=1 velocity=64 time=\\d+.\\d+$', str(sig))\n\n sig = midi_hub.MidiSignal(msg=mido.Message(type='note_off', velocity=127))\n self.assertEqual(r'^note_off channel=0 note=0 velocity=127 time=\\d+.\\d+$',\n str(sig))\n\n sig = midi_hub.MidiSignal(\n msg=mido.Message(type='control_change', control=1, value=2))\n self.assertEqual(\n r'^control_change channel=0 control=1 value=2 time=\\d+.\\d+$', str(sig))\n\n def testMidiSignal_Args(self):\n sig = midi_hub.MidiSignal(type='note_on', note=1)\n self.assertEqual(\n r'^note_on channel=\\d+ note=1 velocity=\\d+ time=\\d+.\\d+$', str(sig))\n\n sig = midi_hub.MidiSignal(type='note_off', velocity=127)\n self.assertEqual(\n r'^note_off channel=\\d+ note=\\d+ velocity=127 time=\\d+.\\d+$', str(sig))\n\n sig = midi_hub.MidiSignal(type='control_change', value=2)\n self.assertEqual(\n r'^control_change channel=\\d+ control=\\d+ value=2 time=\\d+.\\d+$',\n str(sig))\n\n def testMidiSignal_Args_InferredType(self):\n sig = midi_hub.MidiSignal(note=1)\n self.assertEqual(\n r'^.* channel=\\d+ note=1 velocity=\\d+ time=\\d+.\\d+$', str(sig))\n\n sig = midi_hub.MidiSignal(value=2)\n self.assertEqual(\n r'^control_change channel=\\d+ control=\\d+ value=2 time=\\d+.\\d+$',\n str(sig))\n\n def testMetronome(self):\n start_time = time.time() + 0.1\n qpm = 180\n self.midi_hub.start_metronome(start_time=start_time, qpm=qpm)\n time.sleep(0.8)\n\n self.midi_hub.stop_metronome()\n self.assertEqual(7, self.port.message_queue.qsize())\n\n msg = self.port.message_queue.get()\n self.assertEqual(msg.type, 'program_change')\n next_tick_time = start_time\n while not self.port.message_queue.empty():\n msg = self.port.message_queue.get()\n if self.port.message_queue.qsize() % 2:\n self.assertEqual(msg.type, 'note_on')\n self.assertAlmostEqual(msg.time, next_tick_time, delta=0.01)\n next_tick_time += 60. / qpm\n else:\n self.assertEqual(msg.type, 'note_off')\n\n def testStartPlayback_NoUpdates(self):\n # Use a time in the past to test handling of past notes.\n start_time = time.time() - 0.05\n seq = music_pb2.NoteSequence()\n notes = [Note(12, 100, 0.0, 1.0), Note(11, 55, 0.1, 0.5),\n Note(40, 45, 0.2, 0.6)]\n notes = [Note(note.pitch, note.velocity, note.start + start_time,\n note.end + start_time) for note in notes]\n testing_lib.add_track_to_sequence(seq, 0, notes)\n player = self.midi_hub.start_playback(seq, allow_updates=False)\n player.join()\n\n note_events = []\n for note in notes:\n note_events.append((note.start, 'note_on', note.pitch))\n note_events.append((note.end, 'note_off', note.pitch))\n\n # The first note on will not be sent since it started before\n # `start_playback` is called.\n del note_events[0]\n\n note_events = collections.deque(sorted(note_events))\n while not self.port.message_queue.empty():\n msg = self.port.message_queue.get()\n note_event = note_events.popleft()\n self.assertEqual(msg.type, note_event[1])\n self.assertEqual(msg.note, note_event[2])\n self.assertAlmostEqual(msg.time, note_event[0], delta=0.01)\n\n self.assertTrue(not note_events)\n\n def testStartPlayback_NoUpdates_UpdateError(self):\n # Use a time in the past to test handling of past notes.\n start_time = time.time()\n seq = music_pb2.NoteSequence()\n notes = [Note(0, 100, start_time + 100, start_time + 101)]\n testing_lib.add_track_to_sequence(seq, 0, notes)\n player = self.midi_hub.start_playback(seq, allow_updates=False)\n\n with self.assertRaises(midi_hub.MidiHubError):\n player.update_sequence(seq)\n\n player.stop()\n\n def testStartPlayback_Updates(self):\n start_time = time.time() + 0.1\n seq = music_pb2.NoteSequence()\n notes = [Note(0, 100, start_time, start_time + 101),\n Note(1, 100, start_time, start_time + 101)]\n testing_lib.add_track_to_sequence(seq, 0, notes)\n player = self.midi_hub.start_playback(seq, allow_updates=True)\n\n # Sleep past first note start.\n concurrency.Sleeper().sleep_until(start_time + 0.2)\n\n new_seq = music_pb2.NoteSequence()\n notes = [Note(1, 100, 0.0, 0.8), Note(2, 100, 0.0, 1.0),\n Note(11, 55, 0.3, 0.5), Note(40, 45, 0.4, 0.6)]\n notes = [Note(note.pitch, note.velocity, note.start + start_time,\n note.end + start_time) for note in notes]\n testing_lib.add_track_to_sequence(new_seq, 0, notes)\n player.update_sequence(new_seq)\n\n # Finish playing sequence.\n concurrency.Sleeper().sleep(0.8)\n\n # Start and end the unclosed note from the first sequence.\n note_events = [(start_time, 'note_on', 0),\n (start_time + 0.3, 'note_off', 0)]\n # The second note will not be played since it started before the update\n # and was not in the original sequence.\n del notes[1]\n for note in notes:\n note_events.append((note.start, 'note_on', note.pitch))\n note_events.append((note.end, 'note_off', note.pitch))\n note_events = collections.deque(sorted(note_events))\n while not self.port.message_queue.empty():\n msg = self.port.message_queue.get()\n note_event = note_events.popleft()\n self.assertEqual(msg.type, note_event[1])\n self.assertEqual(msg.note, note_event[2])\n self.assertAlmostEqual(msg.time, note_event[0], delta=0.01)\n\n self.assertTrue(not note_events)\n player.stop()\n\n def testCaptureSequence_StopSignal(self):\n start_time = 1.0\n\n threading.Timer(0.1, self.send_capture_messages).start()\n\n captured_seq = self.midi_hub.capture_sequence(\n 120, start_time,\n stop_signal=midi_hub.MidiSignal(type='control_change', control=1))\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = 6.0\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, 6)])\n self.assertProtoEquals(captured_seq, expected_seq)\n\n def testCaptureSequence_StopTime(self):\n start_time = 1.0\n stop_time = time.time() + 1.0\n\n self.capture_messages[-1].time += time.time()\n threading.Timer(0.1, self.send_capture_messages).start()\n\n captured_seq = self.midi_hub.capture_sequence(\n 120, start_time, stop_time=stop_time)\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = stop_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, stop_time)])\n self.assertProtoEquals(captured_seq, expected_seq)\n\n def testCaptureSequence_Mono(self):\n start_time = 1.0\n\n threading.Timer(0.1, self.send_capture_messages).start()\n self.midi_hub = midi_hub.MidiHub([self.port], [self.port],\n midi_hub.TextureType.MONOPHONIC)\n captured_seq = self.midi_hub.capture_sequence(\n 120, start_time,\n stop_signal=midi_hub.MidiSignal(type='control_change', control=1))\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = 6\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 3), Note(2, 64, 3, 4), Note(3, 64, 4, 6)])\n self.assertProtoEquals(captured_seq, expected_seq)\n\n def testStartCapture_StopMethod(self):\n start_time = 1.0\n captor = self.midi_hub.start_capture(120, start_time)\n\n self.send_capture_messages()\n time.sleep(0.1)\n\n stop_time = 5.5\n captor.stop(stop_time=stop_time)\n\n captured_seq = captor.captured_sequence()\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = stop_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, stop_time)])\n self.assertProtoEquals(captured_seq, expected_seq)\n\n def testStartCapture_Multiple(self):\n captor_1 = self.midi_hub.start_capture(\n 120, 0.0, stop_signal=midi_hub.MidiSignal(note=3))\n captor_2 = self.midi_hub.start_capture(\n 120, 1.0,\n stop_signal=midi_hub.MidiSignal(type='control_change', control=1))\n\n self.send_capture_messages()\n\n captor_1.join()\n captor_2.join()\n\n captured_seq_1 = captor_1.captured_sequence()\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = 4.0\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(0, 64, 0.01, 3), Note(1, 64, 2, 4), Note(2, 64, 3, 4)])\n self.assertProtoEquals(captured_seq_1, expected_seq)\n\n captured_seq_2 = captor_2.captured_sequence()\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = 6.0\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, 6)])\n self.assertProtoEquals(captured_seq_2, expected_seq)\n\n def testStartCapture_IsDrum(self):\n start_time = 1.0\n captor = self.midi_hub.start_capture(120, start_time)\n\n # Channels are 0-indexed in mido.\n self.capture_messages[2].channel = 9\n self.send_capture_messages()\n time.sleep(0.1)\n\n stop_time = 5.5\n captor.stop(stop_time=stop_time)\n\n captured_seq = captor.captured_sequence()\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = stop_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, stop_time)])\n expected_seq.notes[0].is_drum = True\n self.assertProtoEquals(captured_seq, expected_seq)\n\n def testStartCapture_MidCapture(self):\n start_time = 1.0\n captor = self.midi_hub.start_capture(120, start_time)\n\n # Receive the first 6 messages.\n for msg in self.capture_messages[0:6]:\n self.port.callback(msg)\n time.sleep(0.1)\n\n end_time = 3.5\n captured_seq = captor.captured_sequence(end_time)\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0, [Note(1, 64, 2, 3.5), Note(2, 64, 3, 3.5)])\n self.assertProtoEquals(captured_seq, expected_seq)\n\n end_time = 4.5\n captured_seq = captor.captured_sequence(end_time)\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 4.5), Note(2, 64, 3, 4.5), Note(3, 64, 4, 4.5)])\n self.assertProtoEquals(captured_seq, expected_seq)\n\n end_time = 6.0\n captured_seq = captor.captured_sequence(end_time)\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 6), Note(2, 64, 3, 6), Note(3, 64, 4, 6)])\n self.assertProtoEquals(captured_seq, expected_seq)\n\n # Receive the rest of the messages.\n for msg in self.capture_messages[6:]:\n self.port.callback(msg)\n time.sleep(0.1)\n\n end_time = 6.0\n captured_seq = captor.captured_sequence(end_time)\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, 6)])\n self.assertProtoEquals(captured_seq, expected_seq)\n\n captor.stop()\n\n def testStartCapture_Iterate_Signal(self):\n start_time = 1.0\n captor = self.midi_hub.start_capture(\n 120, start_time,\n stop_signal=midi_hub.MidiSignal(type='control_change', control=1))\n\n for msg in self.capture_messages[:-1]:\n threading.Timer(0.2 * msg.time, self.port.callback, args=[msg]).start()\n\n captured_seqs = []\n for captured_seq in captor.iterate(\n signal=midi_hub.MidiSignal(type='note_off')):\n captured_seqs.append(captured_seq)\n\n self.assertEqual(4, len(captured_seqs))\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = 3\n testing_lib.add_track_to_sequence(expected_seq, 0, [Note(1, 64, 2, 3)])\n self.assertProtoEquals(captured_seqs[0], expected_seq)\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = 4\n testing_lib.add_track_to_sequence(\n expected_seq, 0, [Note(1, 64, 2, 4), Note(2, 64, 3, 4)])\n self.assertProtoEquals(captured_seqs[1], expected_seq)\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = 5\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, 5)])\n self.assertProtoEquals(captured_seqs[2], expected_seq)\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = 6\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, 6)])\n self.assertProtoEquals(captured_seqs[3], expected_seq)\n\n def testStartCapture_Iterate_Period(self):\n start_time = 1.0\n captor = self.midi_hub.start_capture(\n 120, start_time,\n stop_signal=midi_hub.MidiSignal(type='control_change', control=1))\n\n for msg in self.capture_messages[:-1]:\n threading.Timer(0.1 * msg.time, self.port.callback, args=[msg]).start()\n\n period = 0.26\n captured_seqs = []\n wall_start_time = time.time()\n for captured_seq in captor.iterate(period=period):\n if len(captured_seqs) < 2:\n self.assertAlmostEqual(0, (time.time() - wall_start_time) % period,\n delta=0.01)\n time.sleep(0.1)\n captured_seqs.append(captured_seq)\n\n self.assertEqual(3, len(captured_seqs))\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n end_time = captured_seqs[0].total_time\n self.assertAlmostEqual(wall_start_time + period, end_time, delta=0.005)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0, [Note(1, 64, 2, end_time)])\n self.assertProtoEquals(captured_seqs[0], expected_seq)\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n end_time = captured_seqs[1].total_time\n self.assertAlmostEqual(wall_start_time + 2 * period, end_time, delta=0.005)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, end_time)])\n self.assertProtoEquals(captured_seqs[1], expected_seq)\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = 6\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, 6)])\n self.assertProtoEquals(captured_seqs[2], expected_seq)\n\n def testStartCapture_Iterate_Period_Overrun(self):\n start_time = 1.0\n captor = self.midi_hub.start_capture(\n 120, start_time,\n stop_signal=midi_hub.MidiSignal(type='control_change', control=1))\n\n for msg in self.capture_messages[:-1]:\n threading.Timer(0.1 * msg.time, self.port.callback, args=[msg]).start()\n\n period = 0.26\n captured_seqs = []\n wall_start_time = time.time()\n for captured_seq in captor.iterate(period=period):\n time.sleep(0.5)\n captured_seqs.append(captured_seq)\n\n self.assertEqual(2, len(captured_seqs))\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n end_time = captured_seqs[0].total_time\n self.assertAlmostEqual(wall_start_time + period, end_time, delta=0.005)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0, [Note(1, 64, 2, end_time)])\n self.assertProtoEquals(captured_seqs[0], expected_seq)\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n expected_seq.total_time = 6\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, 6)])\n self.assertProtoEquals(captured_seqs[1], expected_seq)\n\n def testStartCapture_Callback_Period(self):\n start_time = 1.0\n captor = self.midi_hub.start_capture(120, start_time)\n\n for msg in self.capture_messages[:-1]:\n threading.Timer(0.1 * msg.time, self.port.callback, args=[msg]).start()\n\n period = 0.26\n wall_start_time = time.time()\n captured_seqs = []\n\n def fn(captured_seq):\n self.assertAlmostEqual(0, (time.time() - wall_start_time) % period,\n delta=0.01)\n captured_seqs.append(captured_seq)\n\n name = captor.register_callback(fn, period=period)\n time.sleep(1.0)\n captor.cancel_callback(name)\n\n self.assertEqual(3, len(captured_seqs))\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n end_time = captured_seqs[0].total_time\n self.assertAlmostEqual(wall_start_time + period, end_time, delta=0.005)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0, [Note(1, 64, 2, end_time)])\n self.assertProtoEquals(captured_seqs[0], expected_seq)\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n end_time = captured_seqs[1].total_time\n self.assertAlmostEqual(wall_start_time + 2 * period, end_time, delta=0.005)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, end_time)])\n self.assertProtoEquals(captured_seqs[1], expected_seq)\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n end_time = captured_seqs[2].total_time\n self.assertAlmostEqual(wall_start_time + 3 * period, end_time, delta=0.005)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, end_time)])\n self.assertProtoEquals(captured_seqs[2], expected_seq)\n\n def testStartCapture_Callback_Period_Overrun(self):\n start_time = 1.0\n captor = self.midi_hub.start_capture(\n 120, start_time)\n\n for msg in self.capture_messages[:-1]:\n threading.Timer(0.1 * msg.time, self.port.callback, args=[msg]).start()\n\n period = 0.26\n wall_start_time = time.time()\n captured_seqs = []\n\n def fn(captured_seq):\n time.sleep(0.5)\n captured_seqs.append(captured_seq)\n\n name = captor.register_callback(fn, period=period)\n time.sleep(1.3)\n captor.cancel_callback(name)\n\n self.assertEqual(2, len(captured_seqs))\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n end_time = captured_seqs[0].total_time\n self.assertAlmostEqual(wall_start_time + period, end_time, delta=0.005)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0, [Note(1, 64, 2, end_time)])\n self.assertProtoEquals(captured_seqs[0], expected_seq)\n\n expected_seq = music_pb2.NoteSequence()\n expected_seq.tempos.add(qpm=120)\n end_time = captured_seqs[1].total_time\n self.assertAlmostEqual(wall_start_time + 2 * period, end_time, delta=0.005)\n expected_seq.total_time = end_time\n testing_lib.add_track_to_sequence(\n expected_seq, 0,\n [Note(1, 64, 2, 5), Note(2, 64, 3, 4), Note(3, 64, 4, end_time)])\n self.assertProtoEquals(captured_seqs[1], expected_seq)\n\n def testPassThrough_Poly(self):\n self.midi_hub.passthrough = False\n self.send_capture_messages()\n self.assertTrue(self.port.message_queue.empty())\n self.midi_hub.passthrough = True\n self.send_capture_messages()\n\n passed_messages = []\n while not self.port.message_queue.empty():\n passed_messages.append(self.port.message_queue.get().bytes())\n self.assertListEqual(\n passed_messages, [m.bytes() for m in self.capture_messages])\n\n def testPassThrough_Mono(self):\n self.midi_hub = midi_hub.MidiHub([self.port], [self.port],\n midi_hub.TextureType.MONOPHONIC)\n self.midi_hub.passthrough = False\n self.send_capture_messages()\n self.assertTrue(self.port.message_queue.empty())\n self.midi_hub.passthrough = True\n self.send_capture_messages()\n\n passed_messages = []\n while not self.port.message_queue.empty():\n passed_messages.append(self.port.message_queue.get())\n passed_messages[-1].time = 0\n expected_messages = [\n mido.Message(type='note_on', note=0),\n mido.Message(type='control_change', control=1, value=1),\n mido.Message(type='note_off', note=0),\n mido.Message(type='note_on', note=1),\n mido.Message(type='note_off', note=1),\n mido.Message(type='note_on', note=2),\n mido.Message(type='note_off', note=2),\n mido.Message(type='note_on', note=3),\n mido.Message(type='control_change', control=1, value=1),\n mido.Message(type='note_off', note=3)]\n\n self.assertListEqual(passed_messages, expected_messages)\n\n def testWaitForEvent_Signal(self):\n for msg in self.capture_messages[3:-1]:\n threading.Timer(0.2 * msg.time, self.port.callback, args=[msg]).start()\n\n wait_start = time.time()\n\n self.midi_hub.wait_for_event(\n signal=midi_hub.MidiSignal(type='control_change', value=1))\n self.assertAlmostEqual(time.time() - wait_start, 1.2, delta=0.01)\n\n def testWaitForEvent_Time(self):\n for msg in self.capture_messages[3:-1]:\n threading.Timer(0.1 * msg.time, self.port.callback, args=[msg]).start()\n\n wait_start = time.time()\n\n self.midi_hub.wait_for_event(timeout=0.3)\n self.assertAlmostEqual(time.time() - wait_start, 0.3, delta=0.01)\n\n def testSendControlChange(self):\n self.midi_hub.send_control_change(0, 1)\n\n sent_messages = []\n while not self.port.message_queue.empty():\n sent_messages.append(self.port.message_queue.get())\n\n self.assertListEqual(\n sent_messages,\n [mido.Message(type='control_change', control=0, value=1,\n time=sent_messages[0].time)])\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2019 The Magenta Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for chord_symbols_lib.\"\"\"\n\nfrom magenta.music import chord_symbols_lib\nimport tensorflow.compat.v1 as tf\n\nCHORD_QUALITY_MAJOR = chord_symbols_lib.CHORD_QUALITY_MAJOR\nCHORD_QUALITY_MINOR = chord_symbols_lib.CHORD_QUALITY_MINOR\nCHORD_QUALITY_AUGMENTED = chord_symbols_lib.CHORD_QUALITY_AUGMENTED\nCHORD_QUALITY_DIMINISHED = chord_symbols_lib.CHORD_QUALITY_DIMINISHED\nCHORD_QUALITY_OTHER = chord_symbols_lib.CHORD_QUALITY_OTHER\n\n\nclass ChordSymbolFunctionsTest(tf.test.TestCase):\n\n def testTransposeChordSymbol(self):\n # Test basic triads.\n figure = chord_symbols_lib.transpose_chord_symbol('C', 2)\n self.assertEqual('D', figure)\n figure = chord_symbols_lib.transpose_chord_symbol('Abm', -3)\n self.assertEqual('Fm', figure)\n figure = chord_symbols_lib.transpose_chord_symbol('F#', 0)\n self.assertEqual('F#', figure)\n figure = chord_symbols_lib.transpose_chord_symbol('Cbb', 6)\n self.assertEqual('Fb', figure)\n figure = chord_symbols_lib.transpose_chord_symbol('C#', -5)\n self.assertEqual('G#', figure)\n\n # Test more complex chords.\n figure = chord_symbols_lib.transpose_chord_symbol('Co7', 7)\n self.assertEqual('Go7', figure)\n figure = chord_symbols_lib.transpose_chord_symbol('D+', -3)\n self.assertEqual('B+', figure)\n figure = chord_symbols_lib.transpose_chord_symbol('Fb9/Ab', 2)\n self.assertEqual('Gb9/Bb', figure)\n figure = chord_symbols_lib.transpose_chord_symbol('A6/9', -7)\n self.assertEqual('D6/9', figure)\n figure = chord_symbols_lib.transpose_chord_symbol('E7(add#9)', 0)\n self.assertEqual('E7(add#9)', figure)\n\n def testPitchesToChordSymbol(self):\n # Test basic triads.\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [60, 64, 67])\n self.assertEqual('C', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [45, 48, 52])\n self.assertEqual('Am', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [63, 66, 69])\n self.assertEqual('Ebo', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [71, 75, 79])\n self.assertEqual('B+', figure)\n\n # Test basic inversions.\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [59, 62, 67])\n self.assertEqual('G/B', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [65, 70, 73])\n self.assertEqual('Bbm/F', figure)\n\n # Test suspended chords.\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [62, 67, 69])\n self.assertEqual('Dsus', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [55, 60, 62, 65])\n self.assertEqual('Gsus7', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [67, 69, 74])\n self.assertEqual('Gsus2', figure)\n\n # Test more complex chords.\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [45, 46, 50, 53])\n self.assertEqual('Bbmaj7/A', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [63, 67, 70, 72, 74])\n self.assertEqual('Cm9/Eb', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [53, 60, 64, 67, 70])\n self.assertEqual('C7/F', figure)\n\n # Test chords with modifications.\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [67, 71, 72, 74, 77])\n self.assertEqual('G7(add4)', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [64, 68, 71, 74, 79])\n self.assertEqual('E7(#9)', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [60, 62, 64, 67])\n self.assertEqual('C(add2)', figure)\n figure = chord_symbols_lib.pitches_to_chord_symbol(\n [60, 64, 68, 70, 75])\n self.assertEqual('C+7(#9)', figure)\n\n # Test invalid chord.\n with self.assertRaises(chord_symbols_lib.ChordSymbolError):\n chord_symbols_lib.pitches_to_chord_symbol(\n [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71])\n\n def testChordSymbolPitches(self):\n pitches = chord_symbols_lib.chord_symbol_pitches('Am')\n pitch_classes = set(pitch % 12 for pitch in pitches)\n self.assertEqual(set([0, 4, 9]), pitch_classes)\n pitches = chord_symbols_lib.chord_symbol_pitches('D7b9')\n pitch_classes = set(pitch % 12 for pitch in pitches)\n self.assertEqual(set([0, 2, 3, 6, 9]), pitch_classes)\n pitches = chord_symbols_lib.chord_symbol_pitches('F/o')\n pitch_classes = set(pitch % 12 for pitch in pitches)\n self.assertEqual(set([3, 5, 8, 11]), pitch_classes)\n pitches = chord_symbols_lib.chord_symbol_pitches('C-(M7)')\n pitch_classes = set(pitch % 12 for pitch in pitches)\n self.assertEqual(set([0, 3, 7, 11]), pitch_classes)\n pitches = chord_symbols_lib.chord_symbol_pitches('E##13')\n pitch_classes = set(pitch % 12 for pitch in pitches)\n self.assertEqual(set([1, 3, 4, 6, 8, 10, 11]), pitch_classes)\n pitches = chord_symbols_lib.chord_symbol_pitches('G(add2)(#5)')\n pitch_classes = set(pitch % 12 for pitch in pitches)\n self.assertEqual(set([3, 7, 9, 11]), pitch_classes)\n\n def testChordSymbolRoot(self):\n root = chord_symbols_lib.chord_symbol_root('Dm9')\n self.assertEqual(2, root)\n root = chord_symbols_lib.chord_symbol_root('E/G#')\n self.assertEqual(4, root)\n root = chord_symbols_lib.chord_symbol_root('Bsus2')\n self.assertEqual(11, root)\n root = chord_symbols_lib.chord_symbol_root('Abmaj7')\n self.assertEqual(8, root)\n root = chord_symbols_lib.chord_symbol_root('D##5(add6)')\n self.assertEqual(4, root)\n root = chord_symbols_lib.chord_symbol_root('F(b7)(#9)(b13)')\n self.assertEqual(5, root)\n\n def testChordSymbolBass(self):\n bass = chord_symbols_lib.chord_symbol_bass('Dm9')\n self.assertEqual(2, bass)\n bass = chord_symbols_lib.chord_symbol_bass('E/G#')\n self.assertEqual(8, bass)\n bass = chord_symbols_lib.chord_symbol_bass('Bsus2/A')\n self.assertEqual(9, bass)\n bass = chord_symbols_lib.chord_symbol_bass('Abm7/Cb')\n self.assertEqual(11, bass)\n bass = chord_symbols_lib.chord_symbol_bass('C#6/9/E#')\n self.assertEqual(5, bass)\n bass = chord_symbols_lib.chord_symbol_bass('G/o')\n self.assertEqual(7, bass)\n\n def testChordSymbolQuality(self):\n # Test major chords.\n quality = chord_symbols_lib.chord_symbol_quality('B13')\n self.assertEqual(CHORD_QUALITY_MAJOR, quality)\n quality = chord_symbols_lib.chord_symbol_quality('E7#9')\n self.assertEqual(CHORD_QUALITY_MAJOR, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Fadd2/Eb')\n self.assertEqual(CHORD_QUALITY_MAJOR, quality)\n quality = chord_symbols_lib.chord_symbol_quality('C6/9/Bb')\n self.assertEqual(CHORD_QUALITY_MAJOR, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Gmaj13')\n self.assertEqual(CHORD_QUALITY_MAJOR, quality)\n\n # Test minor chords.\n quality = chord_symbols_lib.chord_symbol_quality('C#-9')\n self.assertEqual(CHORD_QUALITY_MINOR, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Gm7/Bb')\n self.assertEqual(CHORD_QUALITY_MINOR, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Cbmmaj7')\n self.assertEqual(CHORD_QUALITY_MINOR, quality)\n quality = chord_symbols_lib.chord_symbol_quality('A-(M7)')\n self.assertEqual(CHORD_QUALITY_MINOR, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Bbmin')\n self.assertEqual(CHORD_QUALITY_MINOR, quality)\n\n # Test augmented chords.\n quality = chord_symbols_lib.chord_symbol_quality('D+/A#')\n self.assertEqual(CHORD_QUALITY_AUGMENTED, quality)\n quality = chord_symbols_lib.chord_symbol_quality('A+')\n self.assertEqual(CHORD_QUALITY_AUGMENTED, quality)\n quality = chord_symbols_lib.chord_symbol_quality('G7(#5)')\n self.assertEqual(CHORD_QUALITY_AUGMENTED, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Faug(add2)')\n self.assertEqual(CHORD_QUALITY_AUGMENTED, quality)\n\n # Test diminished chords.\n quality = chord_symbols_lib.chord_symbol_quality('Am7b5')\n self.assertEqual(CHORD_QUALITY_DIMINISHED, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Edim7')\n self.assertEqual(CHORD_QUALITY_DIMINISHED, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Bb/o')\n self.assertEqual(CHORD_QUALITY_DIMINISHED, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Fo')\n self.assertEqual(CHORD_QUALITY_DIMINISHED, quality)\n\n # Test other chords.\n quality = chord_symbols_lib.chord_symbol_quality('G5')\n self.assertEqual(CHORD_QUALITY_OTHER, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Bbsus2')\n self.assertEqual(CHORD_QUALITY_OTHER, quality)\n quality = chord_symbols_lib.chord_symbol_quality('Dsus')\n self.assertEqual(CHORD_QUALITY_OTHER, quality)\n quality = chord_symbols_lib.chord_symbol_quality('E(no3)')\n self.assertEqual(CHORD_QUALITY_OTHER, quality)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2019 The Magenta Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Style transfer network code.\n\nThis model does not apply styles in the encoding\nlayers. Encoding layers (contract) use batch norm as the normalization function.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom magenta.models.image_stylization import model as model_util\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.contrib import slim as contrib_slim\n\nslim = contrib_slim\n\n\ndef transform(input_,\n normalizer_fn=None,\n normalizer_params=None,\n reuse=False,\n trainable=True,\n is_training=True,\n alpha=1.0):\n \"\"\"Maps content images to stylized images.\n\n Args:\n input_: Tensor. Batch of input images.\n normalizer_fn: normalization layer function for applying style\n normalization.\n normalizer_params: dict of parameters to pass to the style normalization op.\n reuse: bool. Whether to reuse model parameters. Defaults to False.\n trainable: bool. Should the parameters be marked as trainable?\n is_training: bool. Is it training phase or not?\n alpha: float. Width multiplier to reduce the number of filters used in the\n model and slim it down. Defaults to 1.0, which results\n in the hyper-parameters used in the published paper.\n\n\n Returns:\n Tensor. The output of the transformer network.\n \"\"\"\n with tf.variable_scope('transformer', reuse=reuse):\n with slim.arg_scope([slim.conv2d],\n activation_fn=tf.nn.relu,\n normalizer_fn=normalizer_fn,\n normalizer_params=normalizer_params,\n weights_initializer=tf.random_normal_initializer(\n 0.0, 0.01),\n biases_initializer=tf.constant_initializer(0.0),\n trainable=trainable):\n with slim.arg_scope([slim.conv2d],\n normalizer_fn=slim.batch_norm,\n normalizer_params=None,\n trainable=trainable):\n with slim.arg_scope([slim.batch_norm],\n is_training=is_training,\n trainable=trainable):\n with tf.variable_scope('contract'):\n h = model_util.conv2d(input_, 9, 1, int(alpha * 32), 'conv1')\n h = model_util.conv2d(h, 3, 2, int(alpha * 64), 'conv2')\n h = model_util.conv2d(h, 3, 2, int(alpha * 128), 'conv3')\n with tf.variable_scope('residual'):\n h = model_util.residual_block(h, 3, 'residual1')\n h = model_util.residual_block(h, 3, 'residual2')\n h = model_util.residual_block(h, 3, 'residual3')\n h = model_util.residual_block(h, 3, 'residual4')\n h = model_util.residual_block(h, 3, 'residual5')\n with tf.variable_scope('expand'):\n h = model_util.upsampling(h, 3, 2, int(alpha * 64), 'conv1')\n h = model_util.upsampling(h, 3, 2, int(alpha * 32), 'conv2')\n return model_util.upsampling(\n h, 9, 1, 3, 'conv3', activation_fn=tf.nn.sigmoid)\n\n\ndef style_normalization_activations(pre_name='transformer',\n post_name='StyleNorm',\n alpha=1.0):\n \"\"\"Returns scope name and depths of the style normalization activations.\n\n Args:\n pre_name: string. Prepends this name to the scope names.\n post_name: string. Appends this name to the scope names.\n alpha: float. Width multiplier to reduce the number of filters used in the\n model and slim it down.. Defaults to 1.0, which results\n in the hyper-parameters used in the published paper.\n\n Returns:\n string. Scope names of the activations of the transformer network which are\n used to apply style normalization.\n int[]. Depths of the activations of the transformer network which are used\n to apply style normalization.\n \"\"\"\n\n scope_names = [\n 'residual/residual1/conv1', 'residual/residual1/conv2',\n 'residual/residual2/conv1', 'residual/residual2/conv2',\n 'residual/residual3/conv1', 'residual/residual3/conv2',\n 'residual/residual4/conv1', 'residual/residual4/conv2',\n 'residual/residual5/conv1', 'residual/residual5/conv2',\n 'expand/conv1/conv', 'expand/conv2/conv', 'expand/conv3/conv'\n ]\n scope_names = [\n '{}/{}/{}'.format(pre_name, name, post_name) for name in scope_names\n ]\n # 10 convolution layers of 'residual/residual*/conv*' have the same depth.\n depths = [int(alpha * 128)] * 10 + [int(alpha * 64), int(alpha * 32), 3]\n\n return scope_names, depths\n"
] |
[
[
"tensorflow.compat.v1.test.main"
],
[
"tensorflow.compat.v1.test.main"
],
[
"tensorflow.compat.v1.constant_initializer",
"tensorflow.compat.v1.random_normal_initializer",
"tensorflow.compat.v1.variable_scope"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gvvynplaine/sonnet
|
[
"5a465696383f967d5bffb6599347d9e6c15cef4b",
"5a465696383f967d5bffb6599347d9e6c15cef4b",
"5a465696383f967d5bffb6599347d9e6c15cef4b"
] |
[
"sonnet/src/leaky_clip_by_value_test.py",
"sonnet/src/dropout.py",
"sonnet/src/test_utils.py"
] |
[
"# Copyright 2019 The Sonnet Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Tests for sonnet.v2.src.leaky_clip_by_value.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nfrom sonnet.src import leaky_clip_by_value\nfrom sonnet.src import test_utils\nimport tensorflow as tf\n\n\nclass LeakyClipByValueTest(test_utils.TestCase, parameterized.TestCase):\n\n def test_leaky_clip_by_value_forward(self):\n t = tf.Variable([1.0, 2.0, 3.0])\n # Test when min/max are scalar values.\n clip_min = [1.5]\n clip_max = [2.5]\n clip_t = leaky_clip_by_value.leaky_clip_by_value(t, clip_min, clip_max)\n self.assertAllEqual(clip_t.numpy(), [1.5, 2.0, 2.5])\n # Test when min/max are of same sizes as t.\n clip_min_array = [0.5, 2.5, 2.5]\n clip_max_array = [1.5, 3.0, 3.5]\n clip_t_2 = leaky_clip_by_value.leaky_clip_by_value(t, clip_min_array,\n clip_max_array)\n self.assertAllEqual(clip_t_2.numpy(), [1.0, 2.5, 3.0])\n\n @parameterized.parameters([\n (0.5, lambda x: x, [1.0]),\n (1.5, lambda x: x, [1.0]),\n (1.5, lambda x: -x, [0.0]),\n (-.5, lambda x: x, [0.0]),\n (-.5, lambda x: -x, [-1.0]),\n ])\n def test_leaky_clip_by_value_backward(self, init, fn, expected_grad):\n t = tf.Variable([init])\n max_val = 1.0\n min_val = 0.0\n with tf.GradientTape() as tape:\n clip_t = leaky_clip_by_value.leaky_clip_by_value(t, min_val, max_val)\n f = fn(clip_t)\n grad = tape.gradient(f, t)\n clip_t_value = clip_t.numpy()\n self.assertAllEqual(grad.numpy(), expected_grad)\n self.assertGreaterEqual(clip_t_value, min_val)\n self.assertLessEqual(clip_t_value, max_val)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2019 The Sonnet 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\"\"\"Sonnet dropout modules.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n# from __future__ import google_type_annotations\nfrom __future__ import print_function\n\nfrom sonnet.src import base\nfrom sonnet.src import types\nfrom sonnet.src import utils\n\nimport tensorflow as tf\nfrom typing import Optional, Text\n\n\nclass Dropout(base.Module):\n \"\"\"Randomly drop units in the input at a given rate.\n\n See: http://www.cs.toronto.edu/~hinton/absps/dropout.pdf\n\n Dropout was originally described by Hinton et al. TensorFlow deviates slightly\n from this paper by scaling activations at training time rather than test time.\n \"\"\"\n\n def __init__(self,\n rate: types.FloatLike,\n noise_shape: Optional[types.ShapeLike] = None,\n seed: Optional[int] = None,\n name: Optional[Text] = None):\n \"\"\"Constructs a Dropout module.\n\n Args:\n rate: Probability that each element of x is discarded. Must be a scalar in\n the range `[0, 1)`.\n noise_shape: (Optional) Shape vector controlling the shape of the random\n noise used to apply dropout. If not set this will be the shape of the\n input. If set it should be broadcastable to the input shape.\n seed: (Optional) Random seed to be passed to TensorFlow ops when\n generating dropout tensor.\n name: (Optional) Name for this module.\n \"\"\"\n super(Dropout, self).__init__(name=name)\n self._rate = rate\n self._noise_shape = noise_shape\n self._seed = seed\n\n @utils.smart_autograph\n def __call__(self, x: tf.Tensor, is_training: types.BoolLike) -> tf.Tensor:\n if not is_training:\n return x\n\n # NOTE: Even if `self._seed` is a constant value (e.g. `2`) this will\n # produce a different random dropout each call (the per-op seed is used\n # in conjunction with the global seed and some persistent state to produce\n # random values).\n # c.f. https://www.tensorflow.org/api_docs/python/tf/random/set_random_seed\n return tf.nn.dropout(\n x, rate=self._rate, noise_shape=self._noise_shape, seed=self._seed)\n",
"# Copyright 2019 The Sonnet Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Test utilities for Sonnet 2.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n# from __future__ import google_type_annotations\nfrom __future__ import print_function\n\nimport functools\nimport inspect\nimport itertools\nimport os\nimport sys\nimport threading\nimport types\n\nfrom absl.testing import parameterized\nimport tensorflow as tf\nfrom typing import Sequence, Text, Tuple, Type, TypeVar\n\nModule = TypeVar(\"Module\")\n\ntpu_initialized = None\ntpu_initialized_lock = threading.Lock()\n\n\nclass TestCase(tf.test.TestCase):\n \"\"\"Test case which handles TPU hard placement.\"\"\"\n\n ENTER_PRIMARY_DEVICE = True\n\n def setUp(self):\n super(TestCase, self).setUp()\n\n # Enable autograph strict mode - any autograph errors will trigger an error\n # rather than falling back to no conversion.\n os.environ[\"AUTOGRAPH_STRICT_CONVERSION\"] = \"1\"\n\n self._device_types = frozenset(\n d.device_type for d in tf.config.experimental.list_logical_devices())\n self._on_tpu = \"TPU\" in self._device_types\n\n # Initialize the TPU system once and only once.\n global tpu_initialized\n if tpu_initialized is None:\n with tpu_initialized_lock:\n if tpu_initialized is None and self._on_tpu:\n tf.tpu.experimental.initialize_tpu_system()\n tpu_initialized = True\n\n if self.ENTER_PRIMARY_DEVICE:\n self._device = tf.device(\"/device:%s:0\" % self.primary_device)\n self._device.__enter__()\n\n def tearDown(self):\n super(TestCase, self).tearDown()\n if self.ENTER_PRIMARY_DEVICE:\n self._device.__exit__(*sys.exc_info())\n del self._device\n\n @property\n def primary_device(self):\n if \"TPU\" in self._device_types:\n return \"TPU\"\n elif \"GPU\" in self._device_types:\n return \"GPU\"\n else:\n return \"CPU\"\n\n @property\n def device_types(self):\n return self._device_types\n\n def get_atol(self):\n \"\"\"Returns a good tolerance for numerical closeness tests.\n\n Any TPU matmuls go via bfloat16, so an assertAllClose which passes under\n some constant small tolerance on CPU will generally fail on TPU. All test\n cases can call get_atol to get an appropriate number.\n\n TODO(mareynolds): assess these thresholds in detail.\n\n Returns:\n small float, eg 1e-4 on CPU/GPU, 5se-3 on TPU.\n \"\"\"\n if self._on_tpu:\n return 5e-3\n else:\n return 1e-4\n\n\ndef find_all_sonnet_modules(\n root_python_module: types.ModuleType,\n base_class: Type[Module],\n) -> Sequence[Type[Module]]:\n \"\"\"Finds all subclasses of `base_class` under `root_python_module`.\"\"\"\n modules = []\n for _, python_module in find_sonnet_python_modules(root_python_module):\n for name in dir(python_module):\n value = getattr(python_module, name)\n if inspect.isclass(value) and issubclass(value, base_class):\n modules.append(value)\n return modules\n\n\ndef find_sonnet_python_modules(\n root_module: types.ModuleType,) -> Sequence[Tuple[Text, types.ModuleType]]:\n \"\"\"Returns `(name, module)` for all Sonnet submodules under `root_module`.\"\"\"\n modules = set([(root_module.__name__, root_module)])\n visited = set()\n to_visit = [root_module]\n\n while to_visit:\n mod = to_visit.pop()\n visited.add(mod)\n\n for name in dir(mod):\n obj = getattr(mod, name)\n if inspect.ismodule(obj) and obj not in visited:\n if obj.__name__.startswith(\"sonnet\"):\n to_visit.append(obj)\n modules.add((obj.__name__, obj))\n\n return sorted(modules)\n\n\ndef combined_named_parameters(*parameters):\n \"\"\"Combines multiple ``@parameterized.named_parameters`` compatible sequences.\n\n >>> foos = (\"a_for_foo\", \"a\"), (\"b_for_foo\", \"b\")\n >>> bars = (\"c_for_bar\", \"c\"), (\"d_for_bar\", \"d\")\n\n >>> @named_parameters(foos)\n ... def testFoo(self, foo):\n ... assert foo in (\"a\", \"b\")\n\n >>> @combined_named_parameters(foos, bars):\n ... def testFooBar(self, foo, bar):\n ... assert foo in (\"a\", \"b\")\n ... assert bar in (\"c\", \"d\")\n\n Args:\n *parameters: A sequence of parameters that will be combined and be passed\n into ``parameterized.named_parameters``.\n\n Returns:\n A test generator to be handled by ``parameterized.TestGeneratorMetaclass``.\n \"\"\"\n combine = lambda a, b: (\"_\".join((a[0], b[0])),) + a[1:] + b[1:]\n return parameterized.named_parameters(\n functools.reduce(combine, r) for r in itertools.product(*parameters))\n\n\ndef named_bools(name) -> Sequence[Tuple[Text, bool]]:\n \"\"\"Returns a pair of booleans suitable for use with ``named_parameters``.\"\"\"\n return (name, True), (\"not_{}\".format(name), False)\n"
] |
[
[
"tensorflow.test.main",
"tensorflow.Variable",
"tensorflow.GradientTape"
],
[
"tensorflow.nn.dropout"
],
[
"tensorflow.tpu.experimental.initialize_tpu_system",
"tensorflow.device",
"tensorflow.config.experimental.list_logical_devices"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"2.7",
"2.6",
"2.3",
"2.4",
"2.9",
"2.5",
"2.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ln0119/tensorflow-fast-rcnn
|
[
"da88903d5e29230d68d861053aa1dea1432c0696",
"da88903d5e29230d68d861053aa1dea1432c0696",
"da88903d5e29230d68d861053aa1dea1432c0696",
"da88903d5e29230d68d861053aa1dea1432c0696",
"da88903d5e29230d68d861053aa1dea1432c0696",
"da88903d5e29230d68d861053aa1dea1432c0696",
"da88903d5e29230d68d861053aa1dea1432c0696",
"da88903d5e29230d68d861053aa1dea1432c0696"
] |
[
"tensorflow/models/embedding/word2vec.py",
"tensorflow/python/kernel_tests/check_ops_test.py",
"tensorflow/python/training/summary_writer_test.py",
"tensorflow/python/kernel_tests/denormal_test.py",
"tensorflow/python/kernel_tests/tensor_array_ops_test.py",
"tensorflow/examples/skflow/resnet.py",
"tensorflow/contrib/metrics/python/metrics/classification.py",
"tensorflow/examples/skflow/text_classification.py"
] |
[
"# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Multi-threaded word2vec mini-batched skip-gram model.\n\nTrains the model described in:\n(Mikolov, et. al.) Efficient Estimation of Word Representations in Vector Space\nICLR 2013.\nhttp://arxiv.org/abs/1301.3781\nThis model does traditional minibatching.\n\nThe key ops used are:\n* placeholder for feeding in tensors for each example.\n* embedding_lookup for fetching rows from the embedding matrix.\n* sigmoid_cross_entropy_with_logits to calculate the loss.\n* GradientDescentOptimizer for optimizing the loss.\n* skipgram custom op that does input processing.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport threading\nimport time\n\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.models.embedding import gen_word2vec as word2vec\n\nflags = tf.app.flags\n\nflags.DEFINE_string(\"save_path\", None, \"Directory to write the model and \"\n \"training summaries.\")\nflags.DEFINE_string(\"train_data\", None, \"Training text file. \"\n \"E.g., unzipped file http://mattmahoney.net/dc/text8.zip.\")\nflags.DEFINE_string(\n \"eval_data\", None, \"File consisting of analogies of four tokens.\"\n \"embedding 2 - embedding 1 + embedding 3 should be close \"\n \"to embedding 4.\"\n \"E.g. https://word2vec.googlecode.com/svn/trunk/questions-words.txt.\")\nflags.DEFINE_integer(\"embedding_size\", 200, \"The embedding dimension size.\")\nflags.DEFINE_integer(\n \"epochs_to_train\", 15,\n \"Number of epochs to train. Each epoch processes the training data once \"\n \"completely.\")\nflags.DEFINE_float(\"learning_rate\", 0.2, \"Initial learning rate.\")\nflags.DEFINE_integer(\"num_neg_samples\", 100,\n \"Negative samples per training example.\")\nflags.DEFINE_integer(\"batch_size\", 16,\n \"Number of training examples processed per step \"\n \"(size of a minibatch).\")\nflags.DEFINE_integer(\"concurrent_steps\", 12,\n \"The number of concurrent training steps.\")\nflags.DEFINE_integer(\"window_size\", 5,\n \"The number of words to predict to the left and right \"\n \"of the target word.\")\nflags.DEFINE_integer(\"min_count\", 5,\n \"The minimum number of word occurrences for it to be \"\n \"included in the vocabulary.\")\nflags.DEFINE_float(\"subsample\", 1e-3,\n \"Subsample threshold for word occurrence. Words that appear \"\n \"with higher frequency will be randomly down-sampled. Set \"\n \"to 0 to disable.\")\nflags.DEFINE_boolean(\n \"interactive\", False,\n \"If true, enters an IPython interactive session to play with the trained \"\n \"model. E.g., try model.analogy(b'france', b'paris', b'russia') and \"\n \"model.nearby([b'proton', b'elephant', b'maxwell'])\")\nflags.DEFINE_integer(\"statistics_interval\", 5,\n \"Print statistics every n seconds.\")\nflags.DEFINE_integer(\"summary_interval\", 5,\n \"Save training summary to file every n seconds (rounded \"\n \"up to statistics interval).\")\nflags.DEFINE_integer(\"checkpoint_interval\", 600,\n \"Checkpoint the model (i.e. save the parameters) every n \"\n \"seconds (rounded up to statistics interval).\")\n\nFLAGS = flags.FLAGS\n\n\nclass Options(object):\n \"\"\"Options used by our word2vec model.\"\"\"\n\n def __init__(self):\n # Model options.\n\n # Embedding dimension.\n self.emb_dim = FLAGS.embedding_size\n\n # Training options.\n # The training text file.\n self.train_data = FLAGS.train_data\n\n # Number of negative samples per example.\n self.num_samples = FLAGS.num_neg_samples\n\n # The initial learning rate.\n self.learning_rate = FLAGS.learning_rate\n\n # Number of epochs to train. After these many epochs, the learning\n # rate decays linearly to zero and the training stops.\n self.epochs_to_train = FLAGS.epochs_to_train\n\n # Concurrent training steps.\n self.concurrent_steps = FLAGS.concurrent_steps\n\n # Number of examples for one training step.\n self.batch_size = FLAGS.batch_size\n\n # The number of words to predict to the left and right of the target word.\n self.window_size = FLAGS.window_size\n\n # The minimum number of word occurrences for it to be included in the\n # vocabulary.\n self.min_count = FLAGS.min_count\n\n # Subsampling threshold for word occurrence.\n self.subsample = FLAGS.subsample\n\n # How often to print statistics.\n self.statistics_interval = FLAGS.statistics_interval\n\n # How often to write to the summary file (rounds up to the nearest\n # statistics_interval).\n self.summary_interval = FLAGS.summary_interval\n\n # How often to write checkpoints (rounds up to the nearest statistics\n # interval).\n self.checkpoint_interval = FLAGS.checkpoint_interval\n\n # Where to write out summaries.\n self.save_path = FLAGS.save_path\n\n # Eval options.\n # The text file for eval.\n self.eval_data = FLAGS.eval_data\n\n\nclass Word2Vec(object):\n \"\"\"Word2Vec model (Skipgram).\"\"\"\n\n def __init__(self, options, session):\n self._options = options\n self._session = session\n self._word2id = {}\n self._id2word = []\n self.build_graph()\n self.build_eval_graph()\n self.save_vocab()\n self._read_analogies()\n\n def _read_analogies(self):\n \"\"\"Reads through the analogy question file.\n\n Returns:\n questions: a [n, 4] numpy array containing the analogy question's\n word ids.\n questions_skipped: questions skipped due to unknown words.\n \"\"\"\n questions = []\n questions_skipped = 0\n with open(self._options.eval_data, \"rb\") as analogy_f:\n for line in analogy_f:\n if line.startswith(b\":\"): # Skip comments.\n continue\n words = line.strip().lower().split(b\" \")\n ids = [self._word2id.get(w.strip()) for w in words]\n if None in ids or len(ids) != 4:\n questions_skipped += 1\n else:\n questions.append(np.array(ids))\n print(\"Eval analogy file: \", self._options.eval_data)\n print(\"Questions: \", len(questions))\n print(\"Skipped: \", questions_skipped)\n self._analogy_questions = np.array(questions, dtype=np.int32)\n\n def forward(self, examples, labels):\n \"\"\"Build the graph for the forward pass.\"\"\"\n opts = self._options\n\n # Declare all variables we need.\n # Embedding: [vocab_size, emb_dim]\n init_width = 0.5 / opts.emb_dim\n emb = tf.Variable(\n tf.random_uniform(\n [opts.vocab_size, opts.emb_dim], -init_width, init_width),\n name=\"emb\")\n self._emb = emb\n\n # Softmax weight: [vocab_size, emb_dim]. Transposed.\n sm_w_t = tf.Variable(\n tf.zeros([opts.vocab_size, opts.emb_dim]),\n name=\"sm_w_t\")\n\n # Softmax bias: [emb_dim].\n sm_b = tf.Variable(tf.zeros([opts.vocab_size]), name=\"sm_b\")\n\n # Global step: scalar, i.e., shape [].\n self.global_step = tf.Variable(0, name=\"global_step\")\n\n # Nodes to compute the nce loss w/ candidate sampling.\n labels_matrix = tf.reshape(\n tf.cast(labels,\n dtype=tf.int64),\n [opts.batch_size, 1])\n\n # Negative sampling.\n sampled_ids, _, _ = (tf.nn.fixed_unigram_candidate_sampler(\n true_classes=labels_matrix,\n num_true=1,\n num_sampled=opts.num_samples,\n unique=True,\n range_max=opts.vocab_size,\n distortion=0.75,\n unigrams=opts.vocab_counts.tolist()))\n\n # Embeddings for examples: [batch_size, emb_dim]\n example_emb = tf.nn.embedding_lookup(emb, examples)\n\n # Weights for labels: [batch_size, emb_dim]\n true_w = tf.nn.embedding_lookup(sm_w_t, labels)\n # Biases for labels: [batch_size, 1]\n true_b = tf.nn.embedding_lookup(sm_b, labels)\n\n # Weights for sampled ids: [num_sampled, emb_dim]\n sampled_w = tf.nn.embedding_lookup(sm_w_t, sampled_ids)\n # Biases for sampled ids: [num_sampled, 1]\n sampled_b = tf.nn.embedding_lookup(sm_b, sampled_ids)\n\n # True logits: [batch_size, 1]\n true_logits = tf.reduce_sum(tf.mul(example_emb, true_w), 1) + true_b\n\n # Sampled logits: [batch_size, num_sampled]\n # We replicate sampled noise lables for all examples in the batch\n # using the matmul.\n sampled_b_vec = tf.reshape(sampled_b, [opts.num_samples])\n sampled_logits = tf.matmul(example_emb,\n sampled_w,\n transpose_b=True) + sampled_b_vec\n return true_logits, sampled_logits\n\n def nce_loss(self, true_logits, sampled_logits):\n \"\"\"Build the graph for the NCE loss.\"\"\"\n\n # cross-entropy(logits, labels)\n opts = self._options\n true_xent = tf.nn.sigmoid_cross_entropy_with_logits(\n true_logits, tf.ones_like(true_logits))\n sampled_xent = tf.nn.sigmoid_cross_entropy_with_logits(\n sampled_logits, tf.zeros_like(sampled_logits))\n\n # NCE-loss is the sum of the true and noise (sampled words)\n # contributions, averaged over the batch.\n nce_loss_tensor = (tf.reduce_sum(true_xent) +\n tf.reduce_sum(sampled_xent)) / opts.batch_size\n return nce_loss_tensor\n\n def optimize(self, loss):\n \"\"\"Build the graph to optimize the loss function.\"\"\"\n\n # Optimizer nodes.\n # Linear learning rate decay.\n opts = self._options\n words_to_train = float(opts.words_per_epoch * opts.epochs_to_train)\n lr = opts.learning_rate * tf.maximum(\n 0.0001, 1.0 - tf.cast(self._words, tf.float32) / words_to_train)\n self._lr = lr\n optimizer = tf.train.GradientDescentOptimizer(lr)\n train = optimizer.minimize(loss,\n global_step=self.global_step,\n gate_gradients=optimizer.GATE_NONE)\n self._train = train\n\n def build_eval_graph(self):\n \"\"\"Build the eval graph.\"\"\"\n # Eval graph\n\n # Each analogy task is to predict the 4th word (d) given three\n # words: a, b, c. E.g., a=italy, b=rome, c=france, we should\n # predict d=paris.\n\n # The eval feeds three vectors of word ids for a, b, c, each of\n # which is of size N, where N is the number of analogies we want to\n # evaluate in one batch.\n analogy_a = tf.placeholder(dtype=tf.int32) # [N]\n analogy_b = tf.placeholder(dtype=tf.int32) # [N]\n analogy_c = tf.placeholder(dtype=tf.int32) # [N]\n\n # Normalized word embeddings of shape [vocab_size, emb_dim].\n nemb = tf.nn.l2_normalize(self._emb, 1)\n\n # Each row of a_emb, b_emb, c_emb is a word's embedding vector.\n # They all have the shape [N, emb_dim]\n a_emb = tf.gather(nemb, analogy_a) # a's embs\n b_emb = tf.gather(nemb, analogy_b) # b's embs\n c_emb = tf.gather(nemb, analogy_c) # c's embs\n\n # We expect that d's embedding vectors on the unit hyper-sphere is\n # near: c_emb + (b_emb - a_emb), which has the shape [N, emb_dim].\n target = c_emb + (b_emb - a_emb)\n\n # Compute cosine distance between each pair of target and vocab.\n # dist has shape [N, vocab_size].\n dist = tf.matmul(target, nemb, transpose_b=True)\n\n # For each question (row in dist), find the top 4 words.\n _, pred_idx = tf.nn.top_k(dist, 4)\n\n # Nodes for computing neighbors for a given word according to\n # their cosine distance.\n nearby_word = tf.placeholder(dtype=tf.int32) # word id\n nearby_emb = tf.gather(nemb, nearby_word)\n nearby_dist = tf.matmul(nearby_emb, nemb, transpose_b=True)\n nearby_val, nearby_idx = tf.nn.top_k(nearby_dist,\n min(1000, self._options.vocab_size))\n\n # Nodes in the construct graph which are used by training and\n # evaluation to run/feed/fetch.\n self._analogy_a = analogy_a\n self._analogy_b = analogy_b\n self._analogy_c = analogy_c\n self._analogy_pred_idx = pred_idx\n self._nearby_word = nearby_word\n self._nearby_val = nearby_val\n self._nearby_idx = nearby_idx\n\n def build_graph(self):\n \"\"\"Build the graph for the full model.\"\"\"\n opts = self._options\n # The training data. A text file.\n (words, counts, words_per_epoch, self._epoch, self._words, examples,\n labels) = word2vec.skipgram(filename=opts.train_data,\n batch_size=opts.batch_size,\n window_size=opts.window_size,\n min_count=opts.min_count,\n subsample=opts.subsample)\n (opts.vocab_words, opts.vocab_counts,\n opts.words_per_epoch) = self._session.run([words, counts, words_per_epoch])\n opts.vocab_size = len(opts.vocab_words)\n print(\"Data file: \", opts.train_data)\n print(\"Vocab size: \", opts.vocab_size - 1, \" + UNK\")\n print(\"Words per epoch: \", opts.words_per_epoch)\n self._examples = examples\n self._labels = labels\n self._id2word = opts.vocab_words\n for i, w in enumerate(self._id2word):\n self._word2id[w] = i\n true_logits, sampled_logits = self.forward(examples, labels)\n loss = self.nce_loss(true_logits, sampled_logits)\n tf.scalar_summary(\"NCE loss\", loss)\n self._loss = loss\n self.optimize(loss)\n\n # Properly initialize all variables.\n tf.initialize_all_variables().run()\n\n self.saver = tf.train.Saver()\n\n def save_vocab(self):\n \"\"\"Save the vocabulary to a file so the model can be reloaded.\"\"\"\n opts = self._options\n with open(os.path.join(opts.save_path, \"vocab.txt\"), \"w\") as f:\n for i in xrange(opts.vocab_size):\n f.write(\"%s %d\\n\" % (tf.compat.as_text(opts.vocab_words[i]),\n opts.vocab_counts[i]))\n\n def _train_thread_body(self):\n initial_epoch, = self._session.run([self._epoch])\n while True:\n _, epoch = self._session.run([self._train, self._epoch])\n if epoch != initial_epoch:\n break\n\n def train(self):\n \"\"\"Train the model.\"\"\"\n opts = self._options\n\n initial_epoch, initial_words = self._session.run([self._epoch, self._words])\n\n summary_op = tf.merge_all_summaries()\n summary_writer = tf.train.SummaryWriter(opts.save_path, self._session.graph)\n workers = []\n for _ in xrange(opts.concurrent_steps):\n t = threading.Thread(target=self._train_thread_body)\n t.start()\n workers.append(t)\n\n last_words, last_time, last_summary_time = initial_words, time.time(), 0\n last_checkpoint_time = 0\n while True:\n time.sleep(opts.statistics_interval) # Reports our progress once a while.\n (epoch, step, loss, words, lr) = self._session.run(\n [self._epoch, self.global_step, self._loss, self._words, self._lr])\n now = time.time()\n last_words, last_time, rate = words, now, (words - last_words) / (\n now - last_time)\n print(\"Epoch %4d Step %8d: lr = %5.3f loss = %6.2f words/sec = %8.0f\\r\" %\n (epoch, step, lr, loss, rate), end=\"\")\n sys.stdout.flush()\n if now - last_summary_time > opts.summary_interval:\n summary_str = self._session.run(summary_op)\n summary_writer.add_summary(summary_str, step)\n last_summary_time = now\n if now - last_checkpoint_time > opts.checkpoint_interval:\n self.saver.save(self._session,\n os.path.join(opts.save_path, \"model.ckpt\"),\n global_step=step.astype(int))\n last_checkpoint_time = now\n if epoch != initial_epoch:\n break\n\n for t in workers:\n t.join()\n\n return epoch\n\n def _predict(self, analogy):\n \"\"\"Predict the top 4 answers for analogy questions.\"\"\"\n idx, = self._session.run([self._analogy_pred_idx], {\n self._analogy_a: analogy[:, 0],\n self._analogy_b: analogy[:, 1],\n self._analogy_c: analogy[:, 2]\n })\n return idx\n\n def eval(self):\n \"\"\"Evaluate analogy questions and reports accuracy.\"\"\"\n\n # How many questions we get right at precision@1.\n correct = 0\n\n total = self._analogy_questions.shape[0]\n start = 0\n while start < total:\n limit = start + 2500\n sub = self._analogy_questions[start:limit, :]\n idx = self._predict(sub)\n start = limit\n for question in xrange(sub.shape[0]):\n for j in xrange(4):\n if idx[question, j] == sub[question, 3]:\n # Bingo! We predicted correctly. E.g., [italy, rome, france, paris].\n correct += 1\n break\n elif idx[question, j] in sub[question, :3]:\n # We need to skip words already in the question.\n continue\n else:\n # The correct label is not the precision@1\n break\n print()\n print(\"Eval %4d/%d accuracy = %4.1f%%\" % (correct, total,\n correct * 100.0 / total))\n\n def analogy(self, w0, w1, w2):\n \"\"\"Predict word w3 as in w0:w1 vs w2:w3.\"\"\"\n wid = np.array([[self._word2id.get(w, 0) for w in [w0, w1, w2]]])\n idx = self._predict(wid)\n for c in [self._id2word[i] for i in idx[0, :]]:\n if c not in [w0, w1, w2]:\n return c\n return \"unknown\"\n\n def nearby(self, words, num=20):\n \"\"\"Prints out nearby words given a list of words.\"\"\"\n ids = np.array([self._word2id.get(x, 0) for x in words])\n vals, idx = self._session.run(\n [self._nearby_val, self._nearby_idx], {self._nearby_word: ids})\n for i in xrange(len(words)):\n print(\"\\n%s\\n=====================================\" % (words[i]))\n for (neighbor, distance) in zip(idx[i, :num], vals[i, :num]):\n print(\"%-20s %6.4f\" % (self._id2word[neighbor], distance))\n\n\ndef _start_shell(local_ns=None):\n # An interactive shell is useful for debugging/development.\n import IPython\n user_ns = {}\n if local_ns:\n user_ns.update(local_ns)\n user_ns.update(globals())\n IPython.start_ipython(argv=[], user_ns=user_ns)\n\n\ndef main(_):\n \"\"\"Train a word2vec model.\"\"\"\n if not FLAGS.train_data or not FLAGS.eval_data or not FLAGS.save_path:\n print(\"--train_data --eval_data and --save_path must be specified.\")\n sys.exit(1)\n opts = Options()\n with tf.Graph().as_default(), tf.Session() as session:\n with tf.device(\"/cpu:0\"):\n model = Word2Vec(opts, session)\n for _ in xrange(opts.epochs_to_train):\n model.train() # Process one epoch\n model.eval() # Eval analogies.\n # Perform a final save.\n model.saver.save(session,\n os.path.join(opts.save_path, \"model.ckpt\"),\n global_step=model.global_step)\n if FLAGS.interactive:\n # E.g.,\n # [0]: model.analogy(b'france', b'paris', b'russia')\n # [1]: model.nearby([b'proton', b'elephant', b'maxwell'])\n _start_shell(locals())\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n",
"# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow.ops.check_ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\n\nclass AssertProperIterableTest(tf.test.TestCase):\n\n def test_single_tensor_raises(self):\n tensor = tf.constant(1)\n with self.assertRaisesRegexp(TypeError, \"proper\"):\n tf.assert_proper_iterable(tensor)\n\n def test_single_sparse_tensor_raises(self):\n ten = tf.SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], shape=[3, 4])\n with self.assertRaisesRegexp(TypeError, \"proper\"):\n tf.assert_proper_iterable(ten)\n\n def test_single_ndarray_raises(self):\n array = np.array([1, 2, 3])\n with self.assertRaisesRegexp(TypeError, \"proper\"):\n tf.assert_proper_iterable(array)\n\n def test_single_string_raises(self):\n mystr = \"hello\"\n with self.assertRaisesRegexp(TypeError, \"proper\"):\n tf.assert_proper_iterable(mystr)\n\n def test_non_iterable_object_raises(self):\n non_iterable = 1234\n with self.assertRaisesRegexp(TypeError, \"to be iterable\"):\n tf.assert_proper_iterable(non_iterable)\n\n def test_list_does_not_raise(self):\n list_of_stuff = [tf.constant([11, 22]), tf.constant([1, 2])]\n tf.assert_proper_iterable(list_of_stuff)\n\n def test_generator_does_not_raise(self):\n generator_of_stuff = (tf.constant([11, 22]), tf.constant([1, 2]))\n tf.assert_proper_iterable(generator_of_stuff)\n\n\nclass AssertEqualTest(tf.test.TestCase):\n\n def test_doesnt_raise_when_equal(self):\n with self.test_session():\n small = tf.constant([1, 2], name=\"small\")\n with tf.control_dependencies([tf.assert_equal(small, small)]):\n out = tf.identity(small)\n out.eval()\n\n def test_raises_when_greater(self):\n with self.test_session():\n small = tf.constant([1, 2], name=\"small\")\n big = tf.constant([3, 4], name=\"big\")\n with tf.control_dependencies([tf.assert_equal(big, small)]):\n out = tf.identity(small)\n with self.assertRaisesOpError(\"big.*small\"):\n out.eval()\n\n def test_raises_when_less(self):\n with self.test_session():\n small = tf.constant([3, 1], name=\"small\")\n big = tf.constant([4, 2], name=\"big\")\n with tf.control_dependencies([tf.assert_equal(small, big)]):\n out = tf.identity(small)\n with self.assertRaisesOpError(\"small.*big\"):\n out.eval()\n\n def test_doesnt_raise_when_equal_and_broadcastable_shapes(self):\n with self.test_session():\n small = tf.constant([1, 2], name=\"small\")\n small_2 = tf.constant([1, 2], name=\"small_2\")\n with tf.control_dependencies([tf.assert_equal(small, small_2)]):\n out = tf.identity(small)\n out.eval()\n\n def test_raises_when_equal_but_non_broadcastable_shapes(self):\n with self.test_session():\n small = tf.constant([1, 1, 1], name=\"small\")\n small_2 = tf.constant([1, 1], name=\"small_2\")\n with self.assertRaisesRegexp(ValueError, \"broadcast\"):\n with tf.control_dependencies([tf.assert_equal(small, small_2)]):\n out = tf.identity(small)\n out.eval()\n\n def test_doesnt_raise_when_both_empty(self):\n with self.test_session():\n larry = tf.constant([])\n curly = tf.constant([])\n with tf.control_dependencies([tf.assert_equal(larry, curly)]):\n out = tf.identity(larry)\n out.eval()\n\n\nclass AssertLessTest(tf.test.TestCase):\n\n def test_raises_when_equal(self):\n with self.test_session():\n small = tf.constant([1, 2], name=\"small\")\n with tf.control_dependencies([tf.assert_less(small, small)]):\n out = tf.identity(small)\n with self.assertRaisesOpError(\"small.*small\"):\n out.eval()\n\n def test_raises_when_greater(self):\n with self.test_session():\n small = tf.constant([1, 2], name=\"small\")\n big = tf.constant([3, 4], name=\"big\")\n with tf.control_dependencies([tf.assert_less(big, small)]):\n out = tf.identity(small)\n with self.assertRaisesOpError(\"big.*small\"):\n out.eval()\n\n def test_doesnt_raise_when_less(self):\n with self.test_session():\n small = tf.constant([3, 1], name=\"small\")\n big = tf.constant([4, 2], name=\"big\")\n with tf.control_dependencies([tf.assert_less(small, big)]):\n out = tf.identity(small)\n out.eval()\n\n def test_doesnt_raise_when_less_and_broadcastable_shapes(self):\n with self.test_session():\n small = tf.constant([1], name=\"small\")\n big = tf.constant([3, 2], name=\"big\")\n with tf.control_dependencies([tf.assert_less(small, big)]):\n out = tf.identity(small)\n out.eval()\n\n def test_raises_when_less_but_non_broadcastable_shapes(self):\n with self.test_session():\n small = tf.constant([1, 1, 1], name=\"small\")\n big = tf.constant([3, 2], name=\"big\")\n with self.assertRaisesRegexp(ValueError, \"broadcast\"):\n with tf.control_dependencies([tf.assert_less(small, big)]):\n out = tf.identity(small)\n out.eval()\n\n def test_doesnt_raise_when_both_empty(self):\n with self.test_session():\n larry = tf.constant([])\n curly = tf.constant([])\n with tf.control_dependencies([tf.assert_less(larry, curly)]):\n out = tf.identity(larry)\n out.eval()\n\n\nclass AssertLessEqualTest(tf.test.TestCase):\n\n def test_doesnt_raise_when_equal(self):\n with self.test_session():\n small = tf.constant([1, 2], name=\"small\")\n with tf.control_dependencies([tf.assert_less_equal(small, small)]):\n out = tf.identity(small)\n out.eval()\n\n def test_raises_when_greater(self):\n with self.test_session():\n small = tf.constant([1, 2], name=\"small\")\n big = tf.constant([3, 4], name=\"big\")\n with tf.control_dependencies([tf.assert_less_equal(big, small)]):\n out = tf.identity(small)\n with self.assertRaisesOpError(\"big.*small\"):\n out.eval()\n\n def test_doesnt_raise_when_less_equal(self):\n with self.test_session():\n small = tf.constant([1, 2], name=\"small\")\n big = tf.constant([3, 2], name=\"big\")\n with tf.control_dependencies([tf.assert_less_equal(small, big)]):\n out = tf.identity(small)\n out.eval()\n\n def test_doesnt_raise_when_less_equal_and_broadcastable_shapes(self):\n with self.test_session():\n small = tf.constant([1], name=\"small\")\n big = tf.constant([3, 1], name=\"big\")\n with tf.control_dependencies([tf.assert_less_equal(small, big)]):\n out = tf.identity(small)\n out.eval()\n\n def test_raises_when_less_equal_but_non_broadcastable_shapes(self):\n with self.test_session():\n small = tf.constant([1, 1, 1], name=\"small\")\n big = tf.constant([3, 1], name=\"big\")\n with self.assertRaisesRegexp(ValueError, \"broadcast\"):\n with tf.control_dependencies([tf.assert_less_equal(small, big)]):\n out = tf.identity(small)\n out.eval()\n\n def test_doesnt_raise_when_both_empty(self):\n with self.test_session():\n larry = tf.constant([])\n curly = tf.constant([])\n with tf.control_dependencies([tf.assert_less_equal(larry, curly)]):\n out = tf.identity(larry)\n out.eval()\n\n\nclass AssertNegativeTest(tf.test.TestCase):\n\n def test_doesnt_raise_when_negative(self):\n with self.test_session():\n frank = tf.constant([-1, -2], name=\"frank\")\n with tf.control_dependencies([tf.assert_negative(frank)]):\n out = tf.identity(frank)\n out.eval()\n\n def test_raises_when_positive(self):\n with self.test_session():\n doug = tf.constant([1, 2], name=\"doug\")\n with tf.control_dependencies([tf.assert_negative(doug)]):\n out = tf.identity(doug)\n with self.assertRaisesOpError(\"doug\"):\n out.eval()\n\n def test_raises_when_zero(self):\n with self.test_session():\n claire = tf.constant([0], name=\"claire\")\n with tf.control_dependencies([tf.assert_negative(claire)]):\n out = tf.identity(claire)\n with self.assertRaisesOpError(\"claire\"):\n out.eval()\n\n def test_empty_tensor_doesnt_raise(self):\n # A tensor is negative when it satisfies:\n # For every element x_i in x, x_i < 0\n # and an empty tensor has no elements, so this is trivially satisfied.\n # This is standard set theory.\n with self.test_session():\n empty = tf.constant([], name=\"empty\")\n with tf.control_dependencies([tf.assert_negative(empty)]):\n out = tf.identity(empty)\n out.eval()\n\n\nclass AssertPositiveTest(tf.test.TestCase):\n\n def test_raises_when_negative(self):\n with self.test_session():\n freddie = tf.constant([-1, -2], name=\"freddie\")\n with tf.control_dependencies([tf.assert_positive(freddie)]):\n out = tf.identity(freddie)\n with self.assertRaisesOpError(\"freddie\"):\n out.eval()\n\n def test_doesnt_raise_when_positive(self):\n with self.test_session():\n remmy = tf.constant([1, 2], name=\"remmy\")\n with tf.control_dependencies([tf.assert_positive(remmy)]):\n out = tf.identity(remmy)\n out.eval()\n\n def test_raises_when_zero(self):\n with self.test_session():\n meechum = tf.constant([0], name=\"meechum\")\n with tf.control_dependencies([tf.assert_positive(meechum)]):\n out = tf.identity(meechum)\n with self.assertRaisesOpError(\"meechum\"):\n out.eval()\n\n def test_empty_tensor_doesnt_raise(self):\n # A tensor is positive when it satisfies:\n # For every element x_i in x, x_i > 0\n # and an empty tensor has no elements, so this is trivially satisfied.\n # This is standard set theory.\n with self.test_session():\n empty = tf.constant([], name=\"empty\")\n with tf.control_dependencies([tf.assert_positive(empty)]):\n out = tf.identity(empty)\n out.eval()\n\n\nclass AssertRankTest(tf.test.TestCase):\n\n def test_rank_zero_tensor_raises_if_rank_too_small_static_rank(self):\n with self.test_session():\n tensor = tf.constant(1, name=\"my_tensor\")\n desired_rank = 1\n with self.assertRaisesRegexp(ValueError, \"my_tensor.*must have rank 1\"):\n with tf.control_dependencies([tf.assert_rank(tensor, desired_rank)]):\n tf.identity(tensor).eval()\n\n def test_rank_zero_tensor_raises_if_rank_too_small_dynamic_rank(self):\n with self.test_session():\n tensor = tf.placeholder(tf.float32, name=\"my_tensor\")\n desired_rank = 1\n with tf.control_dependencies([tf.assert_rank(tensor, desired_rank)]):\n with self.assertRaisesOpError(\"my_tensor.*rank\"):\n tf.identity(tensor).eval(feed_dict={tensor: 0})\n\n def test_rank_zero_tensor_doesnt_raise_if_rank_just_right_static_rank(self):\n with self.test_session():\n tensor = tf.constant(1, name=\"my_tensor\")\n desired_rank = 0\n with tf.control_dependencies([tf.assert_rank(tensor, desired_rank)]):\n tf.identity(tensor).eval()\n\n def test_rank_zero_tensor_doesnt_raise_if_rank_just_right_dynamic_rank(self):\n with self.test_session():\n tensor = tf.placeholder(tf.float32, name=\"my_tensor\")\n desired_rank = 0\n with tf.control_dependencies([tf.assert_rank(tensor, desired_rank)]):\n tf.identity(tensor).eval(feed_dict={tensor: 0})\n\n def test_rank_one_tensor_raises_if_rank_too_large_static_rank(self):\n with self.test_session():\n tensor = tf.constant([1, 2], name=\"my_tensor\")\n desired_rank = 0\n with self.assertRaisesRegexp(ValueError, \"my_tensor.*rank\"):\n with tf.control_dependencies([tf.assert_rank(tensor, desired_rank)]):\n tf.identity(tensor).eval()\n\n def test_rank_one_tensor_raises_if_rank_too_large_dynamic_rank(self):\n with self.test_session():\n tensor = tf.placeholder(tf.float32, name=\"my_tensor\")\n desired_rank = 0\n with tf.control_dependencies([tf.assert_rank(tensor, desired_rank)]):\n with self.assertRaisesOpError(\"my_tensor.*rank\"):\n tf.identity(tensor).eval(feed_dict={tensor: [1, 2]})\n\n def test_rank_one_tensor_doesnt_raise_if_rank_just_right_static_rank(self):\n with self.test_session():\n tensor = tf.constant([1, 2], name=\"my_tensor\")\n desired_rank = 1\n with tf.control_dependencies([tf.assert_rank(tensor, desired_rank)]):\n tf.identity(tensor).eval()\n\n def test_rank_one_tensor_doesnt_raise_if_rank_just_right_dynamic_rank(self):\n with self.test_session():\n tensor = tf.placeholder(tf.float32, name=\"my_tensor\")\n desired_rank = 1\n with tf.control_dependencies([tf.assert_rank(tensor, desired_rank)]):\n tf.identity(tensor).eval(feed_dict={tensor: [1, 2]})\n\n def test_rank_one_tensor_raises_if_rank_too_small_static_rank(self):\n with self.test_session():\n tensor = tf.constant([1, 2], name=\"my_tensor\")\n desired_rank = 2\n with self.assertRaisesRegexp(ValueError, \"my_tensor.*rank\"):\n with tf.control_dependencies([tf.assert_rank(tensor, desired_rank)]):\n tf.identity(tensor).eval()\n\n def test_rank_one_tensor_raises_if_rank_too_small_dynamic_rank(self):\n with self.test_session():\n tensor = tf.placeholder(tf.float32, name=\"my_tensor\")\n desired_rank = 2\n with tf.control_dependencies([tf.assert_rank(tensor, desired_rank)]):\n with self.assertRaisesOpError(\"my_tensor.*rank\"):\n tf.identity(tensor).eval(feed_dict={tensor: [1, 2]})\n\n def test_raises_if_rank_is_not_scalar_static(self):\n with self.test_session():\n tensor = tf.constant([1, 2], name=\"my_tensor\")\n with self.assertRaisesRegexp(ValueError, \"Rank must be a scalar\"):\n tf.assert_rank(tensor, np.array([], dtype=np.int32))\n\n def test_raises_if_rank_is_not_scalar_dynamic(self):\n with self.test_session():\n tensor = tf.constant([1, 2], dtype=tf.float32, name=\"my_tensor\")\n rank_tensor = tf.placeholder(tf.int32, name=\"rank_tensor\")\n with self.assertRaisesOpError(\"Rank must be a scalar\"):\n with tf.control_dependencies([tf.assert_rank(tensor, rank_tensor)]):\n tf.identity(tensor).eval(feed_dict={rank_tensor: [1, 2]})\n\n def test_raises_if_rank_is_not_integer_static(self):\n with self.test_session():\n tensor = tf.constant([1, 2], name=\"my_tensor\")\n with self.assertRaisesRegexp(ValueError,\n \"must be of type <dtype: 'int32'>\"):\n tf.assert_rank(tensor, .5)\n\n def test_raises_if_rank_is_not_integer_dynamic(self):\n with self.test_session():\n tensor = tf.constant([1, 2], dtype=tf.float32, name=\"my_tensor\")\n rank_tensor = tf.placeholder(tf.float32, name=\"rank_tensor\")\n with self.assertRaisesRegexp(ValueError,\n \"must be of type <dtype: 'int32'>\"):\n with tf.control_dependencies([tf.assert_rank(tensor, rank_tensor)]):\n tf.identity(tensor).eval(feed_dict={rank_tensor: .5})\n\n\nclass AssertRankAtLeastTest(tf.test.TestCase):\n\n def test_rank_zero_tensor_raises_if_rank_too_small_static_rank(self):\n with self.test_session():\n tensor = tf.constant(1, name=\"my_tensor\")\n desired_rank = 1\n with self.assertRaisesRegexp(ValueError, \"my_tensor.*rank at least 1\"):\n with tf.control_dependencies([tf.assert_rank_at_least(tensor,\n desired_rank)]):\n tf.identity(tensor).eval()\n\n def test_rank_zero_tensor_raises_if_rank_too_small_dynamic_rank(self):\n with self.test_session():\n tensor = tf.placeholder(tf.float32, name=\"my_tensor\")\n desired_rank = 1\n with tf.control_dependencies([tf.assert_rank_at_least(tensor,\n desired_rank)]):\n with self.assertRaisesOpError(\"my_tensor.*rank\"):\n tf.identity(tensor).eval(feed_dict={tensor: 0})\n\n def test_rank_zero_tensor_doesnt_raise_if_rank_just_right_static_rank(self):\n with self.test_session():\n tensor = tf.constant(1, name=\"my_tensor\")\n desired_rank = 0\n with tf.control_dependencies([tf.assert_rank_at_least(tensor,\n desired_rank)]):\n tf.identity(tensor).eval()\n\n def test_rank_zero_tensor_doesnt_raise_if_rank_just_right_dynamic_rank(self):\n with self.test_session():\n tensor = tf.placeholder(tf.float32, name=\"my_tensor\")\n desired_rank = 0\n with tf.control_dependencies([tf.assert_rank_at_least(tensor,\n desired_rank)]):\n tf.identity(tensor).eval(feed_dict={tensor: 0})\n\n def test_rank_one_ten_doesnt_raise_raise_if_rank_too_large_static_rank(self):\n with self.test_session():\n tensor = tf.constant([1, 2], name=\"my_tensor\")\n desired_rank = 0\n with tf.control_dependencies([tf.assert_rank_at_least(tensor,\n desired_rank)]):\n tf.identity(tensor).eval()\n\n def test_rank_one_ten_doesnt_raise_if_rank_too_large_dynamic_rank(self):\n with self.test_session():\n tensor = tf.placeholder(tf.float32, name=\"my_tensor\")\n desired_rank = 0\n with tf.control_dependencies([tf.assert_rank_at_least(tensor,\n desired_rank)]):\n tf.identity(tensor).eval(feed_dict={tensor: [1, 2]})\n\n def test_rank_one_tensor_doesnt_raise_if_rank_just_right_static_rank(self):\n with self.test_session():\n tensor = tf.constant([1, 2], name=\"my_tensor\")\n desired_rank = 1\n with tf.control_dependencies([tf.assert_rank_at_least(tensor,\n desired_rank)]):\n tf.identity(tensor).eval()\n\n def test_rank_one_tensor_doesnt_raise_if_rank_just_right_dynamic_rank(self):\n with self.test_session():\n tensor = tf.placeholder(tf.float32, name=\"my_tensor\")\n desired_rank = 1\n with tf.control_dependencies([tf.assert_rank_at_least(tensor,\n desired_rank)]):\n tf.identity(tensor).eval(feed_dict={tensor: [1, 2]})\n\n def test_rank_one_tensor_raises_if_rank_too_small_static_rank(self):\n with self.test_session():\n tensor = tf.constant([1, 2], name=\"my_tensor\")\n desired_rank = 2\n with self.assertRaisesRegexp(ValueError, \"my_tensor.*rank\"):\n with tf.control_dependencies([tf.assert_rank_at_least(tensor,\n desired_rank)]):\n tf.identity(tensor).eval()\n\n def test_rank_one_tensor_raises_if_rank_too_small_dynamic_rank(self):\n with self.test_session():\n tensor = tf.placeholder(tf.float32, name=\"my_tensor\")\n desired_rank = 2\n with tf.control_dependencies([tf.assert_rank_at_least(tensor,\n desired_rank)]):\n with self.assertRaisesOpError(\"my_tensor.*rank\"):\n tf.identity(tensor).eval(feed_dict={tensor: [1, 2]})\n\n\nclass AssertNonNegativeTest(tf.test.TestCase):\n\n def test_raises_when_negative(self):\n with self.test_session():\n zoe = tf.constant([-1, -2], name=\"zoe\")\n with tf.control_dependencies([tf.assert_non_negative(zoe)]):\n out = tf.identity(zoe)\n with self.assertRaisesOpError(\"zoe\"):\n out.eval()\n\n def test_doesnt_raise_when_zero_and_positive(self):\n with self.test_session():\n lucas = tf.constant([0, 2], name=\"lucas\")\n with tf.control_dependencies([tf.assert_non_negative(lucas)]):\n out = tf.identity(lucas)\n out.eval()\n\n def test_empty_tensor_doesnt_raise(self):\n # A tensor is non-negative when it satisfies:\n # For every element x_i in x, x_i >= 0\n # and an empty tensor has no elements, so this is trivially satisfied.\n # This is standard set theory.\n with self.test_session():\n empty = tf.constant([], name=\"empty\")\n with tf.control_dependencies([tf.assert_non_negative(empty)]):\n out = tf.identity(empty)\n out.eval()\n\n\nclass AssertNonPositiveTest(tf.test.TestCase):\n\n def test_doesnt_raise_when_zero_and_negative(self):\n with self.test_session():\n tom = tf.constant([0, -2], name=\"tom\")\n with tf.control_dependencies([tf.assert_non_positive(tom)]):\n out = tf.identity(tom)\n out.eval()\n\n def test_raises_when_positive(self):\n with self.test_session():\n rachel = tf.constant([0, 2], name=\"rachel\")\n with tf.control_dependencies([tf.assert_non_positive(rachel)]):\n out = tf.identity(rachel)\n with self.assertRaisesOpError(\"rachel\"):\n out.eval()\n\n def test_empty_tensor_doesnt_raise(self):\n # A tensor is non-positive when it satisfies:\n # For every element x_i in x, x_i <= 0\n # and an empty tensor has no elements, so this is trivially satisfied.\n # This is standard set theory.\n with self.test_session():\n empty = tf.constant([], name=\"empty\")\n with tf.control_dependencies([tf.assert_non_positive(empty)]):\n out = tf.identity(empty)\n out.eval()\n\n\nclass AssertIntegerTest(tf.test.TestCase):\n\n def test_doesnt_raise_when_integer(self):\n with self.test_session():\n integers = tf.constant([1, 2], name=\"integers\")\n with tf.control_dependencies([tf.assert_integer(integers)]):\n out = tf.identity(integers)\n out.eval()\n\n def test_raises_when_float(self):\n with self.test_session():\n floats = tf.constant([1.0, 2.0], name=\"floats\")\n with tf.control_dependencies([tf.assert_integer(floats)]):\n out = tf.identity(floats)\n with self.assertRaisesOpError(\"x is not of integer dtype.*\"):\n out.eval()\n\n\nclass IsStrictlyIncreasingTest(tf.test.TestCase):\n\n def test_constant_tensor_is_not_strictly_increasing(self):\n with self.test_session():\n self.assertFalse(tf.is_strictly_increasing([1, 1, 1]).eval())\n\n def test_decreasing_tensor_is_not_strictly_increasing(self):\n with self.test_session():\n self.assertFalse(tf.is_strictly_increasing([1, 0, -1]).eval())\n\n def test_2d_decreasing_tensor_is_not_strictly_increasing(self):\n with self.test_session():\n self.assertFalse(tf.is_strictly_increasing([[1, 3], [2, 4]]).eval())\n\n def test_increasing_tensor_is_increasing(self):\n with self.test_session():\n self.assertTrue(tf.is_strictly_increasing([1, 2, 3]).eval())\n\n def test_increasing_rank_two_tensor(self):\n with self.test_session():\n self.assertTrue(tf.is_strictly_increasing([[-1, 2], [3, 4]]).eval())\n\n def test_tensor_with_one_element_is_strictly_increasing(self):\n with self.test_session():\n self.assertTrue(tf.is_strictly_increasing([1]).eval())\n\n def test_empty_tensor_is_strictly_increasing(self):\n with self.test_session():\n self.assertTrue(tf.is_strictly_increasing([]).eval())\n\n\nclass IsNonDecreasingTest(tf.test.TestCase):\n\n def test_constant_tensor_is_non_decreasing(self):\n with self.test_session():\n self.assertTrue(tf.is_non_decreasing([1, 1, 1]).eval())\n\n def test_decreasing_tensor_is_not_non_decreasing(self):\n with self.test_session():\n self.assertFalse(tf.is_non_decreasing([3, 2, 1]).eval())\n\n def test_2d_decreasing_tensor_is_not_non_decreasing(self):\n with self.test_session():\n self.assertFalse(tf.is_non_decreasing([[1, 3], [2, 4]]).eval())\n\n def test_increasing_rank_one_tensor_is_non_decreasing(self):\n with self.test_session():\n self.assertTrue(tf.is_non_decreasing([1, 2, 3]).eval())\n\n def test_increasing_rank_two_tensor(self):\n with self.test_session():\n self.assertTrue(tf.is_non_decreasing([[-1, 2], [3, 3]]).eval())\n\n def test_tensor_with_one_element_is_non_decreasing(self):\n with self.test_session():\n self.assertTrue(tf.is_non_decreasing([1]).eval())\n\n def test_empty_tensor_is_non_decreasing(self):\n with self.test_session():\n self.assertTrue(tf.is_non_decreasing([]).eval())\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for training_coordinator.py.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport glob\nimport os.path\nimport shutil\nimport time\n\nimport tensorflow as tf\nfrom tensorflow.core.util.event_pb2 import SessionLog\n\n\nclass SummaryWriterTestCase(tf.test.TestCase):\n\n def _TestDir(self, test_name):\n test_dir = os.path.join(self.get_temp_dir(), test_name)\n return test_dir\n\n def _CleanTestDir(self, test_name):\n test_dir = self._TestDir(test_name)\n if os.path.exists(test_dir):\n shutil.rmtree(test_dir)\n return test_dir\n\n def _EventsReader(self, test_dir):\n event_paths = glob.glob(os.path.join(test_dir, \"event*\"))\n # If the tests runs multiple times in the same directory we can have\n # more than one matching event file. We only want to read the last one.\n self.assertTrue(event_paths)\n return tf.train.summary_iterator(event_paths[-1])\n\n def _assertRecent(self, t):\n self.assertTrue(abs(t - time.time()) < 5)\n\n def _assertEventsWithGraph(self, test_dir, g, has_shapes):\n rr = self._EventsReader(test_dir)\n\n # The first event should list the file_version.\n ev = next(rr)\n self._assertRecent(ev.wall_time)\n self.assertEquals(\"brain.Event:2\", ev.file_version)\n\n # The next event should have the graph.\n ev = next(rr)\n self._assertRecent(ev.wall_time)\n self.assertEquals(0, ev.step)\n ev_graph = tf.GraphDef()\n ev_graph.ParseFromString(ev.graph_def)\n self.assertProtoEquals(g.as_graph_def(add_shapes=has_shapes), ev_graph)\n\n # We should be done.\n self.assertRaises(StopIteration, lambda: next(rr))\n\n def testAddingSummaryGraphAndRunMetadata(self):\n test_dir = self._CleanTestDir(\"basics\")\n sw = tf.train.SummaryWriter(test_dir)\n\n sw.add_session_log(tf.SessionLog(status=SessionLog.START), 1)\n sw.add_summary(tf.Summary(value=[tf.Summary.Value(tag=\"mee\",\n simple_value=10.0)]),\n 10)\n sw.add_summary(tf.Summary(value=[tf.Summary.Value(tag=\"boo\",\n simple_value=20.0)]),\n 20)\n with tf.Graph().as_default() as g:\n tf.constant([0], name=\"zero\")\n sw.add_graph(g, global_step=30)\n\n run_metadata = tf.RunMetadata()\n device_stats = run_metadata.step_stats.dev_stats.add()\n device_stats.device = \"test\"\n sw.add_run_metadata(run_metadata, \"test run\", global_step=40)\n sw.close()\n rr = self._EventsReader(test_dir)\n\n # The first event should list the file_version.\n ev = next(rr)\n self._assertRecent(ev.wall_time)\n self.assertEquals(\"brain.Event:2\", ev.file_version)\n\n # The next event should be the START message.\n ev = next(rr)\n self._assertRecent(ev.wall_time)\n self.assertEquals(1, ev.step)\n self.assertEquals(SessionLog.START, ev.session_log.status)\n\n # The next event should have the value 'mee=10.0'.\n ev = next(rr)\n self._assertRecent(ev.wall_time)\n self.assertEquals(10, ev.step)\n self.assertProtoEquals(\"\"\"\n value { tag: 'mee' simple_value: 10.0 }\n \"\"\", ev.summary)\n\n # The next event should have the value 'boo=20.0'.\n ev = next(rr)\n self._assertRecent(ev.wall_time)\n self.assertEquals(20, ev.step)\n self.assertProtoEquals(\"\"\"\n value { tag: 'boo' simple_value: 20.0 }\n \"\"\", ev.summary)\n\n # The next event should have the graph_def.\n ev = next(rr)\n self._assertRecent(ev.wall_time)\n self.assertEquals(30, ev.step)\n ev_graph = tf.GraphDef()\n ev_graph.ParseFromString(ev.graph_def)\n self.assertProtoEquals(g.as_graph_def(add_shapes=True), ev_graph)\n\n # The next event should have metadata for the run.\n ev = next(rr)\n self._assertRecent(ev.wall_time)\n self.assertEquals(40, ev.step)\n self.assertEquals(\"test run\", ev.tagged_run_metadata.tag)\n parsed_run_metadata = tf.RunMetadata()\n parsed_run_metadata.ParseFromString(ev.tagged_run_metadata.run_metadata)\n self.assertProtoEquals(run_metadata, parsed_run_metadata)\n\n # We should be done.\n self.assertRaises(StopIteration, lambda: next(rr))\n\n def testGraphAsNamed(self):\n test_dir = self._CleanTestDir(\"basics_named_graph\")\n with tf.Graph().as_default() as g:\n tf.constant([12], name=\"douze\")\n sw = tf.train.SummaryWriter(test_dir, graph=g)\n sw.close()\n self._assertEventsWithGraph(test_dir, g, True)\n\n def testGraphAsPositional(self):\n test_dir = self._CleanTestDir(\"basics_positional_graph\")\n with tf.Graph().as_default() as g:\n tf.constant([12], name=\"douze\")\n sw = tf.train.SummaryWriter(test_dir, g)\n sw.close()\n self._assertEventsWithGraph(test_dir, g, True)\n\n def testGraphDefAsNamed(self):\n test_dir = self._CleanTestDir(\"basics_named_graph_def\")\n with tf.Graph().as_default() as g:\n tf.constant([12], name=\"douze\")\n gd = g.as_graph_def()\n sw = tf.train.SummaryWriter(test_dir, graph_def=gd)\n sw.close()\n self._assertEventsWithGraph(test_dir, g, False)\n\n def testGraphDefAsPositional(self):\n test_dir = self._CleanTestDir(\"basics_positional_graph_def\")\n with tf.Graph().as_default() as g:\n tf.constant([12], name=\"douze\")\n gd = g.as_graph_def()\n sw = tf.train.SummaryWriter(test_dir, gd)\n sw.close()\n self._assertEventsWithGraph(test_dir, g, False)\n\n def testGraphAndGraphDef(self):\n with self.assertRaises(ValueError):\n test_dir = self._CleanTestDir(\"basics_graph_and_graph_def\")\n with tf.Graph().as_default() as g:\n tf.constant([12], name=\"douze\")\n gd = g.as_graph_def()\n sw = tf.train.SummaryWriter(test_dir, graph=g, graph_def=gd)\n sw.close()\n\n def testNeitherGraphNorGraphDef(self):\n with self.assertRaises(TypeError):\n test_dir = self._CleanTestDir(\"basics_string_instead_of_graph\")\n sw = tf.train.SummaryWriter(test_dir, \"string instead of graph object\")\n sw.close()\n\n # Checks that values returned from session Run() calls are added correctly to\n # summaries. These are numpy types so we need to check they fit in the\n # protocol buffers correctly.\n def testAddingSummariesFromSessionRunCalls(self):\n test_dir = self._CleanTestDir(\"global_step\")\n sw = tf.train.SummaryWriter(test_dir)\n with self.test_session():\n i = tf.constant(1, dtype=tf.int32, shape=[])\n l = tf.constant(2, dtype=tf.int64, shape=[])\n # Test the summary can be passed serialized.\n summ = tf.Summary(value=[tf.Summary.Value(tag=\"i\", simple_value=1.0)])\n sw.add_summary(summ.SerializeToString(), i.eval())\n sw.add_summary(tf.Summary(value=[tf.Summary.Value(tag=\"l\",\n simple_value=2.0)]),\n l.eval())\n sw.close()\n\n rr = self._EventsReader(test_dir)\n\n # File_version.\n ev = next(rr)\n self.assertTrue(ev)\n self._assertRecent(ev.wall_time)\n self.assertEquals(\"brain.Event:2\", ev.file_version)\n\n # Summary passed serialized.\n ev = next(rr)\n self.assertTrue(ev)\n self._assertRecent(ev.wall_time)\n self.assertEquals(1, ev.step)\n self.assertProtoEquals(\"\"\"\n value { tag: 'i' simple_value: 1.0 }\n \"\"\", ev.summary)\n\n # Summary passed as SummaryObject.\n ev = next(rr)\n self.assertTrue(ev)\n self._assertRecent(ev.wall_time)\n self.assertEquals(2, ev.step)\n self.assertProtoEquals(\"\"\"\n value { tag: 'l' simple_value: 2.0 }\n \"\"\", ev.summary)\n\n # We should be done.\n self.assertRaises(StopIteration, lambda: next(rr))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for denormal handling.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python.platform import control_imports\n\n\nclass DenormalTest(tf.test.TestCase):\n\n def testPythonHasDenormals(self):\n \"\"\"Non-tf numpy code should treat denormals correctly.\"\"\"\n for dtype in np.float32, np.float64:\n tiny = np.finfo(dtype).tiny\n self.assertEqual(tiny, tiny / 16 * 16)\n\n def _flushDenormalsTest(self, use_gpu, dtypes):\n if control_imports.USE_OSS:\n # TODO(irving): Fix denormal flushing for open source.\n return\n with self.test_session(use_gpu=use_gpu):\n tf.identity(7).eval()\n for dtype in dtypes:\n tiny = np.finfo(dtype).tiny\n # Small shape to test main thread, large shape to test thread pool\n for shape in (), (1<<20,):\n flush = 0.1 * tf.constant(tiny, shape=shape)\n self.assertAllEqual(flush.eval(), np.zeros(shape))\n # Make sure the flags don't leak out\n self.testPythonHasDenormals()\n\n def testFlushDenormalsCPU(self):\n # On CPUs, the processor flags flush for both single and double precision.\n self._flushDenormalsTest(use_gpu=False, dtypes=(np.float32, np.float64))\n\n def testFlushDenormalsGPU(self):\n # On GPUs, only single precision can flush to zero.\n self._flushDenormalsTest(use_gpu=True, dtypes=(np.float32,))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Tests for tensorflow.ops.tensor_array_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import gen_data_flow_ops\nfrom tensorflow.python.ops import tensor_array_grad\nfrom tensorflow.python.ops import tensor_array_ops\n\n\nclass TensorArrayCPUTest(tf.test.TestCase):\n _use_gpu = False\n\n def testTensorArrayWriteRead(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n\n w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [[1.0]])\n w2 = w1.write(2, -3.0)\n\n r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)\n\n d0, d1, d2 = session.run([r0, r1, r2])\n self.assertAllEqual([[4.0, 5.0]], d0)\n self.assertAllEqual([[1.0]], d1)\n self.assertAllEqual(-3.0, d2)\n\n def _testTensorArrayWritePack(self, tf_dtype):\n dtype = tf_dtype.as_numpy_dtype()\n with self.test_session(use_gpu=self._use_gpu):\n ta = tensor_array_ops.TensorArray(\n dtype=tf_dtype, tensor_array_name=\"foo\", size=3)\n\n if tf_dtype == tf.string:\n # In Python3, np.str is unicode, while we always want bytes\n convert = lambda x: np.asarray(x).astype(\"|S\")\n else:\n convert = lambda x: np.asarray(x).astype(dtype)\n\n w0 = ta.write(0, convert([[4.0, 5.0]]))\n w1 = w0.write(1, convert([[6.0, 7.0]]))\n w2 = w1.write(2, convert([[8.0, 9.0]]))\n\n c0 = w2.pack()\n\n self.assertAllEqual(\n convert([[[4.0, 5.0]], [[6.0, 7.0]], [[8.0, 9.0]]]), c0.eval())\n\n def testTensorArrayWritePack(self):\n self._testTensorArrayWritePack(tf.float32)\n self._testTensorArrayWritePack(tf.float64)\n self._testTensorArrayWritePack(tf.int32)\n self._testTensorArrayWritePack(tf.int64)\n self._testTensorArrayWritePack(tf.complex64)\n self._testTensorArrayWritePack(tf.complex128)\n self._testTensorArrayWritePack(tf.string)\n\n def _testTensorArrayWriteConcat(self, tf_dtype):\n dtype = tf_dtype.as_numpy_dtype()\n with self.test_session(use_gpu=self._use_gpu):\n ta = tensor_array_ops.TensorArray(\n dtype=tf_dtype, tensor_array_name=\"foo\", size=3)\n\n if tf_dtype == tf.string:\n # In Python3, np.str is unicode, while we always want bytes\n convert = lambda x: np.asarray(x).astype(\"|S\")\n else:\n convert = lambda x: np.asarray(x).astype(dtype)\n\n w0 = ta.write(0, convert([[4.0, 5.0], [104.0, 105.0], [204.0, 205.0]]))\n w1 = w0.write(1, convert([[6.0, 7.0], [106.0, 107.0]]))\n w2 = w1.write(2, convert([[8.0, 9.0]]))\n\n c0 = w2.concat()\n\n self.assertAllEqual(\n convert([[4.0, 5.0],\n [104.0, 105.0],\n [204.0, 205.0],\n [6.0, 7.0],\n [106.0, 107.0],\n [8.0, 9.0]]), c0.eval())\n\n def testTensorArrayWriteConcat(self):\n self._testTensorArrayWriteConcat(tf.float32)\n self._testTensorArrayWriteConcat(tf.float64)\n self._testTensorArrayWriteConcat(tf.int32)\n self._testTensorArrayWriteConcat(tf.int64)\n self._testTensorArrayWriteConcat(tf.complex64)\n self._testTensorArrayWriteConcat(tf.complex128)\n self._testTensorArrayWriteConcat(tf.string)\n\n def testTensorArrayUnpackWrongMajorSizeFails(self):\n with self.test_session():\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n\n with self.assertRaisesOpError(\n r\"Input value must have first dimension \"\n r\"equal to the array size \\(2 vs. 3\\)\"):\n ta.unpack([1.0, 2.0]).flow.eval()\n\n def testTensorArrayPackNotAllValuesAvailableFails(self):\n with self.test_session():\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n\n with self.assertRaisesOpError(\n \"Could not read from TensorArray index 1 \"\n \"because it has not yet been written to.\"):\n ta.write(0, [[4.0, 5.0]]).pack().eval()\n\n def _testTensorArrayUnpackRead(self, tf_dtype):\n dtype = tf_dtype.as_numpy_dtype()\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf_dtype, tensor_array_name=\"foo\", size=3)\n\n if tf_dtype is tf.string:\n # In Python3, np.str is unicode, while we always want bytes\n convert = lambda x: np.asarray(x).astype(\"|S\")\n else:\n convert = lambda x: np.asarray(x).astype(dtype)\n\n # Unpack a vector into scalars\n w0 = ta.unpack(convert([1.0, 2.0, 3.0]))\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)\n\n d0, d1, d2 = session.run([r0, r1, r2])\n self.assertAllEqual(convert(1.0), d0)\n self.assertAllEqual(convert(2.0), d1)\n self.assertAllEqual(convert(3.0), d2)\n\n # Unpack a matrix into vectors\n w1 = ta.unpack(convert([[1.0, 1.1], [2.0, 2.1], [3.0, 3.1]]))\n r0 = w1.read(0)\n r1 = w1.read(1)\n r2 = w1.read(2)\n\n d0, d1, d2 = session.run([r0, r1, r2])\n self.assertAllEqual(convert([1.0, 1.1]), d0)\n self.assertAllEqual(convert([2.0, 2.1]), d1)\n self.assertAllEqual(convert([3.0, 3.1]), d2)\n\n def testTensorArrayUnpackRead(self):\n self._testTensorArrayUnpackRead(tf.float32)\n self._testTensorArrayUnpackRead(tf.float64)\n self._testTensorArrayUnpackRead(tf.int32)\n self._testTensorArrayUnpackRead(tf.int64)\n self._testTensorArrayUnpackRead(tf.complex64)\n self._testTensorArrayUnpackRead(tf.complex128)\n self._testTensorArrayUnpackRead(tf.string)\n\n def _testTensorArraySplitRead(self, tf_dtype):\n dtype = tf_dtype.as_numpy_dtype()\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf_dtype, tensor_array_name=\"foo\", size=3)\n\n if tf_dtype == tf.string:\n # In Python3, np.str is unicode, while we always want bytes\n convert = lambda x: np.asarray(x).astype(\"|S\")\n else:\n convert = lambda x: np.asarray(x).astype(dtype)\n\n # Split an empty vector\n lengths = tf.constant([0, 0, 0])\n w0 = ta.split(convert([]), lengths=lengths)\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)\n\n d0, d1, d2 = session.run([r0, r1, r2])\n self.assertAllEqual(convert([]), d0)\n self.assertAllEqual(convert([]), d1)\n self.assertAllEqual(convert([]), d2)\n\n # Split a vector\n lengths = tf.constant([2, 0, 1])\n w0 = ta.split(\n convert([1.0, 2.0, 3.0]), lengths=lengths)\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)\n\n d0, d1, d2 = session.run([r0, r1, r2])\n self.assertAllEqual(convert([1.0, 2.0]), d0)\n self.assertAllEqual(convert([]), d1)\n self.assertAllEqual(convert([3.0]), d2)\n\n # Split a matrix\n lengths = tf.constant([2, 0, 1])\n w0 = ta.split(\n convert([[1.0, 101.0], [2.0, 201.0], [3.0, 301.0]]), lengths=lengths)\n r0 = w0.read(0)\n r1 = w0.read(1)\n r2 = w0.read(2)\n\n d0, d1, d2 = session.run([r0, r1, r2])\n self.assertAllEqual(convert([[1.0, 101.0], [2.0, 201.0]]), d0)\n self.assertAllEqual(convert([]).reshape(0, 2), d1)\n self.assertAllEqual(convert([[3.0, 301.0]]), d2)\n\n def testTensorArraySplitRead(self):\n self._testTensorArraySplitRead(tf.float32)\n self._testTensorArraySplitRead(tf.float64)\n self._testTensorArraySplitRead(tf.int32)\n self._testTensorArraySplitRead(tf.int64)\n self._testTensorArraySplitRead(tf.complex64)\n self._testTensorArraySplitRead(tf.complex128)\n self._testTensorArraySplitRead(tf.string)\n\n def testTensorGradArrayWriteRead(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n g_ta = ta.grad(\"grad\")\n\n w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [[1.0]])\n w2 = w1.write(2, -3.0)\n\n g_w0 = g_ta.write(0, [[5.0, 6.0]])\n g_w1 = g_w0.write(1, [[2.0]])\n g_w2 = g_w1.write(2, -2.0)\n\n r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)\n\n g_r0 = g_w2.read(0)\n g_r1 = g_w2.read(1)\n g_r2 = g_w2.read(2)\n\n d0, d1, d2, g_d0, g_d1, g_d2 = session.run([r0, r1, r2, g_r0, g_r1, g_r2])\n self.assertAllEqual([[4.0, 5.0]], d0)\n self.assertAllEqual([[1.0]], d1)\n self.assertAllEqual(-3.0, d2)\n self.assertAllEqual([[5.0, 6.0]], g_d0)\n self.assertAllEqual([[2.0]], g_d1)\n self.assertAllEqual(-2.0, g_d2)\n\n def testTensorGradArrayDynamicWriteRead(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=0, dynamic_size=True)\n\n w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [[1.0]])\n w2 = w1.write(2, -3.0)\n\n g_ta = w2.grad(\"grad\") # Get gradient array here so we know the shape\n\n s = w2.size()\n g_s = g_ta.size()\n\n g_w0 = g_ta.write(0, [[5.0, 6.0]])\n g_w1 = g_w0.write(1, [[2.0]])\n g_w2 = g_w1.write(2, -2.0)\n\n r0 = w2.read(0)\n r1 = w2.read(1)\n r2 = w2.read(2)\n\n g_r0 = g_w2.read(0)\n g_r1 = g_w2.read(1)\n g_r2 = g_w2.read(2)\n\n d0, d1, d2, g_d0, g_d1, g_d2, vs, g_vs = session.run([\n r0, r1, r2, g_r0, g_r1, g_r2, s, g_s])\n self.assertAllEqual([[4.0, 5.0]], d0)\n self.assertAllEqual([[1.0]], d1)\n self.assertAllEqual(-3.0, d2)\n self.assertAllEqual([[5.0, 6.0]], g_d0)\n self.assertAllEqual([[2.0]], g_d1)\n self.assertAllEqual(-2.0, g_d2)\n self.assertAllEqual(3, vs)\n self.assertAllEqual(3, g_vs)\n\n def testTensorGradAccessTwiceReceiveSameObject(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n g_ta_0 = ta.grad(\"grad\")\n g_ta_1 = ta.grad(\"grad\")\n\n with tf.control_dependencies([g_ta_0.write(0, [[4.0, 5.0]]).flow]):\n # Write with one gradient handle, read with another copy of it\n r1_0 = g_ta_1.read(0)\n\n t_g_ta_0, t_g_ta_1, d_r1_0 = session.run(\n [g_ta_0.handle, g_ta_1.handle, r1_0])\n self.assertAllEqual(t_g_ta_0, t_g_ta_1)\n self.assertAllEqual([[4.0, 5.0]], d_r1_0)\n\n def testTensorArrayWriteWrongIndexOrDataTypeFails(self):\n with self.test_session(use_gpu=self._use_gpu):\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n\n # Test writing the wrong datatype\n with self.assertRaisesOpError(\n \"TensorArray dtype is float but Op is trying to write dtype string\"):\n ta.write(-1, \"wrong_type_scalar\").flow.eval()\n\n # Test writing to a negative index\n with self.assertRaisesOpError(\n \"Tried to write to index -1 but array is not \"\n \"resizeable and size is: 3\"):\n ta.write(-1, 3.0).flow.eval()\n\n # Test reading from too large an index\n with self.assertRaisesOpError(\n \"Tried to write to index 3 but array is not \"\n \"resizeable and size is: 3\"):\n ta.write(3, 3.0).flow.eval()\n\n def testTensorArrayReadWrongIndexOrDataTypeFails(self):\n with self.test_session(use_gpu=self._use_gpu):\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n\n w0 = ta.write(0, [[4.0, 5.0]])\n\n # Test reading wrong datatype\n r0_bad = gen_data_flow_ops._tensor_array_read(\n handle=w0.handle, index=0, dtype=tf.int64, flow_in=w0.flow)\n with self.assertRaisesOpError(\n \"TensorArray dtype is float but Op requested dtype int64.\"):\n r0_bad.eval()\n\n # Test reading from a different index than the one we wrote to\n r1 = w0.read(1)\n with self.assertRaisesOpError(\n \"Could not read from TensorArray index 1 because \"\n \"it has not yet been written to.\"):\n r1.eval()\n\n # Test reading from a negative index\n with self.assertRaisesOpError(\n r\"Tried to read from index -1 but array size is: 3\"):\n ta.read(-1).eval()\n\n # Test reading from too large an index\n with self.assertRaisesOpError(\n \"Tried to read from index 3 but array size is: 3\"):\n ta.read(3).eval()\n\n def testTensorArrayWriteMultipleFails(self):\n with self.test_session(use_gpu=self._use_gpu):\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n\n with self.assertRaisesOpError(\n \"Could not write to TensorArray index 2 because \"\n \"it has already been written to.\"):\n ta.write(2, 3.0).write(2, 3.0).flow.eval()\n\n def testTensorArrayConcatIncompatibleShapesFails(self):\n with self.test_session(use_gpu=self._use_gpu):\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n\n w1 = ta.write(0, 3.0)\n w2 = w1.write(1, 4.0)\n w3 = w2.write(2, [3.0])\n\n with self.assertRaisesOpError(\n \"Concat saw a scalar shape at index 0 but requires at least vectors\"):\n w3.concat().eval()\n\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n\n w1 = ta.write(0, [3.0])\n w2 = w1.write(1, [4.0])\n w3 = w2.write(2, [[3.0]])\n\n with self.assertRaisesOpError(\n r\"TensorArray has inconsistent shapes. Index 0 has \"\n r\"\\(excepting dimension 0\\) shape: \\[\\] but index 2 has \\(excepting \"\n r\"dimension 0\\) shape: \\[1\\]\"):\n w3.concat().eval()\n\n def testTensorArraySplitIncompatibleShapesFails(self):\n with self.test_session(use_gpu=self._use_gpu):\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n\n with self.assertRaisesOpError(\n r\"Expected lengths to be a vector, received shape: \\[\\]\"):\n lengths = tf.placeholder(tf.int64)\n ta.split([1.0, 2.0, 3.0], lengths).flow.eval(feed_dict={lengths: 1})\n\n with self.assertRaisesOpError(\n r\"Expected sum of lengths to be equal to values.shape\\[0\\], \"\n r\"but sum of lengths is 1 and value's shape is: \\[3\\]\"):\n ta.split([1.0, 2.0, 3.0], [1]).flow.eval()\n\n with self.assertRaisesOpError(\n r\"Expected value to be at least a vector, but received shape: \\[\\]\"):\n ta.split(1.0, [1]).flow.eval()\n\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=2)\n\n with self.assertRaisesOpError(\n r\"TensorArray's size is not equal to the size of lengths \"\n r\"\\(2 vs. 1\\), and the TensorArray is not marked as \"\n r\"dynamically resizeable\"):\n ta.split([1.0], [1]).flow.eval()\n\n def _testTensorArrayWriteGradientAddMultipleAdds(self, dtype):\n with self.test_session(use_gpu=self._use_gpu):\n ta = tensor_array_ops.TensorArray(\n dtype=dtype, tensor_array_name=\"foo\", size=3)\n ta_grad = ta.grad(\"grad\")\n\n c = lambda x: np.asarray(x, dtype=dtype.as_numpy_dtype)\n\n w0 = ta.write(2, c(3.0))\n w1 = w0.write(2, c(4.0))\n\n w0_grad = ta_grad.write(2, c(3.0))\n w1_grad = w0_grad.write(2, c(4.0))\n w2_grad = w1_grad.write(2, c(5.0))\n\n # Assert that aggregation works correctly\n self.assertAllEqual(c(12.00), w2_grad.read(2).eval())\n\n # Assert that if multiple_writes_aggregate is not enabled,\n # multiple writes raise an exception.\n with self.assertRaisesOpError(\n r\"TensorArray foo: Could not write to TensorArray index 2 because \"\n r\"it has already been written to.\"):\n w1.flow.eval()\n\n # Using differing shapes causes an exception\n wb0_grad = ta_grad.write(1, c(1.0))\n wb1_grad = wb0_grad.write(1, c([1.0]))\n\n with self.assertRaisesOpError(\n r\"Could not aggregate to TensorArray index 1 because the \"\n r\"existing shape is \\[\\] but the new input shape is \\[1\\]\"):\n wb1_grad.flow.eval()\n\n def testTensorArrayWriteGradientAddMultipleAdds(self):\n for dtype in (tf.int32, tf.int64, tf.float32,\n tf.float64, tf.complex64, tf.complex128):\n self._testTensorArrayWriteGradientAddMultipleAdds(dtype)\n\n def testMultiTensorArray(self):\n with self.test_session(use_gpu=self._use_gpu):\n h1 = tensor_array_ops.TensorArray(\n size=1, dtype=tf.float32, tensor_array_name=\"foo\")\n w1 = h1.write(0, 4.0)\n r1 = w1.read(0)\n\n h2 = tensor_array_ops.TensorArray(\n size=1, dtype=tf.float32, tensor_array_name=\"bar\")\n\n w2 = h2.write(0, 5.0)\n r2 = w2.read(0)\n r = r1 + r2\n self.assertAllClose(9.0, r.eval())\n\n def testDuplicateTensorArrayFails(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n h1 = tensor_array_ops.TensorArray(\n size=1, dtype=tf.float32, tensor_array_name=\"foo\")\n c1 = h1.write(0, 4.0)\n h2 = tensor_array_ops.TensorArray(\n size=1, dtype=tf.float32, tensor_array_name=\"foo\")\n c2 = h2.write(0, 5.0)\n with self.assertRaises(errors.AlreadyExistsError):\n session.run([c1.flow, c2.flow])\n\n def _testTensorArrayGradientWriteReadType(self, dtype):\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf.as_dtype(dtype), tensor_array_name=\"foo\", size=3)\n\n c = lambda x: np.array(x, dtype=dtype)\n\n value_0 = tf.constant(c([[4.0, 5.0]]))\n value_1 = tf.constant(c(3.0))\n\n w0 = ta.write(0, value_0)\n w1 = w0.write(1, value_1)\n r0 = w1.read(0)\n r1 = w1.read(1)\n r0_2 = w1.read(0)\n\n # Test individual components' gradients\n grad_just_r0 = tf.gradients(\n ys=[r0], xs=[value_0], grad_ys=[c([[2.0, 3.0]])])\n grad_just_r0_vals = session.run(grad_just_r0)\n self.assertAllEqual(c([[2.0, 3.0]]), grad_just_r0_vals[0])\n\n grad_r0_r0_2 = tf.gradients(\n ys=[r0, r0_2], xs=[value_0],\n grad_ys=[c([[2.0, 3.0]]), c([[1.0, -1.0]])])\n grad_r0_r0_2_vals = session.run(grad_r0_r0_2)\n self.assertAllEqual(c([[3.0, 2.0]]), grad_r0_r0_2_vals[0])\n\n grad_just_r1 = tf.gradients(\n ys=[r1], xs=[value_1], grad_ys=[c(-2.0)])\n grad_just_r1_vals = session.run(grad_just_r1)\n self.assertAllEqual(c(-2.0), grad_just_r1_vals[0])\n\n # Test combined gradients\n grad = tf.gradients(\n ys=[r0, r0_2, r1], xs=[value_0, value_1],\n grad_ys=[c([[2.0, 3.0]]), c([[1.0, -1.0]]), c(-2.0)])\n grad_vals = session.run(grad)\n self.assertEqual(len(grad_vals), 2)\n self.assertAllEqual(c([[3.0, 2.0]]), grad_vals[0])\n self.assertAllEqual(c(-2.0), grad_vals[1])\n\n def testTensorArrayGradientWriteRead(self):\n for dtype in (np.float32, np.float64, np.int32,\n np.int64, np.complex64, np.complex128):\n self._testTensorArrayGradientWriteReadType(dtype)\n\n def testTensorArrayGradientWritePackConcatAndRead(self):\n with self.test_session(use_gpu=self._use_gpu) as sess:\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=2,\n clear_after_read=False)\n\n value_0 = tf.constant([-1.0, 1.0])\n value_1 = tf.constant([-10.0, 10.0])\n\n w0 = ta.write(0, value_0)\n w1 = w0.write(1, value_1)\n p0 = w1.pack()\n r0 = w1.read(0)\n s0 = w1.concat()\n\n # Test gradient accumulation between read(0), pack(), and concat()\n with tf.control_dependencies([p0, r0, s0]):\n grad_r = tf.gradients(\n ys=[p0, r0, s0], xs=[value_0, value_1],\n grad_ys=[\n [[2.0, 3.0], [4.0, 5.0]], # pack gradient\n [-0.5, 1.5], # read(0) gradient\n [20.0, 30.0, 40.0, 50.0]]) # concat gradient\n grad_vals = sess.run(grad_r) # 2 + 2 entries\n\n self.assertAllClose([2.0 - 0.5 + 20.0, 3.0 + 1.5 + 30.0], grad_vals[0])\n self.assertAllEqual([4.0 + 40.0, 5.0 + 50.0], grad_vals[1])\n\n def testTensorArrayReadTwice(self):\n with self.test_session(use_gpu=self._use_gpu):\n value = tf.constant([[1.0, -1.0], [10.0, -10.0]])\n\n ta_readonce = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=2)\n\n w_readonce = ta_readonce.unpack(value)\n r0_readonce = w_readonce.read(0)\n with tf.control_dependencies([r0_readonce]):\n r1_readonce = w_readonce.read(0)\n\n with self.assertRaisesOpError(\n r\"Could not read index 0 twice because it was cleared after a \"\n r\"previous read \\(perhaps try setting clear_after_read = false\\?\\)\"):\n r1_readonce.eval()\n\n ta_readtwice = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=2,\n clear_after_read=False)\n w_readtwice = ta_readtwice.unpack(value)\n r0_readtwice = w_readtwice.read(0)\n with tf.control_dependencies([r0_readtwice]):\n r1_readtwice = w_readtwice.read(0)\n\n self.assertAllEqual([1.0, -1.0], r1_readtwice.eval())\n\n def testTensorArrayGradientUnpackRead(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=2,\n clear_after_read=False)\n\n value = tf.constant([[1.0, -1.0], [10.0, -10.0]])\n\n w = ta.unpack(value)\n r0 = w.read(0)\n r0_1 = w.read(0)\n r1 = w.read(1)\n\n # Test combined gradients + aggregation of read(0)\n grad = tf.gradients(\n ys=[r0, r0_1, r1], xs=[value],\n grad_ys=[[2.0, 3.0], [-1.5, 1.5], [4.0, 5.0]])\n grad_vals = session.run(grad)\n\n self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([[2.0 - 1.5, 3.0 + 1.5], [4.0, 5.0]], grad_vals[0])\n\n def testTensorArrayGradientSplitConcat(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=2)\n\n value = tf.constant([[1.0, -1.0], [10.0, -10.0], [100.0, -100.0]])\n\n w = ta.split(value, [2, 1])\n r = w.concat()\n\n # Test combined gradients\n grad = tf.gradients(\n ys=[r], xs=[value],\n grad_ys=[[[2.0, -2.0], [20.0, -20.0], [200.0, -200.0]]])\n grad_vals = session.run(grad)\n\n self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual(\n [[2.0, -2.0], [20.0, -20.0], [200.0, -200.0]], grad_vals[0])\n\n def testTensorArrayGradientDynamicUnpackRead(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=0, dynamic_size=True)\n\n value = tf.constant([[1.0, -1.0], [10.0, -10.0]])\n\n w = ta.unpack(value)\n r0 = w.read(0)\n r1 = w.read(1)\n\n # Test combined gradients + aggregation of read(0)\n grad = tf.gradients(\n ys=[r0, r1], xs=[value], grad_ys=[[2.0, 3.0], [4.0, 5.0]])\n grad_vals = session.run(grad)\n\n self.assertEqual(len(grad_vals), 1)\n self.assertAllEqual([[2.0, 3.0], [4.0, 5.0]], grad_vals[0])\n\n def testCloseTensorArray(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n c1 = ta.close()\n session.run(c1)\n\n def testSizeTensorArray(self):\n with self.test_session(use_gpu=self._use_gpu):\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n s = ta.size()\n self.assertAllEqual(3, s.eval())\n\n def testWriteCloseTensorArray(self):\n with self.test_session(use_gpu=self._use_gpu):\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3)\n w0 = ta.write(0, [[4.0, 5.0]])\n w1 = w0.write(1, [3.0])\n w1.close().run() # Expected to run without problems\n\n with self.assertRaisesOpError(\n r\"TensorArray foo has already been closed.\"):\n with tf.control_dependencies([w1.close()]):\n w1.write(2, 3.0).flow.eval()\n\n def _testWhileLoopWritePackGradients(self, dynamic_size, dtype):\n np_dtype = dtype.as_numpy_dtype\n with self.test_session(use_gpu=self._use_gpu) as session:\n v0 = tf.identity(np.arange(3*5, dtype=np_dtype).reshape(3, 5))\n var = tf.Variable(np.arange(100, 105, dtype=np_dtype))\n state0 = tf.identity(np.array([1] * 5, dtype=np_dtype))\n ta = tensor_array_ops.TensorArray(\n dtype=dtype, tensor_array_name=\"foo\",\n size=0 if dynamic_size else 3, dynamic_size=dynamic_size)\n time_0 = tf.identity(0)\n\n def body(time, ta_t, state):\n sliced = tf.slice(v0, begin=tf.pack([time, 0]), size=[1, -1])\n sliced = tf.squeeze(sliced)\n out = sliced + var + state\n state += sliced\n ta_t = ta_t.write(time, out)\n return (time+1, ta_t, state)\n\n (unused_0, h_final, unused_2) = tf.while_loop(\n cond=lambda time, unused_1, unused_2: time < 3,\n body=body,\n loop_vars=(time_0, ta, state0),\n parallel_iterations=3)\n vout = h_final.pack()\n\n grad_val = -np.arange(3*5, dtype=np_dtype).reshape(3, 5)\n v0_grad = tf.gradients([vout], [v0], [grad_val])[0]\n state0_grad = tf.gradients([vout], [state0], [grad_val])[0]\n var_grad = tf.gradients([vout], [var], [grad_val])[0]\n\n tf.initialize_all_variables().run()\n state0_t, var_t, v0_t, vout_t, v0_grad_t, var_grad_t, state0_grad_t = (\n session.run([state0, var, v0, vout, v0_grad, var_grad, state0_grad]))\n just_v0_grad_t, = session.run([v0_grad])\n\n # state = [ state0 | state0 + v0[0] | state0 + v0[0] + v0[1] ]\n # vout = [ v0[0] + var + state[0] |\n # v0[1] + var + state[1] |\n # v0[2] + var + state[2] ]\n # = [ v0[0] + var + state0 |\n # v0[1] + var + state0 + v0[0] |\n # v0[2] + var + state0 + v0[0] + v0[1] ]\n #\n # d(vout[0])/d(v0) = [1 | 0 | 0 ]\n # d(vout[1])/d(v0) = [1 | 1 | 0 ]\n # d(vout[2])/d(v0) = [1 | 1 | 1 ]\n # d(vout)/d(var) = [1 | 1 | 1]\n # d(vout)/d(state0) = [ 1 | 1 | 1 ]\n\n state_per_time = np.array([\n state0_t,\n state0_t + v0_t[0, :],\n state0_t + v0_t[0, :] + v0_t[1, :]])\n\n # Compare forward prop\n self.assertAllClose(v0_t + var_t + state_per_time, vout_t)\n\n # Compare backward prop\n expected_v0_grad_t = np.array([\n grad_val[0, :] + grad_val[1, :] + grad_val[2, :],\n grad_val[1, :] + grad_val[2, :],\n grad_val[2, :]])\n\n self.assertAllEqual(expected_v0_grad_t, v0_grad_t)\n self.assertAllEqual(expected_v0_grad_t, just_v0_grad_t)\n self.assertAllClose(grad_val.sum(axis=0), var_grad_t)\n self.assertAllClose(grad_val.sum(axis=0), state0_grad_t)\n\n def testWhileLoopWritePackGradients(self):\n self._testWhileLoopWritePackGradients(\n dynamic_size=False, dtype=tf.float32)\n # TODO(ebrevdo): re-enable when While supports non-float32 gradients.\n # self._testWhileLoopWritePackGradients(\n # dynamic_size=False, dtype=tf.int64)\n\n def testWhileLoopDynamicWritePackGradients(self):\n self._testWhileLoopWritePackGradients(\n dynamic_size=True, dtype=tf.float32)\n\n def testSumOfTwoReadVariablesWithoutRepeatGrad(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n a = tf.identity(np.arange(3*5, dtype=np.float32).reshape(3, 5) + 1)\n b = tf.identity(np.arange(3*5, dtype=np.float32).reshape(3, 5) + 1 + 3*5)\n ta = tensor_array_ops.TensorArray(dtype=tf.float32, size=2)\n ta = ta.write(0, a, name=\"write_a\")\n ta = ta.write(1, b, name=\"write_b\")\n c = (ta.read(0, name=\"read_a_0\") + # a + b\n ta.read(1, name=\"read_b_0\"))\n g0 = -(np.arange(3*5, dtype=np.float32).reshape(3, 5) + 1)\n grad_a = tf.gradients([c], [a], [g0])[0] # d(a+b)/da = 1\n grad_b = tf.gradients([c], [b], [g0])[0] # d(a+b)/db = 1\n\n # Test gradients calculated individually\n grad_a_t, = session.run([grad_a])\n self.assertAllEqual(grad_a_t, g0)\n\n grad_b_t, = session.run([grad_b])\n self.assertAllEqual(grad_b_t, g0)\n\n # Test gradients calculated jointly\n joint_grad_a_t, joint_grad_b_t = session.run([grad_a, grad_b])\n self.assertAllEqual(joint_grad_a_t, g0)\n self.assertAllEqual(joint_grad_b_t, g0)\n\n def _grad_source_for_name(self, name):\n return tensor_array_grad._GetGradSource(tf.constant(0, name=name))\n\n def testGetGradSource_Invalid(self):\n with self.assertRaises(ValueError):\n self._grad_source_for_name(\"\")\n with self.assertRaises(ValueError):\n self._grad_source_for_name(\"foo\")\n with self.assertRaises(ValueError):\n self._grad_source_for_name(\"foo/bar\")\n\n def testGetGradSource_NoEnclosingScope(self):\n self.assertEqual(\"gradients:0\", self._grad_source_for_name(\"gradients\"))\n self.assertEqual(\"gradients_0:0\", self._grad_source_for_name(\"gradients_0\"))\n self.assertEqual(\"gradients\", self._grad_source_for_name(\"gradients/foo\"))\n self.assertEqual(\n \"gradients_0\", self._grad_source_for_name(\"gradients_0/foo\"))\n self.assertEqual(\n \"gradients\", self._grad_source_for_name(\"gradients/foo/bar\"))\n self.assertEqual(\n \"gradients_0\", self._grad_source_for_name(\"gradients_0/foo/bar\"))\n\n def testGetGradSource_EnclosingScope(self):\n self.assertEqual(\n \"foo/gradients:0\", self._grad_source_for_name(\"foo/gradients\"))\n self.assertEqual(\n \"foo/gradients_0:0\", self._grad_source_for_name(\"foo/gradients_0\"))\n self.assertEqual(\n \"foo/gradients\", self._grad_source_for_name(\"foo/gradients/bar\"))\n self.assertEqual(\n \"foo/gradients_0\", self._grad_source_for_name(\"foo/gradients_0/bar\"))\n self.assertEqual(\n \"foo/bar/gradients\",\n self._grad_source_for_name(\"foo/bar/gradients/baz\"))\n self.assertEqual(\n \"foo/bar/gradients_0\",\n self._grad_source_for_name(\"foo/bar/gradients_0/baz\"))\n\n def testGetGradSource_NestedUsesInnermost(self):\n self.assertEqual(\n \"foo/gradients/bar/gradients_0\",\n self._grad_source_for_name(\"foo/gradients/bar/gradients_0/baz\"))\n\n def testWriteShape(self):\n with self.test_session():\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3, infer_shape=True)\n c0 = tf.constant([4.0, 5.0])\n w0 = ta.write(0, c0)\n r0 = w0.read(0)\n self.assertAllEqual(c0.get_shape(), r0.get_shape())\n\n c1 = tf.constant([6.0, 7.0])\n w1 = w0.write(1, c1)\n r0 = w1.read(0)\n r1 = w1.read(1)\n self.assertAllEqual(c0.get_shape(), r0.get_shape())\n self.assertAllEqual(c1.get_shape(), r1.get_shape())\n\n c2 = tf.constant([4.0, 5.0, 6.0])\n with self.assertRaises(ValueError):\n w0.write(0, c2)\n\n def testUnpackShape(self):\n with self.test_session():\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\",\n size=0, dynamic_size=True, infer_shape=True)\n value = tf.constant([[1.0, -1.0], [10.0, -10.0], [100.0, -100.0]])\n w0 = ta.unpack(value)\n r0 = w0.read(0)\n self.assertAllEqual((2,), r0.get_shape())\n\n c1 = tf.constant([4.0, 5.0])\n w1 = w0.write(3, c1)\n r1 = w1.read(0)\n self.assertAllEqual(c1.get_shape(), r1.get_shape())\n\n c2 = tf.constant([4.0, 5.0, 6.0])\n with self.assertRaises(ValueError):\n w1.write(4, c2)\n\n def testSplitShape(self):\n with self.test_session():\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\",\n size=0, dynamic_size=True, infer_shape=True)\n value = tf.constant([[1.0, -1.0], [2.0, -2.0], [3.0, -3.0]])\n w0 = ta.split(value, [1, 1, 1])\n r0 = w0.read(0)\n self.assertAllEqual((1, 2), r0.get_shape())\n\n ta1 = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo1\",\n size=0, dynamic_size=True, infer_shape=True)\n w0 = ta1.split(value, [1, 2])\n r0 = w0.read(0)\n self.assertAllEqual(r0.get_shape(), tensor_shape.unknown_shape())\n\n def testWriteUnknownShape(self):\n with self.test_session():\n ta = tensor_array_ops.TensorArray(\n dtype=tf.float32, tensor_array_name=\"foo\", size=3, infer_shape=True)\n c0 = tf.placeholder(tf.float32)\n w0 = ta.write(0, c0)\n r0 = w0.read(0)\n self.assertAllEqual(r0.get_shape(), tensor_shape.unknown_shape())\n\n def testGradientWhenNotAllComponentsRead(self):\n with self.test_session(use_gpu=self._use_gpu) as session:\n ta = tensor_array_ops.TensorArray(dtype=tf.float32, size=2)\n x = tf.constant([2.0, 3.0])\n w = ta.unpack(x)\n r0 = w.read(0)\n # calculate (dr0/dx0, dr0/dx1). since r0 = x0, gradients are (1, 0).\n grad_r0 = tf.gradients(ys=[r0], xs=[x], grad_ys=[1.0])\n grad_r0_vals = session.run(grad_r0)[0]\n self.assertAllEqual(grad_r0_vals, [1.0, 0.0])\n\n\nclass TensorArrayGPUTest(TensorArrayCPUTest):\n _use_gpu = True\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This example builds deep residual network for mnist data.\n\nReference Paper: http://arxiv.org/pdf/1512.03385.pdf\n\nNote that this is still a work-in-progress. Feel free to submit a PR\nto make this better.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import namedtuple\nfrom math import sqrt\nimport os\n\nfrom sklearn import metrics\nimport tensorflow as tf\nfrom tensorflow.contrib import learn\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\ndef res_net(x, y, activation=tf.nn.relu):\n \"\"\"Builds a residual network.\n\n Note that if the input tensor is 2D, it must be square in order to be\n converted to a 4D tensor.\n\n Borrowed structure from:\n github.com/pkmital/tensorflow_tutorials/blob/master/10_residual_network.py\n\n Args:\n x: Input of the network\n y: Output of the network\n activation: Activation function to apply after each convolution\n\n Returns:\n Predictions and loss tensors.\n \"\"\"\n\n # Configurations for each bottleneck block.\n BottleneckBlock = namedtuple(\n 'BottleneckBlock', ['num_layers', 'num_filters', 'bottleneck_size'])\n blocks = [BottleneckBlock(3, 128, 32),\n BottleneckBlock(3, 256, 64),\n BottleneckBlock(3, 512, 128),\n BottleneckBlock(3, 1024, 256)]\n\n input_shape = x.get_shape().as_list()\n\n # Reshape the input into the right shape if it's 2D tensor\n if len(input_shape) == 2:\n ndim = int(sqrt(input_shape[1]))\n x = tf.reshape(x, [-1, ndim, ndim, 1])\n\n # First convolution expands to 64 channels\n with tf.variable_scope('conv_layer1'):\n net = learn.ops.conv2d(x, 64, [7, 7], batch_norm=True,\n activation=activation, bias=False)\n\n # Max pool\n net = tf.nn.max_pool(\n net, [1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')\n\n # First chain of resnets\n with tf.variable_scope('conv_layer2'):\n net = learn.ops.conv2d(net, blocks[0].num_filters,\n [1, 1], [1, 1, 1, 1],\n padding='VALID', bias=True)\n\n # Create each bottleneck building block for each layer\n for block_i, block in enumerate(blocks):\n for layer_i in range(block.num_layers):\n\n name = 'block_%d/layer_%d' % (block_i, layer_i)\n\n # 1x1 convolution responsible for reducing dimension\n with tf.variable_scope(name + '/conv_in'):\n conv = learn.ops.conv2d(net, block.bottleneck_size,\n [1, 1], [1, 1, 1, 1],\n padding='VALID',\n activation=activation,\n batch_norm=True,\n bias=False)\n\n with tf.variable_scope(name + '/conv_bottleneck'):\n conv = learn.ops.conv2d(conv, block.bottleneck_size,\n [3, 3], [1, 1, 1, 1],\n padding='SAME',\n activation=activation,\n batch_norm=True,\n bias=False)\n\n # 1x1 convolution responsible for restoring dimension\n with tf.variable_scope(name + '/conv_out'):\n conv = learn.ops.conv2d(conv, block.num_filters,\n [1, 1], [1, 1, 1, 1],\n padding='VALID',\n activation=activation,\n batch_norm=True,\n bias=False)\n\n # shortcut connections that turn the network into its counterpart\n # residual function (identity shortcut)\n net = conv + net\n\n try:\n # upscale to the next block size\n next_block = blocks[block_i + 1]\n with tf.variable_scope('block_%d/conv_upscale' % block_i):\n net = learn.ops.conv2d(net, next_block.num_filters,\n [1, 1], [1, 1, 1, 1],\n bias=False,\n padding='SAME')\n except IndexError:\n pass\n\n net_shape = net.get_shape().as_list()\n net = tf.nn.avg_pool(net,\n ksize=[1, net_shape[1], net_shape[2], 1],\n strides=[1, 1, 1, 1], padding='VALID')\n\n net_shape = net.get_shape().as_list()\n net = tf.reshape(net, [-1, net_shape[1] * net_shape[2] * net_shape[3]])\n\n return learn.models.logistic_regression(net, y)\n\n\n# Download and load MNIST data.\nmnist = input_data.read_data_sets('MNIST_data')\n\n# Restore model if graph is saved into a folder.\nif os.path.exists('models/resnet/graph.pbtxt'):\n classifier = learn.TensorFlowEstimator.restore('models/resnet/')\nelse:\n # Create a new resnet classifier.\n classifier = learn.TensorFlowEstimator(\n model_fn=res_net, n_classes=10, batch_size=100, steps=100,\n learning_rate=0.001, continue_training=True)\n\nwhile True:\n # Train model and save summaries into logdir.\n classifier.fit(\n mnist.train.images, mnist.train.labels, logdir='models/resnet/')\n\n # Calculate accuracy.\n score = metrics.accuracy_score(\n mnist.test.labels, classifier.predict(mnist.test.images, batch_size=64))\n print('Accuracy: {0:f}'.format(score))\n\n # Save model graph and checkpoints.\n classifier.save('models/resnet/')\n",
"# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Classification metrics library.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import math_ops\n\n# TODO(nsilberman): move into metrics/python/ops/\n\n\ndef accuracy(predictions, labels, weights=None):\n \"\"\"Computes the percentage of times that predictions matches labels.\n\n Args:\n predictions: the predicted values, a `Tensor` whose dtype and shape\n matches 'labels'.\n labels: the ground truth values, a `Tensor` of any shape and\n integer or string dtype.\n weights: None or `Tensor` of float values to reweight the accuracy.\n\n Returns:\n Accuracy `Tensor`.\n\n Raises:\n ValueError: if dtypes don't match or\n if dtype is not integer or string.\n \"\"\"\n if not (labels.dtype.is_integer or labels.dtype == dtypes.string):\n raise ValueError('Labels should have integer or string dtype. '\n 'Given: %s' % str(labels.dtype))\n if not labels.dtype.is_compatible_with(predictions.dtype):\n raise ValueError('Dtypes of predictions and labels should match. '\n 'Given: predictions (%s) and labels (%s)' %\n (str(predictions.dtype), str(labels.dtype)))\n with ops.op_scope([predictions, labels], 'accuracy'):\n is_correct = math_ops.cast(\n math_ops.equal(predictions, labels), dtypes.float32)\n if weights is not None:\n is_correct = math_ops.mul(is_correct, weights)\n return math_ops.reduce_mean(is_correct)\n",
"# Copyright 2015-present The Scikit Flow 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.\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom sklearn import metrics\nimport pandas\n\nimport tensorflow as tf\nfrom tensorflow.contrib import learn\n\n### Training data\n\n# Downloads, unpacks and reads DBpedia dataset.\ndbpedia = learn.datasets.load_dataset('dbpedia')\nX_train, y_train = pandas.DataFrame(dbpedia.train.data)[1], pandas.Series(dbpedia.train.target)\nX_test, y_test = pandas.DataFrame(dbpedia.test.data)[1], pandas.Series(dbpedia.test.target)\n\n### Process vocabulary\n\nMAX_DOCUMENT_LENGTH = 10\n\nvocab_processor = learn.preprocessing.VocabularyProcessor(MAX_DOCUMENT_LENGTH)\nX_train = np.array(list(vocab_processor.fit_transform(X_train)))\nX_test = np.array(list(vocab_processor.transform(X_test)))\n\nn_words = len(vocab_processor.vocabulary_)\nprint('Total words: %d' % n_words)\n\n### Models\n\nEMBEDDING_SIZE = 50\n\ndef average_model(X, y):\n word_vectors = learn.ops.categorical_variable(X, n_classes=n_words,\n embedding_size=EMBEDDING_SIZE, name='words')\n features = tf.reduce_max(word_vectors, reduction_indices=1)\n return learn.models.logistic_regression(features, y)\n\ndef rnn_model(X, y):\n \"\"\"Recurrent neural network model to predict from sequence of words\n to a class.\"\"\"\n # Convert indexes of words into embeddings.\n # This creates embeddings matrix of [n_words, EMBEDDING_SIZE] and then\n # maps word indexes of the sequence into [batch_size, sequence_length,\n # EMBEDDING_SIZE].\n word_vectors = learn.ops.categorical_variable(X, n_classes=n_words,\n embedding_size=EMBEDDING_SIZE, name='words')\n # Split into list of embedding per word, while removing doc length dim.\n # word_list results to be a list of tensors [batch_size, EMBEDDING_SIZE].\n word_list = learn.ops.split_squeeze(1, MAX_DOCUMENT_LENGTH, word_vectors)\n # Create a Gated Recurrent Unit cell with hidden size of EMBEDDING_SIZE.\n cell = tf.nn.rnn_cell.GRUCell(EMBEDDING_SIZE)\n # Create an unrolled Recurrent Neural Networks to length of\n # MAX_DOCUMENT_LENGTH and passes word_list as inputs for each unit.\n _, encoding = tf.nn.rnn(cell, word_list, dtype=tf.float32)\n # Given encoding of RNN, take encoding of last step (e.g hidden size of the\n # neural network of last step) and pass it as features for logistic\n # regression over output classes.\n return learn.models.logistic_regression(encoding, y)\n\nclassifier = learn.TensorFlowEstimator(model_fn=rnn_model, n_classes=15,\n steps=1000, optimizer='Adam', learning_rate=0.01, continue_training=True)\n\n# Continuously train for 1000 steps & predict on test set.\nwhile True:\n classifier.fit(X_train, y_train, logdir='/tmp/tf_examples/word_rnn')\n score = metrics.accuracy_score(y_test, classifier.predict(X_test))\n print('Accuracy: {0:f}'.format(score))\n"
] |
[
[
"tensorflow.device",
"tensorflow.zeros",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.Graph",
"tensorflow.Variable",
"tensorflow.merge_all_summaries",
"tensorflow.gather",
"tensorflow.nn.top_k",
"tensorflow.models.embedding.gen_word2vec.skipgram",
"tensorflow.initialize_all_variables",
"tensorflow.Session",
"tensorflow.train.Saver",
"tensorflow.compat.as_text",
"tensorflow.app.run",
"tensorflow.nn.l2_normalize",
"tensorflow.matmul",
"tensorflow.placeholder",
"tensorflow.zeros_like",
"tensorflow.train.GradientDescentOptimizer",
"numpy.array",
"tensorflow.nn.embedding_lookup",
"tensorflow.reshape",
"tensorflow.scalar_summary",
"tensorflow.ones_like",
"tensorflow.train.SummaryWriter",
"tensorflow.mul",
"tensorflow.random_uniform"
],
[
"tensorflow.assert_proper_iterable",
"tensorflow.assert_rank_at_least",
"tensorflow.assert_non_positive",
"tensorflow.assert_less_equal",
"tensorflow.is_non_decreasing",
"tensorflow.assert_rank",
"tensorflow.test.main",
"tensorflow.assert_less",
"tensorflow.identity",
"tensorflow.placeholder",
"tensorflow.assert_equal",
"numpy.array",
"tensorflow.assert_negative",
"tensorflow.assert_integer",
"tensorflow.is_strictly_increasing",
"tensorflow.constant",
"tensorflow.SparseTensor",
"tensorflow.assert_non_negative",
"tensorflow.assert_positive"
],
[
"tensorflow.Graph",
"tensorflow.constant",
"tensorflow.RunMetadata",
"tensorflow.test.main",
"tensorflow.train.SummaryWriter",
"tensorflow.Summary.Value",
"tensorflow.train.summary_iterator",
"tensorflow.SessionLog",
"tensorflow.GraphDef"
],
[
"tensorflow.constant",
"tensorflow.identity",
"tensorflow.test.main",
"numpy.finfo",
"numpy.zeros"
],
[
"tensorflow.python.ops.tensor_array_ops.TensorArray",
"tensorflow.constant",
"tensorflow.while_loop",
"tensorflow.control_dependencies",
"tensorflow.as_dtype",
"numpy.asarray",
"numpy.arange",
"tensorflow.gradients",
"tensorflow.test.main",
"tensorflow.identity",
"tensorflow.placeholder",
"tensorflow.squeeze",
"tensorflow.initialize_all_variables",
"tensorflow.python.framework.tensor_shape.unknown_shape",
"numpy.array",
"tensorflow.pack",
"tensorflow.python.ops.gen_data_flow_ops._tensor_array_read"
],
[
"tensorflow.contrib.learn.TensorFlowEstimator",
"tensorflow.nn.max_pool",
"tensorflow.contrib.learn.TensorFlowEstimator.restore",
"tensorflow.reshape",
"tensorflow.contrib.learn.models.logistic_regression",
"tensorflow.nn.avg_pool",
"tensorflow.variable_scope",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.contrib.learn.ops.conv2d"
],
[
"tensorflow.python.framework.ops.op_scope",
"tensorflow.python.ops.math_ops.reduce_mean",
"tensorflow.python.ops.math_ops.mul",
"tensorflow.python.ops.math_ops.equal"
],
[
"tensorflow.contrib.learn.TensorFlowEstimator",
"tensorflow.reduce_max",
"pandas.Series",
"tensorflow.nn.rnn",
"tensorflow.contrib.learn.ops.split_squeeze",
"pandas.DataFrame",
"tensorflow.contrib.learn.models.logistic_regression",
"tensorflow.contrib.learn.preprocessing.VocabularyProcessor",
"tensorflow.contrib.learn.ops.categorical_variable",
"tensorflow.nn.rnn_cell.GRUCell",
"tensorflow.contrib.learn.datasets.load_dataset"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"0.12",
"1.7"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"2.2",
"1.13",
"2.3",
"2.4",
"2.9",
"1.7",
"2.5",
"0.12",
"2.8",
"2.10"
]
},
{
"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": []
}
] |
gjunyi90/Machine-Learning-For-Finance
|
[
"e73c3df3c68d71f671cdde3153988c6c617eba53"
] |
[
"Classification Based Machine Learning for Algorithmic Trading/default_predictions/Naive Bayes.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 25 22:02:07 2017\n\n@author: Anthony\n\"\"\"\nimport numpy as np\nimport pandas as pd\ndf = pd.read_csv(\"dataset_2.csv\")\n\ndf['default'].describe()\nprint(sum(df['default'] == 0))\nprint(sum(df['default'] == 1))\n\nX = df.iloc[:, 1:6].values\ny = df['default'].values\n\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, \n random_state=0)\n\nshuffle_index = np.random.permutation(len(X_train))\nX_train, y_train = X_train[shuffle_index], y_train[shuffle_index]\n\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_X = StandardScaler()\nX_train = sc_X.fit_transform(X_train)\nX_test = sc_X.transform(X_test)\n\nfrom sklearn.naive_bayes import GaussianNB\nclassifier = GaussianNB()\nclf.fit(X_train, y_train)\n\n# Cross Validation\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import cross_val_predict\ncross_val_score(clf, X_train, y_train, cv=3, scoring='accuracy')\ny_train_pred = cross_val_predict(clf, X_train, y_train, cv=3)\ncm = confusion_matrix(y_train, y_train_pred)\nprint(cm)\n\nfrom sklearn.metrics import precision_score, recall_score\nprint(\"precision score = {0:.4f}\".format(precision_score(y_train, y_train_pred)))\nprint(\"recall score = {0:.4f}\".format(recall_score(y_train, y_train_pred)))\n"
] |
[
[
"pandas.read_csv",
"sklearn.model_selection.cross_val_score",
"sklearn.naive_bayes.GaussianNB",
"sklearn.model_selection.cross_val_predict",
"sklearn.metrics.precision_score",
"sklearn.model_selection.train_test_split",
"sklearn.metrics.confusion_matrix",
"sklearn.preprocessing.StandardScaler",
"sklearn.metrics.recall_score"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
0x384c0/Experiments-RL
|
[
"709f720fbba1d4b15a29fbc6ed80d17852b627f8"
] |
[
"keras-rl/dqn_atari.py"
] |
[
"from __future__ import division\nimport argparse\n\nfrom PIL import Image\nimport numpy as np\nimport gym\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Flatten, Convolution2D, Permute\nfrom keras.optimizers import Adam\nimport keras.backend as K\n\nfrom rl.agents.dqn import DQNAgent\nfrom rl.policy import LinearAnnealedPolicy, BoltzmannQPolicy, EpsGreedyQPolicy\nfrom rl.memory import SequentialMemory\nfrom rl.core import Processor\nfrom rl.callbacks import FileLogger, ModelIntervalCheckpoint, Visualizer\n\n\nINPUT_SHAPE = (84, 84)\nWINDOW_LENGTH = 4\n\n\nclass AtariProcessor(Processor):\n def process_observation(self, observation):\n assert observation.ndim == 3 # (height, width, channel)\n img = Image.fromarray(observation)\n img = img.resize(INPUT_SHAPE).convert('L') # resize and convert to grayscale\n processed_observation = np.array(img)\n assert processed_observation.shape == INPUT_SHAPE\n return processed_observation.astype('uint8') # saves storage in experience memory\n\n def process_state_batch(self, batch):\n # We could perform this processing step in `process_observation`. In this case, however,\n # we would need to store a `float32` array instead, which is 4x more memory intensive than\n # an `uint8` array. This matters if we store 1M observations.\n processed_batch = batch.astype('float32') / 255.\n return processed_batch\n\n def process_reward(self, reward):\n # print(\"reward \" + str(reward))\n return np.clip(reward, -1., 1.)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--mode', choices=['train', 'test'], default='train')\nparser.add_argument('--env-name', type=str, default='BreakoutDeterministic-v4')\nparser.add_argument('--weights', type=str, default=None)\nargs = parser.parse_args()\n\n# Get the environment and extract the number of actions.\nenv = gym.make(args.env_name)\nnp.random.seed(123)\nenv.seed(123)\nnb_actions = env.action_space.n\n\n# Next, we build our model. We use the same model that was described by Mnih et al. (2015).\ninput_shape = (WINDOW_LENGTH,) + INPUT_SHAPE\nmodel = Sequential()\nif K.image_dim_ordering() == 'tf':\n # (width, height, channels)\n model.add(Permute((2, 3, 1), input_shape=input_shape))\nelif K.image_dim_ordering() == 'th':\n # (channels, width, height)\n model.add(Permute((1, 2, 3), input_shape=input_shape))\nelse:\n raise RuntimeError('Unknown image_dim_ordering.')\nmodel.add(Convolution2D(32, (8, 8), strides=(4, 4)))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(64, (4, 4), strides=(2, 2)))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(64, (3, 3), strides=(1, 1)))\nmodel.add(Activation('relu'))\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\nmodel.add(Dense(nb_actions))\nmodel.add(Activation('linear'))\nprint(model.summary())\n\n# Finally, we configure and compile our agent. You can use every built-in Keras optimizer and\n# even the metrics!\nmemory = SequentialMemory(limit=1000000, window_length=WINDOW_LENGTH)\nprocessor = AtariProcessor()\n\n# Select a policy. We use eps-greedy action selection, which means that a random action is selected\n# with probability eps. We anneal eps from 1.0 to 0.1 over the course of 1M steps. This is done so that\n# the agent initially explores the environment (high eps) and then gradually sticks to what it knows\n# (low eps). We also set a dedicated eps value that is used during testing. Note that we set it to 0.05\n# so that the agent still performs some random actions. This ensures that the agent cannot get stuck.\npolicy = LinearAnnealedPolicy(EpsGreedyQPolicy(), attr='eps', value_max=1., value_min=.1, value_test=.05,\n nb_steps=1000000)\n\n# The trade-off between exploration and exploitation is difficult and an on-going research topic.\n# If you want, you can experiment with the parameters or use a different policy. Another popular one\n# is Boltzmann-style exploration:\n# policy = BoltzmannQPolicy(tau=1.)\n# Feel free to give it a try!\n\ndqn = DQNAgent(model=model, nb_actions=nb_actions, policy=policy, memory=memory,\n processor=processor, nb_steps_warmup=50000, gamma=.99, target_model_update=10000,\n train_interval=4, delta_clip=1.)\ndqn.compile(Adam(lr=.00025), metrics=['mae'])\n\nif args.mode == 'train':\n # Okay, now it's time to learn something! We capture the interrupt exception so that training\n # can be prematurely aborted. Notice that you can the built-in Keras callbacks!\n weights_filename = 'tmp/dqn_{}_weights.h5f'.format(args.env_name)\n checkpoint_weights_filename = 'tmp/dqn_' + args.env_name + '_weights_{step}.h5f'\n log_filename = 'tmp/dqn_{}_log.json'.format(args.env_name)\n callbacks = [\n ModelIntervalCheckpoint(checkpoint_weights_filename, interval=250000),\n FileLogger(log_filename, interval=100),\n Visualizer()\n ]\n dqn.fit(env, callbacks=callbacks, nb_steps=1750000, log_interval=10000)\n\n # After training is done, we save the final weights one more time.\n dqn.save_weights(weights_filename, overwrite=True)\n\n # Finally, evaluate our algorithm for 10 episodes.\n dqn.test(env, nb_episodes=10, visualize=False)\nelif args.mode == 'test':\n weights_filename = 'tmp/dqn_{}_weights.h5f'.format(args.env_name)\n if args.weights:\n weights_filename = args.weights\n dqn.load_weights(weights_filename)\n dqn.test(env, nb_episodes=10, visualize=True)\n"
] |
[
[
"numpy.array",
"numpy.random.seed",
"numpy.clip"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jhykes/rebin
|
[
"1f106c3a856289c26aaead8c7e08b37a1e88b266"
] |
[
"test_rebin.py"
] |
[
"\"\"\"\nTesting bebin histogram values.\n\n\"\"\"\nimport numpy as np\nfrom numpy.random import uniform\nfrom numpy.testing import assert_allclose\n\nfrom scipy.interpolate import splrep, splint\n\nimport uncertainties.unumpy as unp\n\nimport rebin\nfrom bounded_splines import BoundedUnivariateSpline, BoundedRectBivariateSpline\n\n\n# ---------------------------------------------------------------------------- #\n# Tests for piecewise continuous rebinning\n# ---------------------------------------------------------------------------- #\n\n# ---------------------------------------------------------------------------- #\ndef test_x2_same_as_x1():\n \"\"\"\n x2 same as x1\n \"\"\"\n # old size\n m = 6\n \n # new size\n n = 6\n \n # bin edges \n x_old = np.linspace(0., 1., m+1)\n x_new = np.linspace(0., 1., n+1)\n \n # some arbitrary distribution\n y_old = 1. + np.sin(x_old[:-1]*np.pi) / np.ediff1d(x_old)\n \n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind='piecewise_constant')\n\n assert_allclose(y_new, y_old)\n\n\n# ---------------------------------------------------------------------------- #\ndef test_x2_surrounds_x1():\n \"\"\"\n x2 range surrounds x1 range\n \"\"\"\n # old size\n m = 2\n \n # new size\n n = 3\n \n # bin edges \n x_old = np.linspace(0., 1., m+1)\n x_new = np.linspace(-0.1, 1.2, n+1)\n \n # some arbitrary distribution\n y_old = 1. + np.sin(x_old[:-1]*np.pi) / np.ediff1d(x_old)\n \n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind='piecewise_constant')\n\n # compute answer here to check rebin\n y_old_ave = y_old / np.ediff1d(x_old)\n y_new_here = [y_old_ave[0]*(x_new[1]-0.), \n y_old_ave[0]*(x_old[1]-x_new[1]) + y_old_ave[1]*(x_new[2]-x_old[1]),\n y_old_ave[1]*(x_old[-1]-x_new[-2])]\n\n assert_allclose(y_new, y_new_here)\n assert_allclose(y_new.sum(), y_old.sum())\n\n\n# ---------------------------------------------------------------------------- #\ndef test_x2_lower_than_x1():\n \"\"\"\n x2 range is completely lower than x1 range\n \"\"\"\n # old size\n m = 2\n\n # new size\n n = 3\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.linspace(-0.2, -0.0, n+1)\n\n # some arbitrary distribution\n y_old = 1. + np.sin(x_old[:-1]*np.pi) / np.ediff1d(x_old)\n\n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind='piecewise_constant')\n\n\n assert_allclose(y_new, [0.,0.,0.])\n assert_allclose(y_new.sum(), 0.)\n\n# ---------------------------------------------------------------------------- #\ndef test_x2_above_x1():\n \"\"\"\n x2 range is completely above x1 range\n \"\"\"\n # old size\n m = 20\n\n # new size\n n = 30\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.linspace(1.2, 10., n+1)\n\n # some arbitrary distribution\n y_old = 1. + np.sin(x_old[:-1]*np.pi) / np.ediff1d(x_old)\n\n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind='piecewise_constant')\n\n\n assert_allclose(y_new, np.zeros((n,)))\n assert_allclose(y_new.sum(), 0.)\n\n\n# ---------------------------------------------------------------------------- #\ndef test_x2_in_x1():\n \"\"\"\n x2 only has one bin, and it is surrounded by x1 range\n \"\"\"\n # old size\n m = 4\n\n # new size\n n = 1\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.linspace(0.3, 0.65, n+1)\n\n # some arbitrary distribution\n y_old = 1. + np.sin(x_old[:-1]*np.pi) / np.ediff1d(x_old)\n\n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind='piecewise_constant')\n\n # compute answer here to check rebin\n y_old_ave = y_old / np.ediff1d(x_old)\n y_new_here = ( y_old_ave[1]*(x_old[2]-x_new[0])\n + y_old_ave[2]*(x_new[1]-x_old[2]) )\n\n assert_allclose(y_new, y_new_here)\n\n\n# ---------------------------------------------------------------------------- #\ndef test_x2_in_x1_2():\n \"\"\"\n x2 has a couple of bins, each of which span more than one original bin\n \"\"\"\n # old size\n m = 10\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.array([0.25, 0.55, 0.75])\n\n # some arbitrary distribution\n y_old = 1. + np.sin(x_old[:-1]*np.pi) / np.ediff1d(x_old)\n\n y_old = unp.uarray(y_old, 0.1*y_old*uniform((m,)))\n\n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind='piecewise_constant')\n\n # compute answer here to check rebin\n y_new_here = unp.uarray(np.zeros(2), np.zeros(2))\n y_new_here[0] = 0.5 * y_old[2] + y_old[3] + y_old[4] + 0.5 * y_old[5]\n y_new_here[1] = 0.5 * y_old[5] + y_old[6] + 0.5 * y_old[7]\n\n assert_allclose(unp.nominal_values(y_new),\n unp.nominal_values(y_new_here))\n\n # mean or nominal value comparison\n assert_allclose(unp.std_devs(y_new),\n unp.std_devs(y_new_here))\n\n\n# ---------------------------------------------------------------------------- #\ndef test_y1_uncertainties():\n \"\"\"\n x2 range surrounds x1 range, y1 has uncertainties\n \"\"\"\n # old size\n m = 2\n\n # new size\n n = 3\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.linspace(-0.1, 1.2, n+1)\n\n # some arbitrary distribution\n y_old = 1. + np.sin(x_old[:-1]*np.pi) / np.ediff1d(x_old)\n\n # with uncertainties\n y_old = unp.uarray(y_old, 0.1*y_old*uniform((m,)))\n\n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind='piecewise_constant')\n\n # compute answer here to check rebin\n y_old_ave = y_old / np.ediff1d(x_old)\n y_new_here = np.array(\n [y_old_ave[0]*(x_new[1]-0.),\n y_old_ave[0]*(x_old[1]-x_new[1]) + y_old_ave[1]*(x_new[2]-x_old[1]),\n y_old_ave[1]*(x_old[-1]-x_new[-2])]\n )\n\n\n # mean or nominal value comparison\n assert_allclose(unp.nominal_values(y_new),\n unp.nominal_values(y_new_here))\n\n # mean or nominal value comparison\n assert_allclose(unp.std_devs(y_new),\n unp.std_devs(y_new_here))\n assert_allclose(unp.nominal_values(y_new).sum(),\n unp.nominal_values(y_new_here).sum())\n\n\n# ---------------------------------------------------------------------------- #\n# Tests for cubic-spline rebinning\n# ---------------------------------------------------------------------------- #\n\n\n# ---------------------------------------------------------------------------- #\ndef test_x2_surrounds_x1_with_constant_distribution():\n \"\"\"\n x2 domain completely surrounds x1 domain\n \"\"\"\n # old size\n m = 20\n\n # new size\n n = 30\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.linspace(-0.5, 1.5, n+1)\n\n # constant spline\n mms_spline = BoundedUnivariateSpline([0,.1,.2,1], [1,1,1,1], s=0.)\n\n y_old = np.array(\n [ mms_spline.integral(x_old[i],x_old[i+1]) for i in range(m) ])\n\n y_new_mms = np.array(\n [ mms_spline.integral(x_new[i],x_new[i+1]) for i in range(n) ])\n\n\n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind=3)\n\n assert_allclose(y_new, y_new_mms)\n\n# ---------------------------------------------------------------------------- #\ndef test_x2_left_overlap_x1_with_constant_distribution():\n \"\"\"\n x2 domain overlaps x1 domain from the left\n \"\"\"\n # old size\n m = 20\n\n # new size\n n = 30\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.linspace(-0.75, 0.45, n+1)\n\n # constant spline\n mms_spline = BoundedUnivariateSpline([0,.1,.2,1], [1,1,1,1], s=0.)\n\n y_old = np.array(\n [ mms_spline.integral(x_old[i],x_old[i+1]) for i in range(m) ])\n\n y_new_mms = np.array(\n [ mms_spline.integral(x_new[i],x_new[i+1]) for i in range(n) ])\n\n\n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind=3)\n\n assert_allclose(y_new, y_new_mms)\n\n# ---------------------------------------------------------------------------- #\ndef test_x2_right_overlap_x1_with_constant_distribution():\n \"\"\"\n x2 domain overlaps x1 domain from the right\n \"\"\"\n # old size\n m = 20\n\n # new size\n n = 30\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.linspace(0.95, 1.05, n+1)\n\n # constant spline\n mms_spline = BoundedUnivariateSpline([0,.1,.2,1], [1,1,1,1], s=0.)\n\n y_old = np.array(\n [ mms_spline.integral(x_old[i],x_old[i+1]) for i in range(m) ])\n\n y_new_mms = np.array(\n [ mms_spline.integral(x_new[i],x_new[i+1]) for i in range(n) ])\n\n\n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind=3)\n\n assert_allclose(y_new, y_new_mms, atol=1e-15)\n\n# ---------------------------------------------------------------------------- #\ndef test_x1_surrounds_x2_with_constant_distribution():\n \"\"\"\n x1 domain surrounds x2\n \"\"\"\n # old size\n m = 20\n\n # new size\n n = 30\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.linspace(0.05, 0.26, n+1)\n\n # constant spline\n mms_spline = BoundedUnivariateSpline([0,.1,.2,1], [1,1,1,1], s=0.)\n\n y_old = np.array(\n [ mms_spline.integral(x_old[i],x_old[i+1]) for i in range(m) ])\n\n y_new_mms = np.array(\n [ mms_spline.integral(x_new[i],x_new[i+1]) for i in range(n) ])\n\n\n # rebin\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind=3)\n\n assert_allclose(y_new, y_new_mms)\n\n\n# ---------------------------------------------------------------------------- #\ndef test_x2_surrounds_x1_sine_spline():\n \"\"\"\n x2 range is completely above x1 range\n using a random vector to build spline\n \"\"\"\n # old size\n m = 5\n\n # new size\n n = 6\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.array([-.3, -.09, 0.11, 0.14, 0.2, 0.28, 0.73])\n\n subbins = np.array([-.3, -.09, 0., 0.11, 0.14, 0.2, 0.28, 0.4, 0.6, 0.73])\n\n y_old = 1.+np.sin(x_old[:-1]*np.pi)\n\n # compute spline ----------------------------------\n x_mids = x_old[:-1] + 0.5*np.ediff1d(x_old)\n xx = np.hstack([x_old[0], x_mids, x_old[-1]])\n yy = np.hstack([y_old[0], y_old, y_old[-1]])\n\n # build spline\n spl = splrep(xx, yy)\n\n area_old = np.array(\n [ splint(x_old[i],x_old[i+1], spl) for i in range(m) ])\n\n # computing subbin areas\n area_subbins = np.zeros((subbins.size-1,))\n for i in range(area_subbins.size):\n a, b = subbins[i:i+2]\n a = max([a,x_old[0]])\n b = min([b,x_old[-1]])\n if b>a:\n area_subbins[i] = splint(a, b, spl)\n\n # summing subbin contributions in y_new_ref\n y_new_ref = np.zeros((x_new.size-1,))\n y_new_ref[1] = y_old[0] * area_subbins[2] / area_old[0]\n y_new_ref[2] = y_old[0] * area_subbins[3] / area_old[0]\n y_new_ref[3] = y_old[0] * area_subbins[4] / area_old[0]\n y_new_ref[4] = y_old[1] * area_subbins[5] / area_old[1]\n\n y_new_ref[5] = y_old[1] * area_subbins[6] / area_old[1]\n y_new_ref[5] += y_old[2] * area_subbins[7] / area_old[2]\n y_new_ref[5] += y_old[3] * area_subbins[8] / area_old[3]\n\n # call rebin function\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind=3)\n\n assert_allclose(y_new, y_new_ref)\n\n# ---------------------------------------------------------------------------- #\ndef test_y1_uncertainties_spline_with_constant_distribution():\n \"\"\"\n\n \"\"\"\n # old size\n m = 5\n\n # new size\n n = 6\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n x_new = np.array([-.3, -.09, 0.11, 0.14, 0.2, 0.28, 0.73])\n\n subbins = np.array([-.3, -.09, 0., 0.11, 0.14, 0.2, 0.28, 0.4, 0.6, 0.73])\n\n y_old = 1.+np.sin(x_old[:-1]*np.pi)\n\n # compute spline ----------------------------------\n x_mids = x_old[:-1] + 0.5*np.ediff1d(x_old)\n xx = np.hstack([x_old[0], x_mids, x_old[-1]])\n yy = np.hstack([y_old[0], y_old, y_old[-1]])\n\n # build spline\n spl = splrep(xx, yy)\n\n area_old = np.array(\n [ splint(x_old[i],x_old[i+1], spl) for i in range(m) ])\n\n # with uncertainties\n y_old = unp.uarray(y_old, 0.1*y_old*uniform((m,)))\n\n # computing subbin areas\n area_subbins = np.zeros((subbins.size-1,))\n for i in range(area_subbins.size):\n a, b = subbins[i:i+2]\n a = max([a,x_old[0]])\n b = min([b,x_old[-1]])\n if b>a:\n area_subbins[i] = splint(a, b, spl)\n\n # summing subbin contributions in y_new_ref\n a = np.zeros((x_new.size-1,))\n y_new_ref = unp.uarray(a,a)\n y_new_ref[1] = y_old[0] * area_subbins[2] / area_old[0]\n y_new_ref[2] = y_old[0] * area_subbins[3] / area_old[0]\n y_new_ref[3] = y_old[0] * area_subbins[4] / area_old[0]\n y_new_ref[4] = y_old[1] * area_subbins[5] / area_old[1]\n\n y_new_ref[5] = y_old[1] * area_subbins[6] / area_old[1]\n y_new_ref[5] += y_old[2] * area_subbins[7] / area_old[2]\n y_new_ref[5] += y_old[3] * area_subbins[8] / area_old[3]\n\n # call rebin function\n y_new = rebin.rebin(x_old, y_old, x_new, interp_kind=3)\n\n # mean or nominal value comparison\n assert_allclose(unp.nominal_values(y_new),\n unp.nominal_values(y_new_ref))\n\n # mean or nominal value comparison\n assert_allclose(unp.std_devs(y_new),\n unp.std_devs(y_new_ref))\n\n\n# ---------------------------------------------------------------------------- #\n# Tests for 2d rebinning\n# ---------------------------------------------------------------------------- #\n\n\n# ---------------------------------------------------------------------------- #\ndef test_2d_same():\n \"\"\"\n x1, y1 == x2, y2 implies z1 == z2\n 2d\n \"\"\"\n # old size\n m = 20\n n = 30\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n y_old = np.linspace(-0.5, 1.5, n+1)\n\n z_old = np.random.random((m,n))\n\n # rebin\n z_new = rebin.rebin2d(x_old, y_old, z_old, x_old, y_old)\n\n assert_allclose(z_old, z_new)\n\n# ---------------------------------------------------------------------------- #\ndef test_2d_constant_distribution():\n \"\"\"\n various new domains with a constant underlying distribution\n 2d\n \"\"\"\n # old size\n m = 8\n n = 11\n\n # new size\n p = 5\n q = 14\n\n new_bounds = [ (0., 1., -1.5, 1.7),\n (0., 1., -1.5, 0.7),\n (0., 1., -1.5, -0.7),\n (-1., 1.5, -1.5, 1.7),\n (-1., 0.5, -1., 0.5),\n (0.1, 0.6, 0.1, 0.5),\n (0.01, 0.02, -10.0, 20.7)]\n\n for (a,b,c,d) in new_bounds:\n\n # bin edges\n x_old = np.linspace(0., 1., m+1)\n y_old = np.linspace(-0.5, 1.5, n+1)\n\n x_new = np.linspace(a, b, p+1)\n y_new = np.linspace(c, d, q+1)\n\n # constant spline\n z_old = np.ones((m+1,n+1))\n mms_spline = BoundedRectBivariateSpline(x_old, y_old, z_old, s=0.)\n\n z_old = np.zeros((m,n))\n for i in range(m):\n for j in range(n):\n z_old[i,j] = mms_spline.integral(x_old[i], x_old[i+1],\n y_old[j], y_old[j+1])\n\n z_new_mms = np.zeros((p,q))\n for i in range(p):\n for j in range(q):\n z_new_mms[i,j] = mms_spline.integral(x_new[i], x_new[i+1],\n y_new[j], y_new[j+1])\n\n # rebin\n z_new = rebin.rebin2d(x_old, y_old, z_old, x_new, y_new)\n\n assert_allclose(z_new, z_new_mms)\n\n\ndef test_GH9():\n x_old = np.array([1.5, 2.5, 3.5, 4.5, 5.5, 6.5])\n y_old = np.array([10, 10, 10, 10, 10])\n x_new = np.array([1.7, 2.27332857, 2.84665714, 3.41998571,\n 3.99331429, 4.56664286])\n y_new = rebin.rebin(x_old, y_old, x_new)\n assert_allclose(y_new,\n [5.7332857] * 5)\n\n # with uncertainties\n y_old = np.array([11., 12., 13., 14., 15.])\n\n y_old = unp.uarray(y_old, 0.1 * y_old)\n\n # rebin\n y_new = rebin.rebin_piecewise_constant(x_old, y_old, x_new)\n\n # compute answer here to check rebin\n y_old_ave = y_old / np.diff(x_old)\n y_new_here = np.array(\n [y_old_ave[0] * (x_new[1] - x_new[0]),\n\n y_old_ave[0] * (x_old[1] - x_new[1]) +\n y_old_ave[1] * (x_new[2] - x_old[1]),\n\n y_old_ave[1] * (x_new[3] - x_new[2]),\n\n y_old_ave[1] * (x_old[2] - x_new[3]) +\n y_old_ave[2] * (x_new[4] - x_old[2]),\n\n y_old_ave[3] * (x_new[5] - x_old[3]) +\n y_old_ave[2] * (x_old[3] - x_new[4])])\n\n # mean or nominal value comparison\n # assert_allclose(unp.nominal_values(y_new),\n # unp.nominal_values(y_new_here))\n\n # mean or nominal value comparison\n assert_allclose(unp.std_devs(y_new),\n unp.std_devs(y_new_here))\n"
] |
[
[
"numpy.hstack",
"scipy.interpolate.splrep",
"numpy.random.random",
"numpy.linspace",
"numpy.ediff1d",
"numpy.sin",
"numpy.ones",
"scipy.interpolate.splint",
"numpy.diff",
"numpy.testing.assert_allclose",
"numpy.random.uniform",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
Polarbeartnt/SP-ILC
|
[
"07c812dfe40461409c9714936190ba1470f91fc3"
] |
[
"data180k/multA.py"
] |
[
"import numpy as np\nimport os\nfrom PIL import Image\n\nMatrixA = np.loadtxt('../A_8192.txt')\n\nroot = 'selfmadeimg'\nnew_root = 'selfmadetxt'\nfolders = ['2']\n\nif not os.path.exists(new_root):\n os.mkdir(new_root)\n\ncnt = 0\nfor folder in folders:\n if not os.path.exists('%s/%s'%(new_root, folder)):\n os.mkdir('%s/%s'%(new_root, folder))\n images = os.listdir('%s/%s'%(root,folder))\n tot = len(folders)*len(images)\n for imgpath in images:\n fp = open('%s/%s/%s'%(root,folder,imgpath), 'rb')\n img = Image.open(fp).convert('L')\n fp.close()\n img = np.array(img)\n s = np.dot(np.reshape(img,[img.shape[0]*img.shape[1]]),np.transpose(MatrixA))\n imgname = imgpath.split('.')[0] + '.txt'\n np.savetxt('%s/%s/%s'%(new_root,folder,imgname), s)\n cnt += 1\n print('Finished %s / %s.'%(cnt, tot))\n"
] |
[
[
"numpy.reshape",
"numpy.transpose",
"numpy.savetxt",
"numpy.array",
"numpy.loadtxt"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
nolaurence/mlflow
|
[
"2e8a3c53a3657f92cf23b5508f537abd6c2d71f4"
] |
[
"mlflow/models/evaluation/base.py"
] |
[
"from typing import Dict, Union, Any\nimport mlflow\nimport hashlib\nimport json\nimport os\nfrom contextlib import contextmanager\nfrom mlflow.exceptions import MlflowException\nfrom mlflow.utils.file_utils import TempDir\nfrom mlflow.entities import RunTag\nfrom mlflow.tracking.artifact_utils import _download_artifact_from_uri\nfrom mlflow.utils import _get_fully_qualified_class_name\nfrom mlflow.utils.class_utils import _get_class_from_string\nfrom mlflow.utils.annotations import experimental\nimport logging\nimport struct\nimport sys\nimport math\nfrom collections import OrderedDict\nfrom abc import ABCMeta, abstractmethod\n\n\n_logger = logging.getLogger(__name__)\n\n\nclass EvaluationArtifact(metaclass=ABCMeta):\n \"\"\"\n A model evaluation artifact containing an artifact uri and content.\n \"\"\"\n\n def __init__(self, uri, content=None):\n self._uri = uri\n self._content = content\n\n @abstractmethod\n def _load_content_from_file(self, local_artifact_path):\n \"\"\"\n Abstract interface to load the content from local artifact file path,\n and return the loaded content.\n \"\"\"\n pass\n\n def _load(self, local_artifact_path=None):\n \"\"\"\n If ``local_artifact_path`` is ``None``, download artifact from the artifact uri.\n Otherwise, load artifact content from the specified path. Assign the loaded content to\n ``self._content``, and return the loaded content.\n \"\"\"\n if local_artifact_path is not None:\n self._content = self._load_content_from_file(local_artifact_path)\n else:\n with TempDir() as temp_dir:\n temp_dir_path = temp_dir.path()\n _download_artifact_from_uri(self._uri, temp_dir_path)\n local_artifact_file = temp_dir.path(os.listdir(temp_dir_path)[0])\n self._content = self._load_content_from_file(local_artifact_file)\n return self._content\n\n @abstractmethod\n def _save(self, output_artifact_path):\n \"\"\"Save artifact content into specified path.\"\"\"\n pass\n\n @property\n def content(self):\n \"\"\"\n The content of the artifact (representation varies)\n \"\"\"\n if self._content is None:\n self._load()\n return self._content\n\n @property\n def uri(self) -> str:\n \"\"\"\n The URI of the artifact\n \"\"\"\n return self._uri\n\n def __repr__(self):\n return f\"{self.__class__.__name__}(uri='{self.uri}')\"\n\n\nclass EvaluationResult:\n \"\"\"\n Represents the model evaluation outputs of a `mlflow.evaluate()` API call, containing\n both scalar metrics and output artifacts such as performance plots.\n \"\"\"\n\n def __init__(self, metrics, artifacts):\n self._metrics = metrics\n self._artifacts = artifacts\n\n @classmethod\n def load(cls, path):\n \"\"\"Load the evaluation results from the specified local filesystem path\"\"\"\n with open(os.path.join(path, \"metrics.json\"), \"r\") as fp:\n metrics = json.load(fp)\n\n with open(os.path.join(path, \"artifacts_metadata.json\"), \"r\") as fp:\n artifacts_metadata = json.load(fp)\n\n artifacts = {}\n\n artifacts_dir = os.path.join(path, \"artifacts\")\n\n for artifact_name, meta in artifacts_metadata.items():\n uri = meta[\"uri\"]\n ArtifactCls = _get_class_from_string(meta[\"class_name\"])\n artifact = ArtifactCls(uri=uri)\n artifact._load(os.path.join(artifacts_dir, artifact_name))\n artifacts[artifact_name] = artifact\n\n return EvaluationResult(metrics=metrics, artifacts=artifacts)\n\n def save(self, path):\n \"\"\"Write the evaluation results to the specified local filesystem path\"\"\"\n os.makedirs(path, exist_ok=True)\n with open(os.path.join(path, \"metrics.json\"), \"w\") as fp:\n json.dump(self.metrics, fp)\n\n artifacts_metadata = {\n artifact_name: {\n \"uri\": artifact.uri,\n \"class_name\": _get_fully_qualified_class_name(artifact),\n }\n for artifact_name, artifact in self.artifacts.items()\n }\n with open(os.path.join(path, \"artifacts_metadata.json\"), \"w\") as fp:\n json.dump(artifacts_metadata, fp)\n\n artifacts_dir = os.path.join(path, \"artifacts\")\n os.mkdir(artifacts_dir)\n\n for artifact_name, artifact in self.artifacts.items():\n artifact._save(os.path.join(artifacts_dir, artifact_name))\n\n @property\n def metrics(self) -> Dict[str, Any]:\n \"\"\"\n A dictionary mapping scalar metric names to scalar metric values\n \"\"\"\n return self._metrics\n\n @property\n def artifacts(self) -> Dict[str, \"mlflow.models.EvaluationArtifact\"]:\n \"\"\"\n A dictionary mapping standardized artifact names (e.g. \"roc_data\") to\n artifact content and location information\n \"\"\"\n return self._artifacts\n\n\n_cached_mlflow_client = None\n\n\ndef _hash_uint64_ndarray_as_bytes(array):\n assert len(array.shape) == 1\n # see struct pack format string https://docs.python.org/3/library/struct.html#format-strings\n return struct.pack(f\">{array.size}Q\", *array)\n\n\ndef _hash_ndarray_as_bytes(nd_array):\n from pandas.util import hash_array\n import numpy as np\n\n return _hash_uint64_ndarray_as_bytes(\n hash_array(nd_array.flatten(order=\"C\"))\n ) + _hash_uint64_ndarray_as_bytes(np.array(nd_array.shape, dtype=\"uint64\"))\n\n\ndef _hash_array_like_obj_as_bytes(data):\n \"\"\"\n Helper method to convert pandas dataframe/numpy array/list into bytes for\n MD5 calculation purpose.\n \"\"\"\n from pandas.util import hash_pandas_object\n import numpy as np\n import pandas as pd\n\n if isinstance(data, pd.DataFrame):\n # add checking `'pyspark' in sys.modules` to avoid importing pyspark when user\n # run code not related to pyspark.\n if \"pyspark\" in sys.modules:\n from pyspark.ml.linalg import Vector as spark_vector_type\n else:\n spark_vector_type = None\n\n def _hash_array_like_element_as_bytes(v):\n if spark_vector_type is not None:\n if isinstance(v, spark_vector_type):\n return _hash_ndarray_as_bytes(v.toArray())\n if isinstance(v, np.ndarray):\n return _hash_ndarray_as_bytes(v)\n if isinstance(v, list):\n return _hash_ndarray_as_bytes(np.array(v))\n return v\n\n data = data.applymap(_hash_array_like_element_as_bytes)\n return _hash_uint64_ndarray_as_bytes(hash_pandas_object(data))\n elif isinstance(data, np.ndarray):\n return _hash_ndarray_as_bytes(data)\n elif isinstance(data, list):\n return _hash_ndarray_as_bytes(np.array(data))\n else:\n raise ValueError(\"Unsupported data type.\")\n\n\ndef _gen_md5_for_arraylike_obj(md5_gen, data):\n \"\"\"\n Helper method to generate MD5 hash array-like object, the MD5 will calculate over:\n - array length\n - first NUM_SAMPLE_ROWS_FOR_HASH rows content\n - last NUM_SAMPLE_ROWS_FOR_HASH rows content\n \"\"\"\n import numpy as np\n\n len_bytes = _hash_uint64_ndarray_as_bytes(np.array([len(data)], dtype=\"uint64\"))\n md5_gen.update(len_bytes)\n if len(data) < EvaluationDataset.NUM_SAMPLE_ROWS_FOR_HASH * 2:\n md5_gen.update(_hash_array_like_obj_as_bytes(data))\n else:\n head_rows = data[: EvaluationDataset.NUM_SAMPLE_ROWS_FOR_HASH]\n tail_rows = data[-EvaluationDataset.NUM_SAMPLE_ROWS_FOR_HASH :]\n md5_gen.update(_hash_array_like_obj_as_bytes(head_rows))\n md5_gen.update(_hash_array_like_obj_as_bytes(tail_rows))\n\n\nclass EvaluationDataset:\n \"\"\"\n An input dataset for model evaluation. This is intended for use with the\n :py:func:`mlflow.models.evaluate()`\n API.\n \"\"\"\n\n NUM_SAMPLE_ROWS_FOR_HASH = 5\n SPARK_DATAFRAME_LIMIT = 10000\n\n def __init__(self, data, *, targets, name=None, path=None, feature_names=None):\n \"\"\"\n The values of the constructor arguments comes from the `evaluate` call.\n \"\"\"\n import numpy as np\n import pandas as pd\n\n if name is not None and '\"' in name:\n raise ValueError(f'Dataset name cannot include a double quote (\") but got {name}')\n if path is not None and '\"' in path:\n raise ValueError(f'Dataset path cannot include a double quote (\") but got {path}')\n\n self._user_specified_name = name\n self._path = path\n self._hash = None\n self._supported_dataframe_types = (pd.DataFrame,)\n self._spark_df_type = None\n\n try:\n # add checking `'pyspark' in sys.modules` to avoid importing pyspark when user\n # run code not related to pyspark.\n if \"pyspark\" in sys.modules:\n from pyspark.sql import DataFrame as SparkDataFrame\n\n self._supported_dataframe_types = (pd.DataFrame, SparkDataFrame)\n self._spark_df_type = SparkDataFrame\n except ImportError:\n pass\n\n if feature_names is not None and len(set(feature_names)) < len(list(feature_names)):\n raise ValueError(\n \"`feature_names` argument must be a list containing unique feature names.\"\n )\n\n if isinstance(data, (np.ndarray, list)):\n if not isinstance(targets, (np.ndarray, list)):\n raise ValueError(\n \"If data is a numpy array or list of evaluation features, \"\n \"`targets` argument must be a numpy array or list of evaluation labels.\"\n )\n if isinstance(data, list):\n data = np.array(data)\n\n if len(data.shape) != 2:\n raise ValueError(\n \"If the `data` argument is a numpy array, it must be a 2 dimension array \"\n \"and second dimension represent the number of features. If the `data` \"\n \"argument is a list, each of its element must be a feature array of \"\n \"numpy array or list and all element must has the same length.\"\n )\n\n self._features_data = data\n self._labels_data = targets if isinstance(targets, np.ndarray) else np.array(targets)\n\n if len(self._features_data) != len(self._labels_data):\n raise ValueError(\n \"The input features example rows must be the same length with labels array.\"\n )\n\n num_features = data.shape[1]\n\n if feature_names is not None:\n feature_names = list(feature_names)\n if num_features != len(feature_names):\n raise ValueError(\"feature name list must be the same length with feature data.\")\n self._feature_names = feature_names\n else:\n self._feature_names = [\n f\"feature_{str(i + 1).zfill(math.ceil((math.log10(num_features + 1))))}\"\n for i in range(num_features)\n ]\n elif isinstance(data, self._supported_dataframe_types):\n if not isinstance(targets, str):\n raise ValueError(\n \"If data is a Pandas DataFrame or Spark DataFrame, `targets` argument must \"\n \"be the name of the column which contains evaluation labels in the `data` \"\n \"dataframe.\"\n )\n if self._spark_df_type and isinstance(data, self._spark_df_type):\n _logger.warning(\n \"Specified Spark DataFrame is too large for model evaluation. Only \"\n f\"the first {EvaluationDataset.SPARK_DATAFRAME_LIMIT} rows will be used.\"\n \"If you want evaluate on the whole spark dataframe, please manually call \"\n \"`spark_dataframe.toPandas()`.\"\n )\n data = data.limit(EvaluationDataset.SPARK_DATAFRAME_LIMIT).toPandas()\n\n self._labels_data = data[targets].to_numpy()\n\n if feature_names is not None:\n self._features_data = data[list(feature_names)]\n self._feature_names = feature_names\n else:\n self._features_data = data.drop(targets, axis=1, inplace=False)\n self._feature_names = list(self._features_data.columns)\n else:\n raise ValueError(\n \"The data argument must be a numpy array, a list or a Pandas DataFrame, or \"\n \"spark DataFrame if pyspark package installed.\"\n )\n\n # generate dataset hash\n md5_gen = hashlib.md5()\n _gen_md5_for_arraylike_obj(md5_gen, self._features_data)\n _gen_md5_for_arraylike_obj(md5_gen, self._labels_data)\n md5_gen.update(\",\".join(self._feature_names).encode(\"UTF-8\"))\n\n self._hash = md5_gen.hexdigest()\n\n @property\n def feature_names(self):\n return self._feature_names\n\n @property\n def features_data(self):\n \"\"\"\n return features data as a numpy array or a pandas DataFrame.\n \"\"\"\n return self._features_data\n\n @property\n def labels_data(self):\n \"\"\"\n return labels data as a numpy array\n \"\"\"\n return self._labels_data\n\n @property\n def name(self):\n \"\"\"\n Dataset name, which is specified dataset name or the dataset hash if user don't specify\n name.\n \"\"\"\n return self._user_specified_name if self._user_specified_name is not None else self.hash\n\n @property\n def path(self):\n \"\"\"\n Dataset path\n \"\"\"\n return self._path\n\n @property\n def hash(self):\n \"\"\"\n Dataset hash, includes hash on first 20 rows and last 20 rows.\n \"\"\"\n return self._hash\n\n @property\n def _metadata(self):\n \"\"\"\n Return dataset metadata containing name, hash, and optional path.\n \"\"\"\n metadata = {\n \"name\": self.name,\n \"hash\": self.hash,\n }\n if self.path is not None:\n metadata[\"path\"] = self.path\n return metadata\n\n def _log_dataset_tag(self, client, run_id, model_uuid):\n \"\"\"\n Log dataset metadata as a tag \"mlflow.datasets\", if the tag already exists, it will\n append current dataset metadata into existing tag content.\n \"\"\"\n existing_dataset_metadata_str = client.get_run(run_id).data.tags.get(\n \"mlflow.datasets\", \"[]\"\n )\n dataset_metadata_list = json.loads(existing_dataset_metadata_str)\n\n for metadata in dataset_metadata_list:\n if (\n metadata[\"hash\"] == self.hash\n and metadata[\"name\"] == self.name\n and metadata[\"model\"] == model_uuid\n ):\n break\n else:\n dataset_metadata_list.append({**self._metadata, \"model\": model_uuid})\n\n dataset_metadata_str = json.dumps(dataset_metadata_list, separators=(\",\", \":\"))\n client.log_batch(\n run_id,\n tags=[RunTag(\"mlflow.datasets\", dataset_metadata_str)],\n )\n\n def __hash__(self):\n return hash(self.hash)\n\n def __eq__(self, other):\n import numpy as np\n\n if not isinstance(other, EvaluationDataset):\n return False\n\n if isinstance(self._features_data, np.ndarray):\n is_features_data_equal = np.array_equal(self._features_data, other._features_data)\n else:\n is_features_data_equal = self._features_data.equals(other._features_data)\n\n return (\n is_features_data_equal\n and np.array_equal(self._labels_data, other._labels_data)\n and self.name == other.name\n and self.path == other.path\n and self._feature_names == other._feature_names\n )\n\n\nclass ModelEvaluator(metaclass=ABCMeta):\n @abstractmethod\n def can_evaluate(self, *, model_type, evaluator_config, **kwargs) -> bool:\n \"\"\"\n :param model_type: A string describing the model type (e.g., \"regressor\", \"classifier\", …).\n :param evaluator_config: A dictionary of additional configurations for\n the evaluator.\n :param kwargs: For forwards compatibility, a placeholder for additional arguments\n that may be added to the evaluation interface in the future.\n :return: True if the evaluator can evaluate the specified model on the\n specified dataset. False otherwise.\n \"\"\"\n raise NotImplementedError()\n\n @abstractmethod\n def evaluate(self, *, model, model_type, dataset, run_id, evaluator_config, **kwargs):\n \"\"\"\n The abstract API to log metrics and artifacts, and return evaluation results.\n\n :param model: A pyfunc model instance.\n :param model_type: A string describing the model type\n (e.g., ``\"regressor\"``, ``\"classifier\"``, …).\n :param dataset: An instance of `mlflow.models.evaluation.base._EvaluationDataset`\n containing features and labels (optional) for model evaluation.\n :param run_id: The ID of the MLflow Run to which to log results.\n :param evaluator_config: A dictionary of additional configurations for\n the evaluator.\n :param kwargs: For forwards compatibility, a placeholder for additional arguments that\n may be added to the evaluation interface in the future.\n :return: An :py:class:`mlflow.models.EvaluationResult` instance containing\n evaluation results.\n \"\"\"\n raise NotImplementedError()\n\n\ndef list_evaluators():\n \"\"\"\n Return a name list for all available Evaluators.\n \"\"\"\n # import _model_evaluation_registry inside function to avoid circuit importing\n from mlflow.models.evaluation.evaluator_registry import _model_evaluation_registry\n\n return list(_model_evaluation_registry._registry.keys())\n\n\n@contextmanager\ndef _start_run_or_reuse_active_run():\n \"\"\"\n A manager context return:\n - If there's an active run, return the active run id.\n - otherwise start a mflow run with the specified run_id,\n if specified run_id is None, start a new run.\n \"\"\"\n active_run = mlflow.active_run()\n if not active_run:\n # Note `mlflow.start_run` throws if `run_id` is not found.\n with mlflow.start_run() as run:\n yield run.info.run_id\n else:\n yield active_run.info.run_id\n\n\ndef _normalize_evaluators_and_evaluator_config_args(\n evaluators,\n evaluator_config,\n):\n from mlflow.models.evaluation.evaluator_registry import _model_evaluation_registry\n\n def check_nesting_config_dict(_evaluator_name_list, _evaluator_name_to_conf_map):\n return isinstance(_evaluator_name_to_conf_map, dict) and all(\n k in _evaluator_name_list and isinstance(v, dict)\n for k, v in _evaluator_name_to_conf_map.items()\n )\n\n if evaluators is None:\n evaluator_name_list = list(_model_evaluation_registry._registry.keys())\n if len(evaluator_name_list) > 1:\n _logger.warning(\n f\"Multiple registered evaluators are found {evaluator_name_list} and \"\n \"they will all be used in evaluation if they support the specified model type. \"\n \"If you want to evaluate with one evaluator, specify the `evaluator` argument \"\n \"and optionally specify the `evaluator_config` argument.\"\n )\n if evaluator_config is not None:\n conf_dict_value_error = ValueError(\n \"If `evaluators` argument is None, all available evaluators will be used. \"\n \"If only the default evaluator is available, the `evaluator_config` argument is \"\n \"interpreted as the config dictionary for the default evaluator. Otherwise, the \"\n \"`evaluator_config` argument must be a dictionary mapping each evaluator's name \"\n \"to its own evaluator config dictionary.\"\n )\n if evaluator_name_list == [\"default\"]:\n if not isinstance(evaluator_config, dict):\n raise conf_dict_value_error\n elif \"default\" not in evaluator_config:\n evaluator_name_to_conf_map = {\"default\": evaluator_config}\n else:\n evaluator_name_to_conf_map = evaluator_config\n else:\n if not check_nesting_config_dict(evaluator_name_list, evaluator_config):\n raise conf_dict_value_error\n evaluator_name_to_conf_map = evaluator_config\n else:\n evaluator_name_to_conf_map = {}\n elif isinstance(evaluators, str):\n if not (evaluator_config is None or isinstance(evaluator_config, dict)):\n raise ValueError(\n \"If `evaluators` argument is the name of an evaluator, evaluator_config must be \"\n \"None or a dict containing config items for the evaluator.\"\n )\n evaluator_name_list = [evaluators]\n evaluator_name_to_conf_map = {evaluators: evaluator_config}\n elif isinstance(evaluators, list):\n if evaluator_config is not None:\n if not check_nesting_config_dict(evaluators, evaluator_config):\n raise ValueError(\n \"If `evaluators` argument is an evaluator name list, evaluator_config \"\n \"must be a dict contains mapping from evaluator name to individual \"\n \"evaluator config dict.\"\n )\n # Use `OrderedDict.fromkeys` to deduplicate elements but keep elements order.\n evaluator_name_list = list(OrderedDict.fromkeys(evaluators))\n evaluator_name_to_conf_map = evaluator_config or {}\n else:\n raise ValueError(\n \"`evaluators` argument must be None, an evaluator name string, or a list of \"\n \"evaluator names.\"\n )\n\n return evaluator_name_list, evaluator_name_to_conf_map\n\n\n_last_failed_evaluator = None\n\n\ndef _get_last_failed_evaluator():\n \"\"\"\n Return the evaluator name of the last failed evaluator when calling `evalaute`.\n This can be used to check which evaluator fail when `evaluate` API fail.\n \"\"\"\n return _last_failed_evaluator\n\n\ndef _evaluate(\n *, model, model_type, dataset, run_id, evaluator_name_list, evaluator_name_to_conf_map\n):\n \"\"\"\n The public API \"evaluate\" will verify argument first, and then pass normalized arguments\n to the _evaluate method.\n \"\"\"\n # import _model_evaluation_registry and PyFuncModel inside function to avoid circuit importing\n from mlflow.models.evaluation.evaluator_registry import _model_evaluation_registry\n\n global _last_failed_evaluator\n _last_failed_evaluator = None\n\n client = mlflow.tracking.MlflowClient()\n model_uuid = model.metadata.model_uuid\n dataset._log_dataset_tag(client, run_id, model_uuid)\n\n eval_results = []\n for evaluator_name in evaluator_name_list:\n config = evaluator_name_to_conf_map.get(evaluator_name) or {}\n try:\n evaluator = _model_evaluation_registry.get_evaluator(evaluator_name)\n except MlflowException:\n _logger.warning(f\"Evaluator '{evaluator_name}' is not registered.\")\n continue\n\n _last_failed_evaluator = evaluator_name\n if evaluator.can_evaluate(model_type=model_type, evaluator_config=config):\n _logger.info(f\"Evaluating the model with the {evaluator_name} evaluator.\")\n result = evaluator.evaluate(\n model=model,\n model_type=model_type,\n dataset=dataset,\n run_id=run_id,\n evaluator_config=config,\n )\n eval_results.append(result)\n\n _last_failed_evaluator = None\n\n if len(eval_results) == 0:\n raise ValueError(\n \"The model could not be evaluated by any of the registered evaluators, please \"\n \"verify that the model type and other configs are set correctly.\"\n )\n\n merged_eval_result = EvaluationResult(dict(), dict())\n for eval_result in eval_results:\n merged_eval_result.metrics.update(eval_result.metrics)\n merged_eval_result.artifacts.update(eval_result.artifacts)\n\n return merged_eval_result\n\n\n@experimental\ndef evaluate(\n model: Union[str, \"mlflow.pyfunc.PyFuncModel\"],\n data,\n *,\n targets,\n model_type: str,\n dataset_name=None,\n dataset_path=None,\n feature_names: list = None,\n evaluators=None,\n evaluator_config=None,\n):\n \"\"\"\n Evaluate a PyFunc model on the specified dataset using one or more specified ``evaluators``, and\n log resulting metrics & artifacts to MLflow Tracking. For additional overview information, see\n :ref:`the Model Evaluation documentation <model-evaluation>`.\n\n Default Evaluator behavior:\n - The default evaluator, which can be invoked with ``evaluators=\"default\"`` or\n ``evaluators=None``, supports the ``\"regressor\"`` and ``\"classifier\"`` model types.\n It generates a variety of model performance metrics, model performance plots, and\n model explanations.\n\n - For both the ``\"regressor\"`` and ``\"classifier\"`` model types, the default evaluator\n generates model summary plots and feature importance plots using\n `SHAP <https://shap.readthedocs.io/en/latest/index.html>`_.\n\n - For regressor models, the default evaluator additionally logs:\n - **metrics**: example_count, mean_absolute_error, mean_squared_error,\n root_mean_squared_error, sum_on_label, mean_on_label, r2_score, max_error,\n mean_absolute_percentage_error.\n\n - For binary classifiers, the default evaluator additionally logs:\n - **metrics**: true_negatives, false_positives, false_negatives, true_positives, recall,\n precision, f1_score, accuracy, example_count, log_loss, roc_auc, precision_recall_auc.\n - **artifacts**: lift curve plot, precision-recall plot, ROC plot.\n\n - For multiclass classifiers, the default evaluator additionally logs:\n - **metrics**: accuracy, example_count, f1_score_micro, f1_score_macro, log_loss\n - **artifacts**: A CSV file for \"per_class_metrics\" (per-class metrics includes\n true_negatives/false_positives/false_negatives/true_positives/recall/precision/roc_auc,\n precision_recall_auc), precision-recall merged curves plot, ROC merged curves plot.\n\n - The logged MLflow metric keys are constructed using the format:\n ``{metric_name}_on_{dataset_name}``. Any preexisting metrics with the same name are\n overwritten.\n\n - The metrics/artifacts listed above are logged to the active MLflow run.\n If no active run exists, a new MLflow run is created for logging these metrics and\n artifacts.\n\n - Additionally, information about the specified dataset - hash, name (if specified), path\n (if specified), and the UUID of the model that evaluated it - is logged to the\n ``mlflow.datasets`` tag.\n\n - The available ``evaluator_config`` options for the default evaluator include:\n - **log_model_explainability**: A boolean value specifying whether or not to log model\n explainability insights, default value is True.\n - **explainability_algorithm**: A string to specify the SHAP Explainer algorithm for model\n explainability. Supported algorithm includes: 'exact', 'permutation', 'partition'.\n If not set, ``shap.Explainer`` is used with the \"auto\" algorithm, which chooses the best\n Explainer based on the model.\n - **explainability_nsamples**: The number of sample rows to use for computing model\n explainability insights. Default value is 2000.\n - **max_classes_for_multiclass_roc_pr**:\n For multiclass classification tasks, the maximum number of classes for which to log\n the per-class ROC curve and Precision-Recall curve. If the number of classes is\n larger than the configured maximum, these curves are not logged.\n\n - Limitations of evaluation dataset:\n - For classification tasks, dataset labels are used to infer the total number of classes.\n - For binary classification tasks, the negative label value must be 0 or -1 or False, and\n the positive label value must be 1 or True.\n\n - Limitations of metrics/artifacts computation:\n - For classification tasks, some metric and artifact computations require the model to\n output class probabilities. Currently, for scikit-learn models, the default evaluator\n calls the ``predict_proba`` method on the underlying model to obtain probabilities. For\n other model types, the default evaluator does not compute metrics/artifacts that require\n probability outputs.\n\n - Limitations of default evaluator logging model explainability insights:\n - The ``shap.Explainer`` ``auto`` algorithm uses the ``Linear`` explainer for linear models\n and the ``Tree`` explainer for tree models. Because SHAP's ``Linear`` and ``Tree``\n explainers do not support multi-class classification, the default evaluator falls back to\n using the ``Exact`` or ``Permutation`` explainers for multi-class classification tasks.\n - Logging model explainability insights is not currently supported for PySpark models.\n - The evaluation dataset label values must be numeric or boolean, all feature values\n must be numeric, and each feature column must only contain scalar values.\n\n :param model: A pyfunc model instance, or a URI referring to such a model.\n\n :param data: One of the following:\n\n - A numpy array or list of evaluation features, excluding labels.\n\n - A Pandas DataFrame or Spark DataFrame, containing evaluation features and\n labels. If ``feature_names`` argument not specified, all columns are regarded\n as feature columns. Otherwise, only column names present in ``feature_names``\n are regarded as feature columns.\n\n :param targets: If ``data`` is a numpy array or list, a numpy array or list of evaluation\n labels. If ``data`` is a DataFrame, the string name of a column from ``data``\n that contains evaluation labels.\n\n :param model_type: A string describing the model type. The default evaluator\n supports ``\"regressor\"`` and ``\"classifier\"`` as model types.\n\n :param dataset_name: (Optional) The name of the dataset, must not contain double quotes (``“``).\n The name is logged to the ``mlflow.datasets`` tag for lineage tracking\n purposes. If not specified, the dataset hash is used as the dataset name.\n\n :param dataset_path: (Optional) The path where the data is stored. Must not contain double\n quotes (``“``). If specified, the path is logged to the ``mlflow.datasets``\n tag for lineage tracking purposes.\n\n :param feature_names: (Optional) If the ``data`` argument is a feature data numpy array or list,\n ``feature_names`` is a list of the feature names for each feature. If\n ``None``, then the ``feature_names`` are generated using the format\n ``feature_{feature_index}``. If the ``data`` argument is a Pandas\n DataFrame or a Spark DataFrame, ``feature_names`` is a list of the names\n of the feature columns in the DataFrame. If ``None``, then all columns\n except the label column are regarded as feature columns.\n\n :param evaluators: The name of the evaluator to use for model evaluation, or a list of\n evaluator names. If unspecified, all evaluators capable of evaluating the\n specified model on the specified dataset are used. The default evaluator\n can be referred to by the name ``\"default\"``. To see all available\n evaluators, call :py:func:`mlflow.models.list_evaluators`.\n\n :param evaluator_config: A dictionary of additional configurations to supply to the evaluator.\n If multiple evaluators are specified, each configuration should be\n supplied as a nested dictionary whose key is the evaluator name.\n\n :return: An :py:class:`mlflow.models.EvaluationResult` instance containing\n evaluation results.\n \"\"\"\n from mlflow.pyfunc import PyFuncModel\n\n if isinstance(model, str):\n model = mlflow.pyfunc.load_model(model)\n elif isinstance(model, PyFuncModel):\n pass\n else:\n raise ValueError(\n \"The model argument must be a string URI referring to an MLflow model or \"\n \"an instance of `mlflow.pyfunc.PyFuncModel`.\"\n )\n\n (\n evaluator_name_list,\n evaluator_name_to_conf_map,\n ) = _normalize_evaluators_and_evaluator_config_args(evaluators, evaluator_config)\n\n dataset = EvaluationDataset(\n data,\n targets=targets,\n name=dataset_name,\n path=dataset_path,\n feature_names=feature_names,\n )\n\n with _start_run_or_reuse_active_run() as run_id:\n return _evaluate(\n model=model,\n model_type=model_type,\n dataset=dataset,\n run_id=run_id,\n evaluator_name_list=evaluator_name_list,\n evaluator_name_to_conf_map=evaluator_name_to_conf_map,\n )\n"
] |
[
[
"pandas.util.hash_pandas_object",
"numpy.array",
"numpy.array_equal"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
MajesticKhan/adanet
|
[
"574d3dc8b3a531830f6870ffa223317890c20d2e"
] |
[
"adanet/core/estimator_distributed_test.py"
] |
[
"\"\"\"Test AdaNet estimator cluster training support.\n\nCopyright 2019 The AdaNet Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport copy\nimport itertools\nimport json\nimport os\nimport shutil\nimport socket\nimport subprocess\nimport sys\nimport time\n\nfrom absl import flags\nfrom absl import logging\nfrom absl.testing import parameterized\nfrom adanet.core.timer import _CountDownTimer\nimport tensorflow as tf\n\n# Maximum number of characters to log per process.\n# NOTE: The full process output is written to disk.\nMAX_OUTPUT_CHARS = 15000\n\n# A process. name is a string identifying the process in logs. stderr is a file\n# object of the process's stderr.\n_ProcessInfo = collections.namedtuple(\"_ProcessInfo\",\n [\"name\", \"popen\", \"stderr\"])\n\n\ndef _create_task_process(task_type, task_index, estimator_type,\n placement_strategy, tf_config, model_dir):\n \"\"\"Creates a process for a single estimator task.\n\n Args:\n task_type: 'chief', 'worker' or 'ps'.\n task_index: The index of the task within the cluster.\n estimator_type: The estimator type to train. 'estimator' or 'autoensemble'.\n placement_strategy: The distributed placement strategy.\n tf_config: Dictionary representation of the TF_CONFIG environment variable.\n This method creates a copy as to not mutate the input dict.\n model_dir: The Estimator's model directory.\n\n Returns:\n A _ProcessInfo namedtuple of the running process. The stderr field of this\n tuple must be closed by the caller once the process ends.\n \"\"\"\n\n process_name = \"%s_%s\" % (task_type, task_index)\n args = [\"python\", \"adanet/core/estimator_distributed_test_runner.py\"]\n args.append(\"--estimator_type={}\".format(estimator_type))\n args.append(\"--placement_strategy={}\".format(placement_strategy))\n # Log everything to stderr.\n args.append(\"--stderrthreshold=info\")\n args.append(\"--model_dir={}\".format(model_dir))\n logging.info(\"Spawning %s process: %s\", process_name, \" \".join(args))\n stderr_filename = os.path.join(model_dir, \"%s_stderr.txt\" % process_name)\n logging.info(\"Logging to %s\", model_dir)\n stderr_file = open(stderr_filename, \"w+\")\n tf_config = copy.deepcopy(tf_config)\n tf_config[\"task\"][\"type\"] = task_type\n tf_config[\"task\"][\"index\"] = task_index\n json_tf_config = json.dumps(tf_config)\n env = os.environ.copy()\n # Allow stderr to be viewed before the process ends.\n env[\"PYTHONUNBUFFERED\"] = \"1\"\n env[\"TF_CPP_MIN_LOG_LEVEL\"] = \"0\"\n env[\"TF_CONFIG\"] = json_tf_config\n # Change gRPC polling strategy to prevent blocking forever.\n # See https://github.com/tensorflow/tensorflow/issues/17852.\n env[\"GRPC_POLL_STRATEGY\"] = \"poll\"\n popen = subprocess.Popen(args, stderr=stderr_file, env=env)\n return _ProcessInfo(process_name, popen, stderr_file)\n\n\ndef _pick_unused_port():\n \"\"\"Returns a free port on localhost.\"\"\"\n\n for family in (socket.AF_INET6, socket.AF_INET):\n try:\n sock = socket.socket(family, socket.SOCK_STREAM)\n sock.bind((\"\", 0)) # Passing port '0' binds to a free port on localhost.\n port = sock.getsockname()[1]\n sock.close()\n return port\n except socket.error:\n continue\n raise socket.error\n\n\nclass EstimatorDistributedTrainingTest(parameterized.TestCase,\n tf.test.TestCase):\n \"\"\"Tests distributed training.\"\"\"\n\n def setUp(self):\n super(EstimatorDistributedTrainingTest, self).setUp()\n flags.FLAGS(sys.argv)\n # Setup and cleanup test directory.\n self.test_subdirectory = os.path.join(flags.FLAGS.test_tmpdir, self.id())\n shutil.rmtree(self.test_subdirectory, ignore_errors=True)\n os.makedirs(self.test_subdirectory)\n\n def _wait_for_processes(self, wait_processes, kill_processes, timeout_secs):\n \"\"\"Waits until all `wait_processes` finish, then kills `kill_processes`.\n\n Fails an assert if a process in `wait_processes` finishes unsuccessfully.\n The processes in `kill_processes` are assumed to never finish so they are\n killed.\n\n Args:\n wait_processes: A list of _ProcessInfo tuples. This function will wait for\n each to finish.\n kill_processes: A list of _ProcessInfo tuples. Each will be killed once\n every process in `wait_processes` is finished.\n timeout_secs: Seconds to wait before timing out and terminating processes.\n\n Returns:\n A list of strings, each which is a string of the stderr of a wait process.\n\n Raises:\n Exception: When waiting for tasks to finish times out.\n \"\"\"\n\n timer = _CountDownTimer(timeout_secs)\n wait_process_stderrs = [None] * len(wait_processes)\n finished_wait_processes = set()\n while len(finished_wait_processes) < len(wait_processes):\n if timer.secs_remaining() == 0:\n logging.error(\"Timed out! Outputting logs of unfinished processes:\")\n for i, wait_process in enumerate(wait_processes):\n if i in finished_wait_processes:\n continue\n wait_process.stderr.seek(0)\n wait_process_stderrs[i] = wait_process.stderr.read()\n logging.info(\"stderr for incomplete %s (last %d chars): %s\\n\",\n wait_process.name, MAX_OUTPUT_CHARS,\n wait_process.stderr.read()[-MAX_OUTPUT_CHARS:])\n raise Exception(\"Timed out waiting for tasks to complete.\")\n for i, wait_process in enumerate(wait_processes):\n if i in finished_wait_processes:\n continue\n ret_code = wait_process.popen.poll()\n if ret_code is None:\n continue\n logging.info(\"%s finished\", wait_process.name)\n wait_process.stderr.seek(0)\n wait_process_stderrs[i] = wait_process.stderr.read()\n logging.info(\"stderr for %s (last %d chars): %s\\n\", wait_process.name,\n MAX_OUTPUT_CHARS,\n wait_process_stderrs[i][-MAX_OUTPUT_CHARS:])\n self.assertEqual(0, ret_code)\n finished_wait_processes.add(i)\n for kill_process in kill_processes:\n ret_code = kill_process.popen.poll()\n # Kill processes should not end until we kill them.\n # If it returns early, note the return code.\n self.assertIsNone(ret_code)\n # Delay between polling loops.\n time.sleep(0.25)\n logging.info(\"All wait processes finished\")\n for i, kill_process in enumerate(kill_processes):\n # Kill each kill process.\n kill_process.popen.kill()\n kill_process.popen.wait()\n kill_process.stderr.seek(0)\n logging.info(\"stderr for %s (last %d chars): %s\\n\", kill_process.name,\n MAX_OUTPUT_CHARS,\n kill_process.stderr.read()[-MAX_OUTPUT_CHARS:])\n return wait_process_stderrs\n\n # pylint: disable=g-complex-comprehension\n @parameterized.named_parameters(\n itertools.chain(*[[\n {\n \"testcase_name\": \"{}_one_worker\".format(placement),\n \"placement_strategy\": placement,\n \"num_workers\": 1,\n \"num_ps\": 0,\n },\n {\n \"testcase_name\": \"{}_one_worker_one_ps\".format(placement),\n \"placement_strategy\": placement,\n \"num_workers\": 1,\n \"num_ps\": 1,\n },\n {\n \"testcase_name\": \"{}_two_workers_one_ps\".format(placement),\n \"placement_strategy\": placement,\n \"num_workers\": 2,\n \"num_ps\": 1,\n },\n {\n \"testcase_name\": \"{}_three_workers_three_ps\".format(placement),\n \"placement_strategy\": placement,\n \"num_workers\": 3,\n \"num_ps\": 3,\n },\n {\n \"testcase_name\": \"{}_five_workers_three_ps\".format(placement),\n \"placement_strategy\": placement,\n \"num_workers\": 5,\n \"num_ps\": 3,\n },\n {\n \"testcase_name\":\n \"autoensemble_{}_five_workers_three_ps\".format(placement),\n \"estimator\":\n \"autoensemble\",\n \"placement_strategy\":\n placement,\n \"num_workers\":\n 5,\n \"num_ps\":\n 3,\n },\n {\n \"testcase_name\":\n \"autoensemble_trees_multiclass_{}_five_workers_three_ps\"\n .format(placement),\n \"estimator\":\n \"autoensemble_trees_multiclass\",\n \"placement_strategy\":\n placement,\n \"num_workers\":\n 5,\n \"num_ps\":\n 3,\n },\n ] for placement in [\"replication\", \"round_robin\"]]))\n # pylint: enable=g-complex-comprehension\n def test_distributed_training(self,\n num_workers,\n num_ps,\n placement_strategy,\n estimator=\"estimator\"):\n \"\"\"Uses multiprocessing to simulate a distributed training environment.\"\"\"\n\n # Inspired by `tf.test.create_local_cluster`.\n worker_ports = [_pick_unused_port() for _ in range(num_workers)]\n ps_ports = [_pick_unused_port() for _ in range(num_ps)]\n ws_targets = [\"localhost:%s\" % port for port in worker_ports]\n ps_targets = [\"localhost:%s\" % port for port in ps_ports]\n\n # For details see:\n # https://www.tensorflow.org/api_docs/python/tf/estimator/train_and_evaluate\n tf_config = {\n \"cluster\": {\n # The chief is always worker 0.\n \"chief\": [ws_targets[0]],\n },\n \"task\": {\n \"type\": \"chief\",\n \"index\": 0\n },\n }\n\n # The chief is already worker 0.\n if len(ws_targets) > 1:\n tf_config[\"cluster\"][\"worker\"] = ws_targets[1:]\n if ps_targets:\n tf_config[\"cluster\"][\"ps\"] = ps_targets\n\n worker_processes = []\n ps_processes = []\n evaluator_processes = []\n\n model_dir = self.test_subdirectory\n\n # Chief\n worker_processes.append(\n _create_task_process(\"chief\", 0, estimator, placement_strategy,\n tf_config, model_dir))\n # Workers\n for i in range(len(ws_targets[1:])):\n worker_processes.append(\n _create_task_process(\"worker\", i, estimator, placement_strategy,\n tf_config, model_dir))\n # Parameter Servers (PS)\n for i in range(len(ps_targets)):\n ps_processes.append(\n _create_task_process(\"ps\", i, estimator, placement_strategy,\n tf_config, model_dir))\n # Evaluator\n evaluator_processes.append(\n _create_task_process(\"evaluator\", 0, estimator, placement_strategy,\n tf_config, model_dir))\n\n # Run processes.\n try:\n # NOTE: Parameter servers do not shut down on their own.\n self._wait_for_processes(\n worker_processes + evaluator_processes,\n kill_processes=ps_processes,\n timeout_secs=500)\n finally:\n for process in worker_processes + ps_processes + evaluator_processes:\n try:\n process.popen.kill()\n except OSError:\n pass # It's OK (and expected) if the process already exited.\n process.stderr.close()\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
] |
[
[
"tensorflow.test.main"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xSakix/AI_playground
|
[
"17587583ecfc8fd9e92d9d3f643da6d37ac5cffd",
"17587583ecfc8fd9e92d9d3f643da6d37ac5cffd",
"17587583ecfc8fd9e92d9d3f643da6d37ac5cffd",
"17587583ecfc8fd9e92d9d3f643da6d37ac5cffd"
] |
[
"reinforcement_learning/market/market_env_random_agent.py",
"reinforcement_learning/crypto_market_regressor/choose_best_15min_data.py",
"reinforcement_learning/crypto_market/crypto_sklearnclass_agent.py",
"price_seq.py"
] |
[
"from reinforcement_learning.market.random_agent import RandomAgent\n\nimport sys\n\nsys.path.insert(0, '../../../etf_data')\nfrom etf_data_loader import load_all_data_from_file2\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nimport seaborn as sns\n\n\ndef gen_random_date(year_low, year_high):\n y = np.random.randint(year_low, year_high)\n m = np.random.randint(1, 12)\n d = np.random.randint(1, 28)\n return datetime(year=y, month=m, day=d)\n\n\ndef get_data_random_dates(df_adj_close, min_year, max_year):\n rand_start = gen_random_date(min_year, max_year)\n rand_end = gen_random_date(min_year, max_year)\n if rand_start > rand_end:\n tmp = rand_start\n rand_start = rand_end\n rand_end = tmp\n data = df_adj_close[df_adj_close['date'] > str(rand_start)]\n data = data[data['date'] < str(rand_end)]\n\n return data\n\n\ndef clean_data(df_adj_close, ticket):\n top = df_adj_close.index.max()\n\n for index in df_adj_close.index:\n if df_adj_close.loc[index, ticket] == 0.:\n for i in range(index, top + 1):\n if df_adj_close.loc[i, ticket] > 0.:\n df_adj_close.loc[index, ticket] = df_adj_close.loc[i, ticket]\n break\n return df_adj_close\n\n\nstart_date = '1993-01-01'\nend_date = '2018-01-01'\nprefix = 'mil_'\nranked = pd.read_csv('../../../buy_hold_simulation/evaluation_results/mil_evaluation_result_1.csv')\ntickets = ranked.sort_values(by='bayes_interval_high',ascending=False)['ticket'].tolist()[:10]\nprint(tickets)\ndf_adj_close = load_all_data_from_file2(prefix + 'etf_data_adj_close.csv', start_date, end_date)\n\nnp.warnings.filterwarnings('ignore')\n\niter = 0\nscores = []\n\nmax = None\n\nfound = {}\n\n\nwhile len(found) < 100:\n ticket = 'ANX.MI'\n data = get_data_random_dates(df_adj_close,1993,2018)\n data = data[[ticket]]\n if len(data) < 30:\n continue\n\n agent = RandomAgent(ticket)\n agent.invest(data, window=30)\n scores.append(agent.score)\n if max is None:\n max = agent\n if max.score < agent.score:\n max = agent\n\n if agent.score > 0:\n found[agent.score] = agent\n\n # print('\\r %d : %d : %d : %f : %s' % (iter, agent.score, len(found), frac,ticket), end='')\n print('\\r %d : %d : %d : %s' % (iter, agent.score, len(found), ticket), end='')\n iter += 1\n\nprint('\\n scores:', found.keys())\n\nx_train = None\ny_train = None\nfor score in found.keys():\n # print(found[score].state.shape)\n if x_train is None:\n x_train = found[score].state\n else:\n x_train = np.concatenate((x_train,found[score].state))\n if y_train is None:\n y_train= found[score].r_actions\n else:\n y_train = np.concatenate((y_train,found[score].r_actions))\n\n# print(x_train.shape)\n\nx = x_train\nprint(x.shape)\ny = y_train\nprint(y.shape)\n\nnp.save('x.npy', x)\nnp.save('y.npy', y)\n\ndf = pd.DataFrame(columns=['score', 'number_of_actions', 'ror'])\n\nfor key in list(found.keys()):\n num = found[key].actions.count('S') + found[key].actions.count('B')\n ror = found[key].ror_history[-1]\n df = df.append({'score': key, 'number_of_actions': num, 'ror': ror}, ignore_index=True)\n\nprint(df.sort_values(by='ror', ascending=False))\n# print('median actions = ', df['number_of_actions'].median())\n#\n# m = int(df['score'].loc[0])\n# print('\\r chosen key:', m, end='')\n# while True:\n# try:\n# median_chaos = found[m]\n# break\n# except:\n# if m < 0:\n# exit(1)\n# m -= 1\n# print('\\r chosen key:', m, end='')\n#\n# agent = max\n# print('\\n Max score:', max.score)\n#\n# sns.kdeplot(scores)\n# plt.show()\n#\n# plt.plot(agent.ror_history)\n# plt.plot(median_chaos.ror_history)\n# plt.plot(data[[ticket]].pct_change().cumsum().as_matrix())\n# plt.legend(['ror', 'median chaos ror', 'benchmark'])\n# plt.title('chaos results of 2/3 of data')\n# plt.show()\n#\n# chaos_counts = [agent.actions.count('S'),\n# median_chaos.actions.count('S'),\n# agent.actions.count('B'),\n# median_chaos.actions.count('B'),\n# agent.actions.count('H'),\n# median_chaos.actions.count('H'), ]\n# print('\\n[S, Sm, B, Bm, H, Hm]\\n', chaos_counts)\n# # plt.bar(range(6), chaos_counts, width=1, align='center')\n# # plt.xticks(['S', 'Sm', 'B', 'Bm', 'H', 'Hm'])\n# # plt.show()\n",
"import os\nfrom datetime import datetime\n\nimport sys\n\nfrom reinforcement_learning.crypto_market.util import State\nfrom reinforcement_learning.crypto_market_regressor.crypto_trader_regression_agent import CryptoRegressionAgent\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.warnings.filterwarnings('ignore')\n\n\ndef find_best_models(dir_models='models_btc_eur/', debug=False):\n df_adj_close = pd.read_csv('/home/martin/data/coinbaseEUR.csv')\n data = df_adj_close['BTC-EUR']\n\n print(data.head(2))\n print(data.tail(2))\n\n models = [dir_models + f for f in sorted(os.listdir(dir_models))]\n print(models)\n\n max = -99999999.\n max_ror = -99999999.\n max_agent = None\n best_ror_agent = None\n\n for model in models:\n agent = CryptoRegressionAgent('BTC-EUR', dir_models=model, coef=1.)\n agent.invest(data, window=30, debug=debug)\n print('testing:', model, ' => score:', agent.score, '=> ror:', agent.ror_history[-1], ' mean ror => ',\n np.mean(agent.ror_history))\n if max < agent.score:\n max = agent.score\n max_agent = agent\n if max_ror < agent.ror_history[-1]:\n max_ror = agent.ror_history[-1]\n best_ror_agent = agent\n\n return data, max_agent, best_ror_agent\n\n\ndef score_models(data, dir_models='models_btc_eur/', ticket='BTC-EUR'):\n result_score = {}\n result_ror = {}\n\n print(data.head(2))\n print(data.tail(2))\n\n models = sorted(os.listdir(dir_models))\n\n for model in models:\n agent = CryptoRegressionAgent(ticket, dir_models=dir_models + str(model), coef=1.)\n agent.invest(data, window=30)\n print('testing:', agent.model, ' => score:', agent.score)\n result_score[agent.model] = agent.score\n result_ror[agent.model] = agent.ror_history[-1]\n\n return result_score, result_ror\n\n\ndef rank_by_score(dir_models):\n ranked_by_score = {}\n ranked_by_ror = {}\n ticket = 'BTC-EUR'\n\n df_adj_close = pd.read_csv('/home/martin/data/coinbaseEUR.csv')\n df_adj_close = df_adj_close[ticket]\n\n for it in range(100):\n\n print('-' * 80)\n print(it)\n print('-' * 80)\n\n b1 = np.random.randint(0, len(df_adj_close))\n b2 = np.random.randint(0, len(df_adj_close))\n if b1 > b2:\n data = df_adj_close[b2:b1]\n else:\n data = df_adj_close[b1:b2]\n\n while len(data) < 30:\n b1 = np.random.randint(0, len(df_adj_close))\n b2 = np.random.randint(0, len(df_adj_close))\n if b1 > b2:\n data = df_adj_close[b2:b1]\n else:\n data = df_adj_close[b1:b2]\n\n print(b1, ' - ', b2)\n\n result_score, result_ror = score_models(data, ticket=ticket, dir_models=dir_models)\n for key in result_score.keys():\n if key in ranked_by_score.keys():\n ranked_by_score[key].append(result_score[key])\n ranked_by_ror[key].append(result_ror[key])\n else:\n ranked_by_score[key] = [result_score[key]]\n ranked_by_ror[key] = [result_ror[key]]\n\n df = pd.DataFrame(columns=['model', 'score', 'ror'])\n for key in ranked_by_score.keys():\n median_score = np.mean(np.array(ranked_by_score[key]))\n median_ror = np.mean(np.array(ranked_by_ror[key]))\n df = df.append({'model': key, 'score': median_score, 'ror': median_ror}, ignore_index=True)\n\n best_by_score = df.sort_values(by=['score'], ascending=False).head(1)\n print(best_by_score)\n best_by_ror = df.sort_values(by=['ror'], ascending=False).head(1)\n print(best_by_ror)\n\n result_list = best_by_score['model'].tolist()\n result_list.extend(best_by_ror['model'].tolist())\n\n\n# def best_of_best(model_dir='best_models_btc_eur/', debug=False):\n# start_date = '2018-04-01'\n# # end_date = '2018-05-01'\n# # start_date = '2018-07-01'\n# end_date = '2018-09-14'\n#\n# ticket = 'BTC-EUR'\n# best_dir = model_dir\n#\n# data, max_agent, best_ror_agent = find_best_models(start_date, end_date, ticket=ticket, dir_models=best_dir,\n# debug=debug)\n# data = data[ticket].reset_index(drop=True).fillna(method=\"bfill\")\n# print(data.head(2))\n# print(data.tail(2))\n#\n# window = 30\n# states = State(window, data)\n# print(states.bench[0])\n# print(states.bench[1])\n# print(states.bench[-2])\n# print(states.bench[-1])\n# print(len(data) - window)\n#\n# plt.plot(states.bench[window:], color='black')\n# plt.plot(max_agent.ror_history, color='red')\n# plt.plot(best_ror_agent.ror_history, color='blue')\n# plt.legend(['bench', max_agent.model, best_ror_agent.model])\n# plt.show()\n#\n# print('best(score):', max_agent.model)\n# print('ror:', max_agent.ror_history[-1])\n# print('portfolio:', max_agent.history[-1])\n#\n# print('best(ror):', best_ror_agent.model)\n# print('ror:', best_ror_agent.ror_history[-1])\n# print('portfolio:', best_ror_agent.history[-1])\n\n\nif __name__ == \"__main__\":\n # rank_by_score('/home/martin/model/')\n data, max_agent, best_ror_agent = find_best_models(dir_models='/home/martin/model/')\n bench = data.apply(lambda x: (x / data[0]) - 1)\n\n print('best(score):', max_agent.model)\n print('ror:', max_agent.ror_history[-1])\n print('portfolio:', max_agent.history[-1])\n\n print('best(ror):', best_ror_agent.model)\n print('ror:', best_ror_agent.ror_history[-1])\n print('portfolio:', best_ror_agent.history[-1])\n\n # df_adj_close = pd.read_csv('/home/martin/data/coinbaseEUR.csv')\n # print(df_adj_close['BTC-EUR'].head())\n",
"import os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, VotingClassifier, BaggingClassifier, \\\n GradientBoostingClassifier\nfrom sklearn.externals import joblib\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics.classification import classification_report, accuracy_score\nfrom sklearn.mixture import BayesianGaussianMixture, GaussianMixture\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.naive_bayes import GaussianNB, BernoulliNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neural_network import MLPClassifier, BernoulliRBM\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import Binarizer\nfrom sklearn.svm import SVC, LinearSVC, NuSVC\nfrom sklearn.tree import DecisionTreeClassifier\n\n\ndef sgd_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...SGDClassifier')\n clf = SGDClassifier()\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n\n joblib.dump(clf, dir_models + ticket + '_sgd_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef qda_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...QuadraticDiscriminantAnalysis')\n clf = QuadraticDiscriminantAnalysis()\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n\n joblib.dump(clf, dir_models + ticket + '_qda_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef adaboost_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...Ada')\n clf = AdaBoostClassifier()\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_adaboost_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef mlp_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...MLP')\n clf = MLPClassifier(early_stopping=True)\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_mlp_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef random_forrest(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...RandomForest')\n clf = RandomForestClassifier(verbose=False, warm_start=True)\n print('training...')\n clf.fit(x, y)\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_random_forrest_' + str(id) + '.pkl')\n return clf.score(x_test, y_test)\n\n\ndef decision_tree(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...decision tree')\n clf = DecisionTreeClassifier()\n print('training...')\n clf.fit(x, y)\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_decission_tree_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef voting_random_forrest(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...voting RandomForest')\n estimators = [(str(idd), RandomForestClassifier()) for idd in range(100)]\n clf = VotingClassifier(estimators=estimators)\n print('training...')\n clf.fit(x, y)\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_voting_rand_forest_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef voting_decision_tree(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...Voting decision tree')\n estimators = [(str(idd), DecisionTreeClassifier()) for idd in range(100)]\n clf = VotingClassifier(estimators=estimators, voting='soft')\n print('training...')\n clf.fit(x, y)\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_voting_dectree_' + str(id) + '.pkl')\n\n return accuracy_score(y_test, predicted)\n\n\ndef gaussnb_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...GaussianNB')\n clf = GaussianNB()\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n score = accuracy_score(y_test, predicted)\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_gausianNB_' + str(id) + '.pkl')\n\n return score\n\n\ndef kneighbors_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...KNeighbors')\n clf = KNeighborsClassifier(3)\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_kneighbors_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef bernoulli_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...BernoulliNB')\n clf = BernoulliNB(binarize=True)\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_bernoulli_' + str(id) + '.pkl')\n return clf.score(x_test, y_test)\n\n\ndef bayes_gauss_classifier(dir_models, ticket, x, x_test, y, y_test):\n # GaussianMixture\n print('getting model...BayesianGaussianMixture')\n clf = BayesianGaussianMixture(n_components=3)\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_bayesian_gaussian_mixture_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef gaussmix_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...GaussianMixture')\n clf = GaussianMixture(n_components=3)\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_gaussian_mixture_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef linearsvc_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...linear svc')\n clf = LinearSVC()\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_linear_svc_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef svc_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...SVC')\n clf = SVC()\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_svc_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\ndef nusvc_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...NuSVC')\n clf = NuSVC(nu=0.8)\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_nusvc_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\ndef bagging_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...Bagging')\n clf = BaggingClassifier()\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_bag_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\ndef gradient_classifier(dir_models, ticket, x, x_test, y, y_test):\n print('getting model...GBC')\n clf = GradientBoostingClassifier(n_estimators=1000)\n\n print('training...')\n clf.fit(x, y)\n\n print('predicting...')\n predicted = clf.predict(x_test)\n print(classification_report(y_test, predicted))\n\n id = len(os.listdir(dir_models))\n joblib.dump(clf, dir_models + ticket + '_gbc_' + str(id) + '.pkl')\n\n return clf.score(x_test, y_test)\n\n\ndef run_learning(dir_data='data_btc_eur/', dir_models=None):\n if dir_models is None:\n models = [d for d in os.listdir('.') if d.startswith('models_btc_eur')]\n dir_models = 'models_btc_eur_' + str(len(models) + 1) + '/'\n\n if not os.path.isdir(dir_models):\n print('creating dir...' + dir_models)\n os.makedirs(dir_models)\n\n ticket = 'BTC_EUR'\n\n print('loading data...')\n x = np.load(dir_data + 'x.npy')\n if len(x.shape) == 1:\n transform = lambda x: x.replace('array', '').replace('(', '').replace(')', '').replace('[', '').replace(']', '')\n x = np.array([np.fromstring(transform(xx), sep=',') for xx in x])\n\n print(x.shape)\n x = np.nan_to_num(x)\n\n y_orig = np.load(dir_data + 'y.npy')\n\n print('reshaping data...')\n if len(x.shape) > 2:\n if x.shape[2] == 1:\n x = np.reshape(x, (x.shape[0], x.shape[1] * x.shape[2]))\n else:\n x = np.reshape(x, (x.shape[0] * x.shape[1], x.shape[2]))\n print(x.shape)\n\n if x.shape[1] == 7:\n x = x[:, 2:7]\n\n print(x.shape)\n\n print('min:', np.min(x))\n print('max:', np.max(x))\n\n labels = ['ror', 'bench', 'lowerb', 'mean', 'median', 'higherb']\n\n if len(y_orig.shape) > 1:\n y = y_orig.reshape(y_orig.shape[0] * y_orig.shape[1])\n else:\n y = y_orig\n print('y_orig:', y.shape)\n\n unique, counts = np.unique(y_orig, return_counts=True)\n print(dict(zip(unique, counts)))\n\n print('spliting data...')\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=2)\n\n result = []\n\n # result.append(decision_tree(dir_models, ticket, x, x_test, y, y_test))\n result.append(random_forrest(dir_models, ticket, x, x_test, y, y_test))\n # result.append(voting_random_forrest(dir_models, ticket, x, x_test, y, y_test))\n # result.append(voting_decision_tree(dir_models, ticket, x, x_test, y, y_test))\n # result.append(gaussnb_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(kneighbors_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(mlp_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(adaboost_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(qda_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(sgd_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(bernoulli_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(bayes_gauss_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(gaussmix_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(linearsvc_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(svc_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(nusvc_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(bagging_classifier(dir_models, ticket, x, x_test, y, y_test))\n # result.append(gradient_classifier(dir_models, ticket, x, x_test, y, y_test))\n\n return result\n\n\nif __name__ == '__main__':\n dir_data = 'data_ga_periodic'\n dir_models = 'models_ga_periodic'\n report = run_learning(dir_data + '/', dir_models + '/')\n print(report)\n",
"from keras import Sequential\nfrom keras.layers import LSTM, Reshape, GRU, Dropout, Dense, Bidirectional\nfrom pandas_datareader import data as data_reader\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pymc3 as pm\nfrom sklearn.preprocessing import StandardScaler\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom keras.preprocessing.sequence import TimeseriesGenerator\nfrom sklearn.model_selection import train_test_split\nimport os\nimport pandas as pd\n\ndata_file = 'btc.data.csv'\n\nif not os.path.isfile(data_file):\n data = data_reader.get_data_yahoo('BTC-USD')\n data.to_csv(data_file)\n\ndata = pd.read_csv(data_file)\n\nprint(data.Open.head())\nprint(data.Open.tail())\nprint(data.Open.iloc[-1])\nhpd = pm.hpd(data.Open, alpha=0.05)\nprint('[%f %f]' % (hpd[0], hpd[1]))\n\n# _, (ax0, ax1) = plt.subplots(2, 1)\n# sns.kdeplot(data.Open, ax=ax0)\n# ax1.plot(data.Open)\n# plt.show()\n\ndata = data.as_matrix(columns=['Open'])\nprint(data.shape)\n\nstandard_scaler = StandardScaler()\nstandard_scaler.fit(data)\nd = standard_scaler.transform(data)\n# d = standard_scaler.inverse_transform(d)\n\n# playing with sklearn clusterings\n# num_of_classes = 8\n#\n# kmean = KMeans(n_clusters=num_of_classes, n_jobs=4)\n# pred = kmean.fit_predict(d)\n#\n# classes = np.unique(pred)\n# print(classes)\n#\n# for clas in range(num_of_classes):\n# pp_ind = np.where(pred == clas)\n# plt.plot(data[pp_ind],pred[pp_ind],'o')\n#\n#\n# plt.show()\n\n# d = d[19:]\n# d_seq = np.array(np.split(d, 93))\n# print(d_seq.shape)\n# result = []\n# for dd in d_seq:\n# result.append(np.reshape(dd, (1, 30)))\n#\n# d_seq = np.array(result)\n# print(d_seq.shape)\n\nMAX_RANGE = 30\n\nprint('creating sequences of %d range' % (MAX_RANGE))\n\nd_seq_file = 'd_seq.npy'\n\nif not os.path.isfile(d_seq_file):\n d_seq = []\n for i in range(len(data) - MAX_RANGE):\n sub = np.empty((MAX_RANGE,))\n index = 0\n for j in range(i, len(data)):\n if index > 0 and index % MAX_RANGE == 0:\n d_seq.append(np.reshape(sub, (1, MAX_RANGE)))\n sub = np.empty((MAX_RANGE,))\n index = 0\n sub[index] = data[j]\n index += 1\n\n d_seq = np.array(d_seq)\n np.save(d_seq_file,d_seq)\n\nd_seq = np.load(d_seq_file)\n\nprint(d_seq.shape)\n\nx_train, x_test = train_test_split(d_seq)\n\nm = Sequential()\nm.add(LSTM(\n 15,\n input_shape=(d_seq[0].shape[0], d_seq[0].shape[1]),\n return_sequences=True,\n dropout=0.2,\n kernel_regularizer='l2'))\nm.add(LSTM(\n MAX_RANGE,\n return_sequences=True,\n kernel_regularizer='l2'))\n\nm.compile(loss='mse', optimizer='nadam', metrics=['accuracy'])\n\nprint(m.summary())\n\nHistory = m.fit(x_train, x_train, epochs=5, validation_data=(x_test, x_test), batch_size=64, shuffle=True)\n\nplt.plot(History.history['loss'])\nplt.plot(History.history['val_loss'])\nplt.show()\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame",
"numpy.save",
"numpy.concatenate",
"numpy.warnings.filterwarnings",
"numpy.random.randint"
],
[
"pandas.read_csv",
"pandas.DataFrame",
"numpy.mean",
"numpy.warnings.filterwarnings",
"numpy.array"
],
[
"sklearn.neural_network.MLPClassifier",
"sklearn.metrics.classification.classification_report",
"numpy.nan_to_num",
"numpy.max",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.naive_bayes.BernoulliNB",
"sklearn.svm.LinearSVC",
"sklearn.linear_model.SGDClassifier",
"sklearn.ensemble.RandomForestClassifier",
"numpy.unique",
"numpy.reshape",
"sklearn.ensemble.VotingClassifier",
"sklearn.neighbors.KNeighborsClassifier",
"numpy.load",
"sklearn.metrics.classification.accuracy_score",
"sklearn.svm.NuSVC",
"sklearn.naive_bayes.GaussianNB",
"numpy.min",
"sklearn.model_selection.train_test_split",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.svm.SVC",
"sklearn.ensemble.GradientBoostingClassifier",
"sklearn.mixture.GaussianMixture",
"sklearn.ensemble.BaggingClassifier",
"sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis",
"sklearn.mixture.BayesianGaussianMixture"
],
[
"numpy.array",
"pandas.read_csv",
"numpy.reshape",
"sklearn.model_selection.train_test_split",
"numpy.save",
"matplotlib.pyplot.plot",
"numpy.load",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.show",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
eambutu/prototypical-pytorch
|
[
"4164705ab5808c288349c6113f2a2e2f6f6ea7b1"
] |
[
"src/loss_plot.py"
] |
[
"# coding=utf-8\nfrom prototypical_batch_sampler import PrototypicalBatchSampler\nfrom omniglot_dataset import OmniglotDataset\nfrom mini_imagenet_dataset import MiniImagenetDataset\nfrom protonet import ProtoNet\nimport torch\nfrom prototypical_loss import prototypical_loss as loss, obtain_mean\nfrom torch.autograd import Variable\nimport numpy as np\nfrom parser import get_parser\nfrom tqdm import tqdm\nimport os\n\n\ndef init_seed(opt):\n '''\n Disable cudnn to maximize reproducibility\n '''\n torch.cuda.cudnn_enabled = False\n np.random.seed(opt.manual_seed)\n torch.manual_seed(opt.manual_seed)\n torch.cuda.manual_seed(opt.manual_seed)\n\n\ndef init_dataset(opt):\n '''\n Initialize the datasets, samplers and dataloaders\n '''\n if opt.dataset == 'omniglot':\n test_dataset = OmniglotDataset(mode='test')\n elif opt.dataset == 'mini_imagenet':\n test_dataset = MiniImagenetDataset(mode='val')\n else:\n print('Dataset is not valid')\n test_sampler = PrototypicalBatchSampler(labels=test_dataset.y,\n classes_per_it=opt.classes_per_it_val,\n num_samples=opt.num_support_val + opt.num_query_val,\n iterations=opt.iterations)\n test_dataloader = torch.utils.data.DataLoader(test_dataset,\n batch_sampler=test_sampler)\n return test_dataloader\n\n\ndef init_protonet(opt):\n '''\n Initialize the ProtoNet\n '''\n if opt.dataset == 'omniglot':\n model = ProtoNet()\n elif opt.dataset == 'mini_imagenet':\n model = ProtoNet(x_dim=3)\n model = model.cuda() if opt.cuda else model\n return model\n\ndef test(opt, test_dataloader, model):\n '''\n Test the model trained with the prototypical learning algorithm\n '''\n rand_vec = 0.01 * np.random.randn(100, 1600)\n accs = []\n test_iter = iter(test_dataloader)\n #batches = [test_iter.__next__() for i in range(100)]\n batch = test_iter.__next__()\n for idx in range(101):\n counter = 0\n #for batch in batches:\n x, y = batch\n x, y = Variable(x), Variable(y)\n if opt.cuda:\n x, y = x.cuda(), y.cuda()\n model_output = model(x)\n means = obtain_mean(model_output, target=y, n_support=opt.num_support_tr)\n if idx < 100:\n means = means.data.numpy()\n means[4] = means[4] + rand_vec[idx]\n means = Variable(torch.FloatTensor(means))\n\n _, acc = loss(model_output, means, target=y, n_support=opt.num_support_tr)\n #avg_acc.append(acc.data[0])\n\n #avg = np.mean(avg_acc)\n print('Test Acc: {}'.format(acc.data[0]))\n accs.append(acc.data[0])\n\n for idx in range(100):\n if accs[idx] > accs[-1]:\n print('Higher index: {}'.format(idx))\n import pdb; pdb.set_trace()\n\n return accs\n\n\ndef eval(opt):\n '''\n Initialize everything and train\n '''\n options = get_parser().parse_args()\n\n if torch.cuda.is_available() and not options.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\n init_seed(options)\n test_dataloader = init_dataset(options)\n model = init_protonet(options)\n model_path = os.path.join(opt.experiment_root, 'best_model.pth')\n model.load_state_dict(torch.load(model_path))\n\n test(opt=options,\n test_dataloader=test_dataloader,\n model=model)\n\ndef main():\n options = get_parser().parse_args()\n eval(opt=options)\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.load",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"numpy.random.randn",
"torch.FloatTensor",
"torch.cuda.is_available",
"torch.autograd.Variable"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bahp/datablend
|
[
"f0b69a012af6ea7cedc9210d46b3047d8e0bf504",
"f0b69a012af6ea7cedc9210d46b3047d8e0bf504",
"f0b69a012af6ea7cedc9210d46b3047d8e0bf504",
"f0b69a012af6ea7cedc9210d46b3047d8e0bf504",
"f0b69a012af6ea7cedc9210d46b3047d8e0bf504"
] |
[
"datablend/tests/test_widgets.py",
"examples/oucru/oucru-32dx/create_data_fixed.py",
"examples/oucru/oucru-fl/create_data_ccfgs.py",
"datablend/utils/methods.py",
"examples/oucru/oucru-01nva/create_data_ccfgs.py"
] |
[
"# Libraries\nimport pytest\nimport pandas as pd\n\n# DataBlend libraries\nfrom datablend.core.blend.template import BlenderTemplate\nfrom datablend.core.widgets.base import BaseWidget\nfrom datablend.core.widgets.format import RenameWidget\nfrom datablend.core.widgets.format import ReplaceWidget\nfrom datablend.core.widgets.format import DateTimeMergeWidget\nfrom datablend.core.exceptions import WrongColumnType\nfrom datablend.core.exceptions import MissingRequiredColumns\nfrom datablend.core.exceptions import IncompatibleBlenderTemplateError\nfrom datablend.core.exceptions import ReplaceWidgetMapWarning\n\n\"\"\"\n.. note: bt is the acronym for BlenderTemplate\n df is the acronym for DataFrame\n\"\"\"\n\n\[email protected]\ndef data():\n \"\"\"Returns a basic data DataFrame.\"\"\"\n data = [\n {'StudyNo': '32dx-001', 'Temp': 37.2, 'Shock': False, 'Sex': 1},\n {'StudyNo': '32dx-002', 'Temp': 36.5, 'Shock': False, 'Sex': 1},\n {'StudyNo': '32dx-003', 'Temp': 39.8, 'Shock': True, 'Sex': 2},\n {'StudyNo': '32dx-004', 'Temp': 37.4, 'Shock': False, 'Sex': 1}\n ]\n # Return\n return pd.DataFrame(data)\n\n\[email protected]\ndef bt_json():\n # Template\n template = [\n # Example rename widget\n {'from_name': 'StudyNo', 'to_name': 'study_number'},\n {'from_name': 'Temp', 'to_name': 'body_temperature'},\n {'from_name': 'Shock', 'to_name': 'shock'},\n {'from_name': 'Sex', 'to_name': 'gender',\n 'to_replace': {1: 'Male', 2: 'Female'}}\n ]\n # Return\n return template\n\n\[email protected]\ndef bt_df(bt_json):\n return pd.DataFrame(bt_json)\n\n\[email protected]\ndef bt(bt_df):\n return BlenderTemplate().fit(bt_df)\n\n\n# ----------------------------\n# Widget tests\n# ----------------------------\n# Basic tests\n# -----------\ndef test_widget_raises_exception_on_None():\n \"\"\"\"\"\"\n with pytest.raises(TypeError):\n RenameWidget().fit(None)\n\n\ndef test_widget_fit_from_df(bt_df):\n \"\"\"\"\"\"\n widget = RenameWidget().fit(bt_df)\n assert isinstance(widget, BaseWidget)\n\n\ndef test_widget_fit_from_json(bt_json):\n \"\"\"\"\"\"\n widget = RenameWidget().fit(bt_json)\n assert isinstance(widget, BaseWidget)\n\n\n# ReplaceWidget tests\n# -------------------\ndef test_widget_replace_raises_exception_on_missing_required_columns(bt_df):\n \"\"\"\"\"\"\n bt_df = bt_df.drop(columns='to_replace')\n bt = BlenderTemplate().fit(bt_df)\n with pytest.raises(MissingRequiredColumns):\n ReplaceWidget().fit(bt)\n\n\ndef test_widget_replace_raises_warning(bt_df, data):\n \"\"\"\"\"\"\n bt_df.at[3, 'to_replace'] = {'Male': 1}\n with pytest.warns(ReplaceWidgetMapWarning):\n ReplaceWidget().fit_transform(bt_df, data)\n\n\ndef test_widget_replace_from_dict(bt, data):\n \"\"\"ReplaceWidget fit from dictionary\"\"\"\n transformed = ReplaceWidget().fit_transform(bt, data)\n unique = set(transformed.Sex.unique())\n assert unique.issubset(set(['Male', 'Female']))\n\n\ndef test_widget_replace_from_str(bt, data):\n \"\"\"ReplaceWidget fit from str dictionary.\"\"\"\n assert True\n\n\n# EventWidget tests\n# -----------------\ndef test_widget_event_raises_exception_on_missing_required_columns(bt_df):\n \"\"\"\"\"\"\n assert True\n\n\n# DateTimeMergeWidget tests\n# -------------------------\ndef test_widget_dtmerge_raises_exception_on_missing_required_columns(bt_df):\n \"\"\"\"\"\"\n assert True\n\n\n# DateFromStudyDay tests\n# ----------------------\ndef test_widget_dtfromstudyday_raises_exception_on_missing_required_columns(bt_df):\n \"\"\"\"\"\"\n assert True\n\n\ndef test_widget_dtmerge(bt, data):\n \"\"\"\"\"\"\n assert True\n\n\ndef test_widget_events(bt, data):\n \"\"\"\"\"\"\n assert True\n\n\ndef test_widget_studyday(bt, data):\n \"\"\"\"\"\"\n assert True\n\n\ndef test_widget_stack(bt, data):\n \"\"\"\"\"\"\n",
"# Libraries\nimport pathlib\nimport pandas as pd\n\n# DataBlend libraries\nfrom datablend.utils.logger import load_logger\n\n\n# ------------------------------------------\n# Methods\n# ------------------------------------------\ndef fix_exam(df_his, df_exam):\n \"\"\"This method fixes the EXAM worksheet\n\n issue 1: There is no date in EXAM\n It can be addressed including the enrolment date in ENROL.\n It can be addressed including the date in NS1STRIP.\n \"\"\"\n # Issue 1: No date found (sample_date)\n # ------------------------------------\n # Create auxiliary dataframe\n aux = df_his[['StudyNo', 'enDate', 'enTime']]\n # Include date enrolment information\n df_exam = df_exam.merge(aux, how='left', on='StudyNo')\n\n # Return\n return df_exam\n\n# -------------------------------\n# Create configuration from data\n# -------------------------------\n# Current path\ncurr_path = pathlib.Path(__file__).parent.absolute()\n\n# Create logger\nlogger = load_logger('%s/logging.yaml' % curr_path)\n\n# Path with raw data.\npath_data = '{0}/resources/datasets/{1}'.format(\n curr_path, '19-5-2020-CTU32DX_Data.xlsx')\n\n# Path to save fixed data.\npath_fixed = '{0}/resources/outputs/datasets/{1}'.format(\n curr_path, '32dx_data_fixed.xlsx')\n\n\n# -------------------------------\n# Read data\n# -------------------------------\n# Read all data sheets\ndata = pd.read_excel(path_data,\n sheet_name=None, engine='openpyxl')\n\n# Logging information\nlogger.info(\"=\" * 80)\nlogger.info(\"File: %s\", path_data)\nlogger.info(\"\")\n\n# Logging worksheets\nfor k, v in data.items():\n logger.info(\"Worksheet %-15s | Rows %5s | Columns %3s\",\n k, v.shape[0], v.shape[1])\n\n\n# -------------------------------\n# Fix data sheets\n# -------------------------------\n# Fix the various worksheets\ndata['EXAM'] = fix_exam(data['HIS'], data['EXAM'])\n\n# ---------------------------------\n# Save\n# ---------------------------------\n# Create path if it does not exist\npathlib.Path(path_fixed).parent.mkdir(parents=True, exist_ok=True)\n\n# Creating Excel Writer Object from Pandas\nwriter = pd.ExcelWriter(path_fixed, engine='xlsxwriter')\n\n# Save each frame\nfor sheet, frame in data.items():\n frame.to_excel(writer, sheet_name=sheet, index=False)\n\n# critical last step\nwriter.save()\n\n# Logging output\nlogger.info(\"\")\nlogger.info(\"Output: %s\", path_fixed)\nlogger.info(\"=\" * 80)",
"# Libraries\nimport pathlib\nimport pandas as pd\n\n# DataBlend libraries\nfrom datablend.core.blend.template import BlenderTemplate\nfrom datablend.utils.pandas import save_xlsx\n\n# -------------------------------\n# Create configuration from data\n# -------------------------------\n# Current path\ncurr_path = pathlib.Path(__file__).parent.absolute()\n\n# Path with raw data.\npath_data = '{0}/resources/outputs/datasets/{1}'.format(\n curr_path, 'fl_data_fixed.xlsx')\n\n# Path to save fixed data.\npath_ccfgs = '{0}/resources/outputs/templates/tmp/{1}'.format(\n curr_path, 'ccfgs_fl_data_fixed.xlsx')\n\n# --------------------\n# Main\n# --------------------\n# Read all data sheets\ndata = pd.read_excel(path_data, sheet_name=None)\n\n# Create templates\ntemplates = {}\n\n# Fill templates\nfor k, df in data.items():\n # Show information\n print(\"Processing sheet... %s <%s>.\" % (path_data, k))\n # Create descriptor template\n templates[k] = BlenderTemplate().fit_from_data(df)\n\n# -----------\n# Save\n# -----------\n# Create path if it does not exist\npath = pathlib.Path(path_ccfgs)\npath.parent.mkdir(parents=True, exist_ok=True)\n\n# Format templates (improve this)\naux = {k: v.df for k, v in templates.items()}\n\n# Save\nsave_xlsx(aux, path_ccfgs)\n",
"# Libraries\nimport json\nimport numpy as np\nimport pandas as pd\n\n\ndef load_features_map(filepath):\n \"\"\"This method loads the features map json file.\n\n Parameters\n ----------\n\n Return\n ------\n \"\"\"\n # Reading the json as a dict\n with open(filepath) as json_data:\n data = json.load(json_data)\n\n # Read file\n config = pd.DataFrame(data)\n\n # Basic formatting\n config.name = config.name.str.title()\n config.code = config.code.str.upper()\n\n # Return\n return config\n\n\ndef load_columns_operations(filepath):\n \"\"\"This method...\"\"\"\n pass\n\n\ndef merge_date_time(data, date_column, time_column=None):\n \"\"\"This method merges columns date and time\n\n .. note: If time is missing default is 00:00.\n .. note: Also convert date using dt.apply(str).\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n if not date_column in data:\n print(\"Column <%s> not found!\" % date_column)\n\n if not time_column in data:\n print(\"Column <%s> not found!\" % time_column)\n\n # Fill empty times with default value\n data[time_column] = data[time_column].fillna('00:00')\n\n # Format\n date = data[date_column].dt.strftime('%Y-%m-%d')\n time = data[time_column]\n\n # Return\n return pd.to_datetime(date + ' ' + time)\n\n\ndef display(data, name):\n \"\"\"This method...\"\"\"\n print(\"Name: %s\" % name)\n print(data.dtypes)\n if 'code' in data:\n print(\"Codes: %s\\n\" % data['code'].unique())\n elif 'column' in data:\n print(\"Columns: %s\\n\" % data['column'].unique())\n print(data)\n print(\"\\n\\n\")\n\n\ndef extract_stacked(dataframe, index, keep=None, source=None,\n name_column='column',\n name_result='result'):\n \"\"\"This method to extract stacked information from the dataframe.\n\n Example:\n\n The dataframe parameter:\n date patient bt hr rr\n d1 p1 35.5 67 18\n d2 p1 - - -\n d1 p2 - - -\n\n The index parameter: ['date', 'patient']\n The keep parameter: ['bt', 'hr', 'rr']\n\n The output:\n date patient column result\n d1 p1 bt 35.5\n d1 p1 hr 67\n d1 p1 rr 18\n d2 p1 bt -\n\n Parameters\n ----------\n dataframe: pd.DataFrame\n The dataframe with the data\n\n index: list\n List of column names that will be set as index.\n\n keep: list\n List of column names that will be stacked. The name\n of the column will be in the column named 'column'\n and the corresponding value in the column named\n 'result'.\n\n source:\n\n name_column:\n\n name_result:\n\n Returns\n -------\n The stacked dataframe\n \"\"\"\n\n # Check inputs\n if keep is None:\n keep = set(dataframe.columns)\n\n # Format inputs\n index = list(index)\n keep = list(set(keep) - set(index))\n\n # Format to stack dataset\n df = dataframe.copy(deep=True)\n df = df[index + keep]\n df = df.set_index(index)\n df = df.stack()\n df = df.reset_index()\n df.columns = index + [name_column, name_result]\n\n # Add source\n if source is not None:\n df['source'] = source\n\n # Return\n return df\n\n\n# -----------------------------------\n# Methods\n# -----------------------------------\ndef extract_events(dataframe, index, keep):\n \"\"\"This method....\"\"\"\n # Format the inputs\n index = list(index)\n keep = list(keep)\n\n # Remove those in index\n print(index)\n print(keep)\n\n # Format to stack dataset\n df = dataframe.copy(deep=True)\n df = df[index + keep]\n df = df.set_index(index)\n df = df.stack()\n df = df.reset_index()\n df.columns = index + ['column', 'date']\n df['result'] = 1.0\n df.column = df.column.apply(lambda x: '_'.join(x.split(\"_\")[1:])) # do it better with replace\n df['source'] = '32dx_evo'\n\n # Return\n return df\n\n\ndef stacked_display(dataframe, title='', top=10):\n \"\"\"This method displays the dataframes.\n\n Parameters\n ---------\n datafame:\n\n title:\n\n top:\n\n Returns\n --------\n \"\"\"\n # Display\n print(\"\\n\\n%s\" % title)\n print(\"=\" * 80)\n print(\"Column counts:\")\n print(\"-\" * 30)\n if 'column' in dataframe:\n print(dataframe.column.value_counts().sort_index())\n print(\"\\nResult counts:\")\n print(\"-\" * 30)\n #if 'result' in dataframe:\n # print(dataframe.result.value_counts().sort_index())\n print(\"\\nDataFrame:\")\n print(\"-\" * 50)\n print(dataframe.head(top))\n\n\ndef extract_records_from_tuples(dataframe, index, tuples,\n bool2int=False, verbose=0, return_by_types=True):\n \"\"\"This method extracts the events from tuples.\n\n This approach is used when there are specific columns for\n the different symptoms indicating the status (true or false),\n the date it started and/or the level.\n\n The input is an array of tuples containing (date, status, level) where\n status indicates the column with the status (True or False),\n date indicates the column with the dates (datetime64[ns]) and\n level indicates the column with the acuity (number).\n\n =============== ====== =========== ======== ============= ==============\n date_enrollment chills chills_date headache headache_date headache_level\n =============== ====== =========== ======== ============= ==============\n 10-10-2020 1 9-10-2020 1 8-10-2020 3\n 5-10-2020 1 1-10-2020 1 8-10-2020 1\n 1-10-2020 0 - 1 8-10-2020 1\n 12-10-2020 1 7-10-2020 1 8-10-2020 2\n =============== ====== =========== ======== ============= ==============\n\n Returns\n -------\n dict\n The result\n \"\"\"\n # Check inputs\n if isinstance(index, str):\n index = [index]\n\n # What if tuples is None\n\n # Output\n stacked_by_dtype = {}\n\n # Loop over all the tuples\n for date, result in tuples:\n # Both status and level are None\n if date is None or result is None:\n print(\"Tuple (%s, %s) has a None.\" % (date, result))\n continue\n\n # Get stacked DataFrame\n aux = extract_stacked(dataframe,\n index=index + [date], keep=[result])\n aux = aux[aux[date].notna()]\n aux = aux.rename(columns={date: 'date'})\n\n # Convert booleans to int (0 or 1)\n #if bool2int:\n # print(result, dataframe[result].dtype.name == 'boolean')\n # if dataframe[result].dtype.name == 'boolean':\n # aux.result = pd.to_numeric(aux.result)\n\n #aux = aux.convert_dtypes()\n\n # .. note: String could be string or class.\n\n # Add to dictionary\n key = str(aux.result.dtype)\n if not key in stacked_by_dtype:\n stacked_by_dtype[key] = []\n stacked_by_dtype[key].append(aux)\n\n\n \"\"\"\n # Display\n if verbose > 0:\n stacked_display(aux, status.title())\n \"\"\"\n\n # Concatenate\n for k, v in stacked_by_dtype.items():\n stacked_by_dtype[k] = \\\n pd.concat(v).reset_index(drop=True)\n\n # Return stacked grouped by types\n if return_by_types:\n return stacked_by_dtype\n\n \"\"\"\n .. warning: The order of the concatenation matters. If we start with\n concatenating ints and then bools, the boolean will be\n converted to 0 or 1. To solve this issue...\n \n 1. Quick fix: start with booleans... \n Will this generate an issue converting ints with only\n 0s or 1s to boolean?\n \n 2. Good fix: keep the types from original data.\n Do as types with the types...\n \n 3. Other fix: Create object dataframe before concatenating?\n \n ['float64', 'int64', 'bool', 'object'])\n \"\"\"\n # Careful if no datetime column ccfg aux will not exist.\n # Merge all no matter their types\n result = pd.DataFrame(columns=aux.columns, dtype=object)\n for k in sorted(stacked_by_dtype.keys()): # Quick fix\n result = result.append(stacked_by_dtype[k])\n\n # Return\n return result\n",
"# Libraries\nimport pathlib\nimport pandas as pd\n\n# DataBlend libraries\nfrom datablend.core.blend.template import BlenderTemplate\nfrom datablend.utils.pandas import save_xlsx\n\n# -------------------------------\n# Create configuration from data\n# -------------------------------\n# Current path\ncurr_path = pathlib.Path(__file__).parent.absolute()\n\n# Path with raw data.\npath_data = '{0}/resources/outputs/datasets/{1}'.format(\n curr_path, '01nva_data_fixed.xlsx')\n\n# Path to save fixed data.\npath_ccfgs = '{0}/resources/outputs/templates/tmp/{1}'.format(\n curr_path, 'ccfgs_01nva_data_fixed.xlsx')\n\n# --------------------\n# Main\n# --------------------\n# Read all data sheets\ndata = pd.read_excel(path_data, sheet_name=None)\n\n# Create templates\ntemplates = {}\n\n# Fill templates\nfor k, df in data.items():\n # Show information\n print(\"Processing sheet... %s <%s>.\" % (path_data, k))\n # Create descriptor template\n templates[k] = BlenderTemplate().fit_from_data(df)\n\n# -----------\n# Save\n# -----------\n# Create path if it does not exist\npath = pathlib.Path(path_ccfgs)\npath.parent.mkdir(parents=True, exist_ok=True)\n\n# Format templates (improve this)\naux = {k:v.df for k,v in templates.items()}\n\n# Save\nsave_xlsx(aux, path_ccfgs)\n"
] |
[
[
"pandas.DataFrame"
],
[
"pandas.read_excel",
"pandas.ExcelWriter"
],
[
"pandas.read_excel"
],
[
"pandas.concat",
"pandas.to_datetime",
"pandas.DataFrame"
],
[
"pandas.read_excel"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
Amir-Mehrpanah/RRFLab
|
[
"0991b7a0c0c977fd25ab3d218ba509db889489ad"
] |
[
"windows-mlps-lrsignal/main.py"
] |
[
"import torch.nn\nfrom src.model_management import models\nfrom torch import optim\nfrom src import signal_functions, metrics\nfrom ray import tune\nimport numpy as np\nfrom src.model_management.hyperparameter_optimization import optimization_objective\nfrom src.trade_utils import ParallelTrader, Trader\n\nanalysis = tune.run(\n optimization_objective,\n metric='test_loss',\n mode='min',\n resources_per_trial={'gpu': 1},\n num_samples=200,\n config={\n 'test_split': 0.2,\n 'valid_split': 0.2,\n 'train_batch_size': 64,\n 'valid_batch_size': 64,\n 'test_batch_size': 64,\n 'data_root_path': '/media/rramezanian/7fa33b6b-1db9-4da7-bf8c-e6880b4a8fd3/'\n 'stock_market/datasets/sandp500/individual_stocks_5yr',\n 'initial_capital': 1000,\n 'metrics': metrics.Apply(['sharpe',\n 'accuracy'],\n daily_risk_free_return_rate=(1.0007 ** (1 / 365)) - 1,\n trader=ParallelTrader([\n Trader(tune.sample_from(lambda x: x.initial_capital), 0.99),\n Trader(tune.sample_from(lambda x: x.initial_capital), 0.66),\n Trader(tune.sample_from(lambda x: x.initial_capital), 0.3)\n ])\n ),\n 'num_symbols': 32,\n 'min_stock_data_length': 1100,\n 'demo': False,\n 'verbose': 0,\n 'loss_function': torch.nn.CrossEntropyLoss(),\n 'learning_rate': tune.loguniform(1e-7, 1),\n 'num_epochs': 200,\n 'model': models.MLP,\n 'optimizer': tune.choice([optim.Adam,\n optim.RMSprop,\n optim.Adadelta,\n optim.SGD]),\n 'early_stopping_patience': 20,\n 'signal_function': signal_functions.LinearRegressionSignalFn,\n 'signal_function_args': {\n 'thresh': tune.uniform(0.01, 1)\n },\n 'num_parallel_windows': tune.sample_from(lambda x: np.random.randint(1, 10)),\n 'min_forward_window_length': tune.sample_from(lambda x: np.random.randint(3, 7)),\n 'min_backward_window_length':\n tune.sample_from(lambda x:\n np.random.randint(x.config.min_forward_window_length,\n 10)),\n 'window_step': 3, # tune.sample_from(lambda x: np.random.randint(1, 10)),\n 'forward_window_lengths':\n tune.sample_from(lambda x:\n [x.config.min_forward_window_length + x.config.window_step * i\n for i in range(x.config.num_parallel_windows)]),\n 'backward_window_lengths':\n tune.sample_from(lambda x:\n [x.config.min_backward_window_length + x.config.window_step * i\n for i in range(x.config.num_parallel_windows)])\n })\n\nprint(analysis.best_config)\n"
] |
[
[
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
michiyasunaga/DrRepair
|
[
"fb447594149ac4f80fef8ba091373184120019c7"
] |
[
"evaluation/spoc/test_spoc.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport csv, os, sys, math, time, random, re\nimport argparse\nimport heapq\nimport subprocess\nfrom enum import Enum\nimport itertools\nimport traceback\nimport json\nimport numpy as np\n\n## for parallel\nfrom joblib import Parallel, delayed\nimport multiprocessing as mp\n\nimport socket\n\n\n# Global arguments\nARGS = None\n\n\nSCORE_THRES = 1e6\nERR_BLACK_AMOUNT = -1e6\n\n\n# indices in the respective tsv_files\nclass _inp():\n text = 0\n code = 1\n hitid = 2\n workerid = 3\n probid = 4\n subid = 5\n line = 6\n indent = 7\n\nclass _pred():\n text = 1\n gold_score = 2\n pred_score = 3\n gold = 4\n pred_best = 5\n\n\n\nrepo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nsys.path.append(os.path.join(repo_root, \"utils\"))\nfrom code_process import tokenize_code, TEXT_TOKENIZER\nfrom code_process import filter_error_message, fix_strings, fix_strings_one_whitespace, remove_braces_gold\nfrom compilation import err, pass_test, compile_and_run_tests_all\n\n\n\n\n################################################\n# Utils\n\ndef prepare_lines_print(text_indent, text_str_noindt, _max_len, wrap_indent=3): #initial text_indent, text_str_noindt\n text_str = text_indent*\" \" + text_str_noindt\n text_to_print = []\n if len(text_str) <= _max_len:\n text_to_print.append(text_str)\n else:\n text_str_print = text_str[:_max_len]\n text_to_print.append(text_str_print)\n text_str_noindt = text_str[_max_len:]\n text_indent += wrap_indent\n text_str = text_indent*\" \" + text_str_noindt\n while len(text_str) > _max_len:\n text_str_print = text_str[:_max_len]\n text_to_print.append(text_str_print)\n text_str_noindt = text_str[_max_len:]\n text_str = text_indent*\" \" + text_str_noindt\n text_to_print.append(text_str)\n return text_to_print\n\n\ndef prepare_code_fix_spoc_bug(inp_stmt, pred_stmt, curr_code_lines_str):\n code = \"#include <bits/stdc++.h>\\n#include <string>\\nusing namespace std;\\n\\n\"\n code_lines = [] # For the error detection model\n prev_line = \" \"\n idx_count = 0\n curr_ind = 0\n for inp, pred in zip(inp_stmt, pred_stmt):\n # indent = '\\t' * int(inp[_inp.indent]) ????????\n tmp_ind = int(inp[_inp.indent])\n if pred[_pred.text] == 'DUMMY':\n curr_line = remove_braces_gold(inp[_inp.code]).strip()\n curr_line_for_repair_model = inp[_inp.code]\n else:\n curr_line_for_repair_model = curr_code_lines_str[idx_count]\n curr_line = fix_strings(curr_code_lines_str[idx_count])\n curr_line = fix_strings_one_whitespace(inp[_inp.text], curr_line)\n _prev_line = prev_line.replace(\" \", \"\")\n # handle case like\n # cout << \" YES \"\n # << \" \\n \" ;\n if (len(curr_line) >= 2 and curr_line[:2]==\"<<\"):\n tmp_ind = curr_ind\n # handle \"std:\", \"pause:\", \"momo:\", \"start:\", \"label:\", etc.\n if (2<= len(curr_line) <=12 and re.match(r'^\\w+:;?$', curr_line.replace(\" \",\"\")) is not None): #^ means start, $ means end. be careful - curr_line is tokenized (e.g. momo :)\n tmp_ind = tmp_ind + 1\n # handle\n # 10,\n # 11\n if _prev_line.endswith(\",\") and curr_line != \"};\":\n tmp_ind = curr_ind\n indent = '\\t' * tmp_ind\n if tmp_ind < curr_ind:\n if not (pred[_pred.text] == 'DUMMY' and (inp[_inp.code].replace(\" \", \"\") in [\"}\", \"};\"])): ##be careful - this function takes in line str from pred (if not DUMMY), so braces are removed\n indent += \"} \"\n if curr_ind - tmp_ind > 1:\n indent += (curr_ind - tmp_ind - 1) * \"} \"\n elif tmp_ind > curr_ind:\n if not prev_line or prev_line[-1] != \"{\":\n indent += \"{ \"\n if tmp_ind - curr_ind > 1:\n indent += (tmp_ind - curr_ind - 1) * \"{ \"\n curr_ind = tmp_ind\n\n ##handle a case like\n # if (i==10)\n # else { ... }\n if _prev_line.startswith(\"if(\") and _prev_line.endswith(\")\") and curr_line.startswith(\"else\"):\n code += (\"\\t\" *curr_ind + \";\\n\")\n elif _prev_line.startswith(\"elseif(\") and _prev_line.endswith(\")\") and curr_line.startswith(\"else\"):\n code += (\"\\t\" *curr_ind + \";\\n\")\n elif _prev_line ==\"else\" and curr_line==\"}\":\n code += (\"\\t\" *curr_ind + \"{\\n\")\n elif _prev_line ==\"do\" and curr_line.startswith(\"while\"):\n code += (\"\\t\" *curr_ind + \"{}\\n\")\n\n if pred[_pred.text] == 'DUMMY':\n code += indent + curr_line + \"\\n\"\n idx_count += 1\n else:\n code += indent + curr_line + \" // \" + inp[_inp.text].rstrip('\\\\') + \"\\n\"\n idx_count += 1\n prev_line = curr_line\n code_lines.append((\" \".join(TEXT_TOKENIZER.findall(inp[_inp.text].rstrip('\\\\'))), curr_line_for_repair_model, curr_ind))\n # print (curr_line)\n return code, code_lines\n\n\n\n\n################################################\n# Run repair model during stitch\n\n# add edited versions of line into heap\ndef stitch_error_localize_edit_search(inp_stmt, pred_stmt, probid, subid):\n # There are 2 different indexing systems (both 0-based)\n # * stmt_idx: index of inp_stmt and pred_stmt (i.e., with DUMMY lines)\n # Note: stmt_idx = real line number minus LINE_OFFSET\n # * prob_list_idx: index of prob_list (i.e., excluding DUMMY lines)\n\n pred_stmt = pred_stmt[:] #we will modify this with editor preds\n curr_code_lines_str = [] #list[str]: with DUMMY lines\n gold_code_lines_str = []\n prob_list = []\n prob_list_idx_to_stmt_idx = []\n unique_id = probid + \"-\" + subid\n for stmt_idx, (inp, pred) in enumerate(zip(inp_stmt, pred_stmt)):\n curr_prob_list = []\n if pred[_pred.text] != 'DUMMY':\n for i in range(_pred.pred_best + ARGS.num_preds, _pred.pred_best + 2 * ARGS.num_preds):\n curr_prob_list.append(float(pred[i]))\n prob_list.append(curr_prob_list)\n prob_list_idx_to_stmt_idx.append(stmt_idx)\n curr_code_lines_str.append(pred[_pred.pred_best]) #initialize with top1 sticth\n gold_code_lines_str.append(pred[_pred.gold])\n else:\n curr_code_lines_str.append(inp[_inp.code]) #DUMMY\n gold_code_lines_str.append(inp[_inp.code])\n stmt_idx_to_prob_list_idx = {x: i for (i, x) in enumerate(prob_list_idx_to_stmt_idx)}\n\n iter_count, compile_count = 0, 0\n # create a heap and add the first element\n # since we want a max_heap, we add a the negative of log prob (by default it's a min heap)\n heap = FragilePrioritySet(prob_list)\n\n\n #load repair model\n from repair_utils import RepairPolicy\n repair_model = RepairPolicy(ARGS, for_deepfix=False)\n\n\n edited_lineidx = {} #idxing system = stmt list\n\n # blacklist[prob_list_idx] = set of candidate_idxs that are blacklisted\n blacklist = [set() for _ in range(len(prob_list))]\n\n # iterate until not empty\n with open(\"error_localize_edit.txt\", \"w\") as stat_file:\n while not heap.empty() and iter_count < ARGS.compile_budget:\n stat_file.flush()\n iter_count += 1\n stat_file.write(\"\\n\")\n stat_file.write(\"Stats after iteration # \" + str(iter_count) + \"\\n\")\n stat_file.write(\"Time: {:.3f}\\n\".format(time.time() - START_TIME))\n # log_prob: float\n # curr_idx: list[int] of length len(prob_list)\n log_prob, curr_idx = heap.pop()\n stat_file.write(str(log_prob) + \"\\n\")\n stat_file.write(str(curr_idx) + \"\\n\")\n if log_prob >= SCORE_THRES:\n stat_file.write('Log_prob threshold reached. Committing suicide ...')\n return False, False\n\n # detect if there is a blacklisted candidate\n found_blacklist = None\n for prob_list_idx, candidate_idx in enumerate(curr_idx):\n if candidate_idx in blacklist[prob_list_idx]:\n found_blacklist = (prob_list_idx, candidate_idx)\n break\n\n # decide whether to proceed with code generation\n skip_synthesis = (found_blacklist is not None and ARGS.err_handling == 'black')\n if skip_synthesis:\n stat_file.write(\"Skip since {}.{} is in blacklist\\n\".format(*found_blacklist))\n iter_count -= 1\n else:\n for (linei, idx) in enumerate(curr_idx):\n curr_code = pred_stmt[prob_list_idx_to_stmt_idx[linei]][_pred.pred_best + idx]\n curr_code_lines_str[prob_list_idx_to_stmt_idx[linei]] = curr_code\n\n code, code_lines = prepare_code_fix_spoc_bug(inp_stmt, pred_stmt, curr_code_lines_str)\n assert len(gold_code_lines_str) == len(code_lines)\n\n print (\"Current code:\", file=stat_file)\n func_acc_tgts = {}\n wrong_lines = [] #list[(lineno, gold_code)]\n for (lineno, code_line) in enumerate(code_lines):\n code_str = code_line[1]\n _code_str = code_str.replace(\" \",\"\")\n text_str = code_line[0]\n indent = code_line[2]\n\n gold_str = remove_braces_gold(gold_code_lines_str[lineno])\n gold_to_print = []\n if lineno in func_acc_tgts:\n if (_code_str not in func_acc_tgts[lineno]):\n gold_to_print += prepare_lines_print(0, \"Gold: {}\".format(gold_str), 50, wrap_indent=8)\n wrong_lines.append(lineno)\n else:\n if _code_str != gold_str.replace(\" \",\"\"):\n gold_to_print += prepare_lines_print(0, \"Gold: {}\".format(gold_str), 50, wrap_indent=8)\n wrong_lines.append(lineno)\n if gold_to_print == []: gold_to_print.append(\"\")\n text_to_print = prepare_lines_print(indent, text_str, 50)\n code_to_print = prepare_lines_print(indent, code_str, 50)\n _text = text_to_print.pop(0)\n _code = code_to_print.pop(0)\n _gold = gold_to_print.pop(0)\n print (\"{:>3} {:<{width1}} {:<{width2}} {:}\".format(str(lineno), _text, _code, _gold, width1=50, width2=50), file=stat_file)\n for _text, _code, _gold in itertools.zip_longest(text_to_print, code_to_print, gold_to_print):\n if _text is None: _text = \"\"\n if _code is None: _code = \"\"\n if _gold is None: _gold = \"\"\n print (\"{:>3} {:<{width1}} {:<{width2}} {:}\".format(\"\", _text, _code, _gold, width1=50, width2=50), file=stat_file)\n\n # run the program\n passed, error, error_message = compile_and_run_tests_all(ARGS, code, probid, subid, None)\n if error != err.compile_err:\n compile_count += 1\n else:\n raw_compiler_err_msg = filter_error_message(error_message, unique_id)\n try:\n pred_lineno, _, err_line_obj = repair_model.policy_localize(code_lines, feedback=raw_compiler_err_msg, threshold_ON=True)\n err_line_stmt_idx = pred_lineno\n err_msg = err_line_obj[\"msg\"]\n except Exception as e:\n # Commit suicide\n print('PANIC (localize)! {}'.format(e))\n print('PANIC (localize)! {}'.format(e), file=stat_file)\n stat_file.write(traceback.format_exc())\n err_line_stmt_idx = None\n err_line = None\n err_msg = None\n # resolve the error line to prob_list_idx\n err_line = stmt_idx_to_prob_list_idx.get(err_line_stmt_idx) if err_line_stmt_idx is not None else None\n\n # after resolving, check if it's a predicted line\n if err_line is None:\n print('Error line UNKNOWN: {}'.format(err_msg), file=stat_file)\n else:\n print('Error line {} (with DUMMY): {}'.format(\n err_line_stmt_idx, err_msg,\n ), file=stat_file)\n\n print('Blacklisting {}.{}'.format(err_line, curr_idx[err_line]), file=stat_file)\n blacklist[err_line].add(curr_idx[err_line])\n\n if ARGS.err_handling == 'gray':\n prob_list[err_line][curr_idx[err_line]] -= ARGS.err_gray_amount\n else:\n prob_list[err_line][curr_idx[err_line]] = ERR_BLACK_AMOUNT\n\n #Before rebuild heap, update prob_list\n if err_line_stmt_idx not in edited_lineidx:\n print ('Getting edit preds for line# {}'.format(err_line_stmt_idx), file=stat_file)\n try:\n _, edit_pred, _ = repair_model.policy_edit(code_lines, feedback=raw_compiler_err_msg, pred_lineno=err_line_stmt_idx, beam_size=50)\n except Exception as e:\n # Commit suicide\n print('PANIC (edit)! {}'.format(e))\n print('PANIC (edit)! {}'.format(e), file=stat_file)\n stat_file.write(traceback.format_exc())\n edit_pred = None\n if edit_pred is not None:\n pred_code_nbest = edit_pred[\"pred\"]\n # pred_code_scores = edit_pred[\"score\"]\n edited_lineidx[err_line_stmt_idx] = True\n curr_highest_prob = max(prob_list[err_line])\n\n topk = 1\n pred_code_nbest = pred_code_nbest[:topk]\n pred_code_nbest_2rank = {x:i for i, x in enumerate(pred_code_nbest)}\n rank_to_remove = {}\n\n #remove duplicates\n for __idx in range(ARGS.num_preds -topk):\n __code = pred_stmt[err_line_stmt_idx][_pred.pred_best + __idx] #base pred code\n if __code in pred_code_nbest_2rank: #overlap btw base pred and editor pred\n rank = pred_code_nbest_2rank[__code]\n if __idx in blacklist[err_line]: #already in blacklist\n rank_to_remove[rank] = True\n else:\n rank_to_remove[rank] = True\n prob_list[err_line][__idx] = curr_highest_prob+1\n\n pred_code_nbest = [code for r, code in enumerate(pred_code_nbest) if r not in rank_to_remove]\n topk = len(pred_code_nbest)\n if topk > 0:\n print (\"adding {} editor preds\".format(topk), file=stat_file)\n #add editor preds to prob list (set the highest prob in line) and pred_stmt (replace with bottom preds)\n prob_list[err_line][-topk:] = list(curr_highest_prob + np.arange(topk) +1)\n pred_stmt[err_line_stmt_idx][_pred.pred_best +ARGS.num_preds - topk: _pred.pred_best +ARGS.num_preds] = pred_code_nbest\n print (\"prob_list[err_line]:\", prob_list[err_line], file=stat_file)\n\n heap.rebuild()\n\n stat_file.write(\"Number of programs compiled: \" + str(compile_count) + \"\\n\")\n stat_file.write(str(passed) + \" \" + str(error) + \"\\n\")\n\n # if public didn't pass then proceed\n if passed == pass_test.none:\n if error != err.compile_err:\n test_results = error_message[\"test_results_public\"]\n for (i, test_result) in enumerate(test_results):\n if test_result[\"error_info\"] is not None:\n x = json.dumps(test_result, ensure_ascii=False, indent=2)\n print (x, file=stat_file)\n stat_file.write(\"continuing best first search...\\n\\n\")\n elif passed == pass_test.public:\n stat_file.write(\"passed public but failed hidden!\\n\\n\")\n return True, False\n else:\n stat_file.write(\"passed public and hidden!\\n\\n\")\n return True, True\n\n return False, False\n\n\n\nclass FragilePrioritySet(object):\n \"\"\"\n Rebuild the heap every time prob_list changes.\n \"\"\"\n\n def __init__(self, prob_list):\n # prob_list[i][j] = logprob\n # prob_list is a shared object that can be updated outside the class\n self.prob_list = prob_list\n self.L = len(self.prob_list)\n # (neg_logprob, (j1, ..., jL), (r1, ..., rL))\n # true indices (j1, ..., jL) are used to track used combinations\n # ranks (r1, ..., rL) are used for finding neighbors\n self.heap = []\n self.rebuild()\n # Store combinations (j1, ..., jL) returnd during any reincarnation\n self.used = set()\n # Store combinations (j1, ..., jL) added to heap in this reincarnation\n self.added = set()\n\n def rebuild(self):\n # rankings[i][r] = j\n self.rankings = []\n for i, logprobs in enumerate(self.prob_list):\n ranked = sorted((-logprob, j) for (j, logprob) in enumerate(logprobs))\n self.rankings.append([j for (_, j) in ranked])\n # print (\"len(self.rankings)\", len(self.rankings))\n # print (self.rankings)\n self.heap.clear()\n self.added = set()\n self._add_r_tuple(tuple([0] * self.L))\n\n def _add_r_tuple(self, r_tuple):\n assert isinstance(r_tuple, tuple)\n # print (r_tuple)\n j_tuple = tuple(self.rankings[i][r] for (i, r) in enumerate(r_tuple))\n if j_tuple in self.added:\n return\n assert len(j_tuple) == self.L\n logprob = sum(self.prob_list[i][j] for (i, j) in enumerate(j_tuple))\n heapq.heappush(self.heap, (-logprob, j_tuple, r_tuple))\n self.added.add(j_tuple)\n\n def add(self, log_prob, idx):\n raise NotImplementedError('Should not be called.')\n\n def pop(self):\n # Keep popping the heap until an unused item is found\n while True:\n neg_logprob, j_tuple, r_tuple = heapq.heappop(self.heap)\n # Immediately add all neighbors\n for i in range(self.L):\n if r_tuple[i] < ARGS.num_preds - 1:\n neighbor = list(r_tuple)\n neighbor[i] += 1\n self._add_r_tuple(tuple(neighbor))\n # If not used, return it\n if j_tuple not in self.used:\n self.used.add(j_tuple)\n return (neg_logprob, list(j_tuple))\n\n def __len__(self):\n return len(self.heap)\n\n def empty(self):\n return len(self.heap) == 0\n\n\n\n################################################\n\ndef stitch_helper(probno):\n input = ARGS.input\n count = 0\n inp_stmt, pred_stmt = [], []\n # print (\"starting\", probno)\n # the following look extracts the input/pred lines for the probno specified\n # and passes it further for stitching\n with open(input + '.tsv','r') as tsvin, open(input + '.summary','r') as predin:\n tsvin.readline(), predin.readline()\n probid, subid = None, None\n\n while True:\n inp = tsvin.readline()\n if not inp:\n # Special handling for last line\n assert count == probno, \\\n 'num problems = {} but probno = {}'.format(count, probno)\n break\n inp = inp.split('\\t')\n pred = predin.readline().split(\"\\t\")\n if int(inp[_inp.line].strip()) == 0:\n if count == probno:\n break\n count += 1\n probid, subid = inp[_inp.probid].strip(), inp[_inp.subid].strip()\n hitid = inp[_inp.hitid].strip()\n if count == probno:\n inp_stmt.append(inp)\n pred_stmt.append(pred)\n\n # generate a unique id for this program\n unique_id = \"{:04d}-{}-{}\".format(probno, probid, subid)\n print(\"Unique ID: \" + unique_id)\n\n init_run_dir = os.getcwd()\n\n local_run_dir = unique_id\n os.system(\"rm -rf \" + local_run_dir)\n os.system(\"mkdir -p \" + local_run_dir)\n assert os.path.exists(local_run_dir)\n print (\"local_run_dir\", local_run_dir)\n os.chdir(local_run_dir)\n\n\n global START_TIME\n START_TIME = time.time()\n\n\n public, hidden = stitch_error_localize_edit_search(inp_stmt, pred_stmt, probid, subid)\n if public:\n tmp_f = open(\"passed_public.txt\", \"w\")\n tmp_f.close()\n if hidden:\n tmp_f = open(\"passed_hidden.txt\", \"w\")\n tmp_f.close()\n\n os.chdir(init_run_dir)\n print ()\n return\n\n\ndef stitch():\n if ARGS.n_parallel:\n probno = ARGS.probno\n n_parallel = ARGS.n_parallel\n probnos = list(np.arange(n_parallel) + probno) #e.g. [201,202,203]\n # Parallel(n_jobs=mp.cpu_count()*5)(delayed(stitch_helper)(probno) for (_, probno) in enumerate(probnos))\n for probno_ in probnos:\n stitch_helper(probno_)\n else:\n stitch_helper(ARGS.probno)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-v', '--verbose', action='store_true')\n parser.add_argument('--prog-dir', default=repo_root+'/raw_data/spoc_data/spoc/testcases',\n help='Path the codeforces-data repository, which contains test cases')\n parser.add_argument('--max-heap', type=int, default=999999,\n help='Suicide when heap is bigger than this')\n parser.add_argument('-t', '--timeout', type=int, default=20,\n help='Timeout for execution (in seconds)')\n parser.add_argument('-T', '--gcc-timeout', type=int, default=60,\n help='Timeout for compilation (in seconds)')\n parser.add_argument('-c', '--compile-budget', type=int, default=100,\n help='Number of maximum g++ calls')\n parser.add_argument('-p', '--num-preds', type=int, default=100,\n help='Number of predictions per line')\n parser.add_argument('--n-parallel', type=int, default=0)\n parser.add_argument('input')\n parser.add_argument('probno', type=int)\n\n\n group = parser.add_argument_group('error')\n group.add_argument('--err-handling', choices=['black', 'gray'], default='gray',\n help='Whether to blacklist or downweight error lines')\n group.add_argument('--err-gray-amount', type=float, default=10,\n help='(for graylisting) Amount to penalize error lines')\n\n group.add_argument('--err-localize-threshold', type=float, default=0.95,\n help='(advanced) Minimum probability for the advanced detector to trigger')\n\n group.add_argument('--repairer-server',\n help='Server + Port. comma separated list')\n\n\n global ARGS\n ARGS = parser.parse_args()\n if ARGS.repairer_server is not None:\n ARGS.repairer_server = ARGS.repairer_server.split(\",\")\n\n\n stitch()\n\n print (\"DONE\")\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.arange"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
assadullah96/mlops-sales-forecasting
|
[
"83cdda22a15720f8f1cfc98810d1643c7cbeb8cd"
] |
[
"sales_forecast/scoring/score.py"
] |
[
"\"\"\"\r\nCopyright (C) Microsoft Corporation. All rights reserved.\r\n \r\nMicrosoft Corporation (“Microsoft”) grants you a nonexclusive, perpetual,\r\nroyalty-free right to use, copy, and modify the software code provided by us\r\n(\"Software Code\"). You may not sublicense the Software Code or any use of it\r\n(except to your affiliates and to vendors to perform work on your behalf)\r\nthrough distribution, network access, service agreement, lease, rental, or\r\notherwise. This license does not purport to express any claim of ownership over\r\ndata you may have shared with Microsoft in the creation of the Software Code.\r\nUnless applicable law gives you more rights, Microsoft reserves all other\r\nrights not expressly granted herein, whether by implication, estoppel or\r\notherwise. \r\n \r\nTHE SOFTWARE CODE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\nMICROSOFT OR ITS LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\r\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\r\nBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\r\nIN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\nARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE CODE, EVEN IF ADVISED OF THE\r\nPOSSIBILITY OF SUCH DAMAGE.\r\n\"\"\"\r\nimport numpy\r\nimport joblib\r\nimport os\r\nfrom azureml.core.model import Model\r\nfrom inference_schema.schema_decorators \\\r\n import input_schema, output_schema\r\nfrom inference_schema.parameter_types.numpy_parameter_type \\\r\n import NumpyParameterType\r\nimport keras\r\nfrom keras.models import load_model\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n\r\ndef init():\r\n # load the model from file into a global object\r\n global model\r\n #data = [[2,230,2]]\r\n #scalar = MinMaxScaler(feature_range=(-1, 1))\r\n #scalar = scalar.fit(data)\r\n #data = scalar.transform(data)\r\n #print(\"value of data after transform\")\r\n #print(data)\r\n #data = data[:, 1:]\r\n #print(\"Value of data after reshaping\")\r\n #print(data)\r\n #data = data.reshape(data.shape[0], 1, data.shape[1])\r\n #print(\"Value of data after reshaping\")\r\n #print(data)\r\n\r\n # we assume that we have just one model\r\n # AZUREML_MODEL_DIR is an environment variable created during deployment.\r\n # It is the path to the model folder\r\n # (./azureml-models/$MODEL_NAME/$VERSION)\r\n model_path = Model.get_model_path(\r\n os.getenv(\"AZUREML_MODEL_DIR\").split('/')[-2])\r\n\r\n #model = joblib.load(model_path)\r\n model = keras.models.load_model(model_path)\r\n print(\"Model is loaded\")\r\n\r\ninput_sample = numpy.array([[30,178,1690,5]])\r\noutput_sample = numpy.array([4])\r\n#input_sample = [[30,178,1690]]\r\n#output_sample = [4]\r\n\r\n\r\n# Inference_schema generates a schema for your web service\r\n# It then creates an OpenAPI (Swagger) specification for the web service\r\n# at http://<scoring_base_url>/swagger.json\r\n@input_schema('data', NumpyParameterType(input_sample))\r\n@output_schema(NumpyParameterType(output_sample))\r\n#@input_schema('data', input_sample)\r\n#@output_schema(output_sample)\r\ndef run(data, request_headers):\r\n import json\r\n scalar = MinMaxScaler(feature_range=(-1, 1))\r\n scalar = scalar.fit(data)\r\n data = scalar.transform(data)\r\n data = data[:, 1:]\r\n data = data.reshape(data.shape[0], 1, data.shape[1])\r\n #print(test)\r\n #print(test.shape)\r\n #result = model.predict(data)\r\n\r\n y_pred=model.predict(data)\r\n y_pred = y_pred.reshape(y_pred.shape[0], 1, 1)\r\n pred_test_set = []\r\n for index in range(0, len(y_pred)):\r\n pred_test_set.append(np.concatenate([y_pred[index], data[index]], axis=1))\r\n\r\n # reshape pred_test_set\r\n pred_test_set = np.array(pred_test_set)\r\n pred_test_set = pred_test_set.reshape(pred_test_set.shape[0], pred_test_set.shape[2])\r\n\r\n # inverse transform\r\n pred_test_set_inverted = scalar.inverse_transform(pred_test_set)\r\n\r\n print(pred_test_set_inverted)\r\n print(\"predicted value:\")\r\n result = int(y_pred + pred_test_set_inverted[0][3])\r\n\r\n\r\n print(\"value of result is: \")\r\n print(result)\r\n\r\n # Demonstrate how we can log custom data into the Application Insights\r\n # traces collection.\r\n # The 'X-Ms-Request-id' value is generated internally and can be used to\r\n # correlate a log entry with the Application Insights requests collection.\r\n # The HTTP 'traceparent' header may be set by the caller to implement\r\n # distributed tracing (per the W3C Trace Context proposed specification)\r\n # and can be used to correlate the request to external systems.\r\n print(('{{\"RequestId\":\"{0}\", '\r\n '\"TraceParent\":\"{1}\", '\r\n '\"NumberOfPredictions\":{2}}}'\r\n ).format(\r\n request_headers.get(\"X-Ms-Request-Id\", \"\"),\r\n request_headers.get(\"Traceparent\", \"\"),\r\n result\r\n #len(result)\r\n ))\r\n\r\n #return {\"result\": result.tolist()}\r\n return {\"result\": result}\r\n\r\nif __name__ == \"__main__\":\r\n init()\r\n test =numpy.array([[0,0,24,5]])\r\n prediction = run(test, {}) \r\n print(\"Test result: \", prediction)\r\n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"sklearn.preprocessing.MinMaxScaler"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AJamesPhillips/cf-python
|
[
"4631bc4ba3c0cb51dcd18905116440007e291e6b"
] |
[
"cf/umread_lib/umfile.py"
] |
[
"import os\n\nfrom functools import cmp_to_key\n\nimport numpy\n\nfrom . import cInterface\nfrom .extraData import ExtraDataUnpacker\n\n\nclass UMFileException(Exception):\n pass\n\n\nclass File:\n '''A class for a UM data file that gives a view of the file including\n sets of PP records combined into variables\n\n '''\n def __init__(self, path, byte_ordering = None, word_size = None,\n format = None, parse = True): \n '''Open and parse a UM file. The following optional arguments specify\n the file type. If all three are set, then this forces the file\n type; otherwise, the file type is autodetected and any of them\n that are set are ignored.\n \n :Parmaeters:\n \n byte_ordering: 'little_endian' or 'big_endian'\n \n word_size: 4 or 8\n \n format: 'FF' or 'PP'\n \n The default action is to open the file, store the file type from\n the arguments or autodetection as described above, and then parse\n the contents, giving a tree of variables and records under the\n File object. However, if \"parse = False\" is set, then an object is\n returned in which the last step is omitted, so only the file type\n is stored, and there are no variables under it. Such an object can\n be passed when instantiating Rec objects, and contains sufficient\n info about the file type to ensure that the get_data method of\n those Rec objects will work.\n\n '''\n c = cInterface.CInterface()\n self._c_interface = c\n self.path = path\n self.fd = None\n self.open_fd()\n if byte_ordering and word_size and format:\n self.format = format\n self.byte_ordering = byte_ordering\n self.word_size = word_size\n else:\n self._detect_file_type()\n self.path = path\n file_type_obj = c.create_file_type(self.format, self.byte_ordering, self.word_size)\n c.set_word_size(file_type_obj)\n if parse:\n info = c.parse_file(self.fd, file_type_obj)\n self.vars = info[\"vars\"]\n self._add_back_refs()\n\n \n def open_fd(self):\n '''(Re)open the low-level file descriptor.\n\n '''\n if self.fd is None:\n self.fd = os.open(self.path, os.O_RDONLY)\n return self.fd\n\n \n def close_fd(self):\n '''Close the low-level file descriptor.\n\n '''\n if self.fd:\n os.close(self.fd)\n self.fd = None\n\n \n def _detect_file_type(self):\n c = self._c_interface\n try:\n file_type_obj = c.detect_file_type(self.fd)\n except:\n self.close_fd()\n raise IOError(\"File {0} has unsupported format\".format(self.path))\n\n d = c.file_type_obj_to_dict(file_type_obj)\n self.format = d[\"format\"]\n self.byte_ordering = d[\"byte_ordering\"]\n self.word_size = d[\"word_size\"]\n\n \n def _add_back_refs(self):\n '''Add file attribute to Var objects, and both file and var\n attributes to Rec objects. The important one is the file\n attribute in the Rec object, as this is used when reading\n data. The others are provided for extra convenience.\n\n '''\n for var in self.vars:\n var.file = self\n for rec in var.recs:\n rec.var = var\n rec.file = self\n\n \n#--- End: class\n\n\nclass Var:\n '''Container for some information about variables\n\n '''\n def __init__(self, recs, nz, nt, supervar_index=None):\n self.recs = recs\n self.nz = nz\n self.nt = nt\n self.supervar_index = supervar_index\n\n \n @staticmethod\n def _compare(x, y):\n '''Method equivalent to the Python 2 'cmp'. Note that (x > y) - (x <\n y) is equivalent but not as performant since it would not\n short-circuit.\n\n '''\n if x == y:\n return 0\n elif x > y:\n return 1\n else:\n return -1\n\n \n def _compare_recs_by_extra_data(self, a, b):\n return self._compare(a.get_extra_data(), b.get_extra_data())\n\n \n def _compare_recs_by_orig_order(self, a, b):\n return self._compare(self.recs.index(a), self.recs.index(b))\n\n \n def group_records_by_extra_data(self):\n '''Returns a list of (sub)lists of records where each records within\n each sublist has matching extra data (if any), so if the whole\n variable has consistent extra data then the return value will be\n of length 1. Within each group, the ordering of returned records\n is the same as in self.recs\n\n '''\n compare = self._compare_recs_by_extra_data\n recs = self.recs[:]\n n = len(recs)\n if n == 0:\n # shouldn't have a var without records, but...\n return []\n \n# recs.sort(compare) #python2\n recs.sort(key=cmp_to_key(compare))\n\n # optimise simple case - if two ends of a sorted list match, \n # the whole list matches\n if not compare(recs[0], recs[-1]):\n return [self.recs[:]]\n\n groups = []\n this_grp = []\n for i, rec in enumerate(recs):\n this_grp.append(rec)\n if i == n - 1 or compare(rec, recs[i + 1]):\n this_grp.sort(key=self._compare_recs_by_orig_order)\n groups.append(this_grp)\n this_grp = []\n #--- End: for\n \n return groups\n\n \n#--- End: class\n\n\nclass Rec:\n '''Container for some information about records\n\n '''\n def __init__(self, int_hdr, real_hdr, hdr_offset, data_offset, disk_length, \n file = None):\n '''Default instantiation, which stores the supplied headers and\n offsets. The 'file' argument, used to set the 'file' attribute,\n does not need to be supplied, but if it is not then it will have\n to be set on the returned object (to the containing File object)\n before calling get_data() will work. Normally this would be done\n by the calling code instantiating via File rather than directly.\n\n '''\n self.int_hdr = int_hdr\n self.real_hdr = real_hdr\n self.hdr_offset = hdr_offset\n self.data_offset = data_offset\n self.disk_length = disk_length\n self._extra_data = None\n if file:\n self.file = file\n\n \n @classmethod\n def from_file_and_offsets(cls, file, hdr_offset, data_offset, disk_length):\n '''Instantiate a Rec object from the file object and the header and\n data offsets. The headers are read in, and also the record object\n is ready for calling get_data().\n\n '''\n c = file._c_interface\n int_hdr, real_hdr = c.read_header(file.fd,\n hdr_offset,\n file.byte_ordering,\n file.word_size)\n return cls(int_hdr, real_hdr, hdr_offset, data_offset, disk_length, file=file)\n\n \n def read_extra_data(self):\n '''Read the extra data associated with the record\n\n '''\n c = self.file._c_interface\n file = self.file\n\n extra_data_offset, extra_data_length = \\\n c.get_extra_data_offset_and_length(self.int_hdr,\n self.data_offset, \n self.disk_length)\n \n raw_extra_data = c.read_extra_data(file.fd,\n extra_data_offset,\n extra_data_length,\n file.byte_ordering, \n file.word_size)\n\n edu = ExtraDataUnpacker(raw_extra_data, \n file.word_size,\n file.byte_ordering)\n\n return edu.get_data()\n\n def get_extra_data(self):\n '''Get extra data associated with the record, either by reading or\n using cached read\n\n '''\n if self._extra_data is None:\n self._extra_data = self.read_extra_data()\n\n return self._extra_data\n\n \n def get_type_and_num_words(self):\n '''Get the data type (as numpy type) and number of words as 2-tuple\n\n '''\n c = self.file._c_interface\n ntype, num_words = c.get_type_and_num_words(self.int_hdr)\n if ntype == 'integer':\n dtype = numpy.dtype(c.file_data_int_type)\n elif ntype == 'real':\n dtype = numpy.dtype(c.file_data_real_type)\n return dtype, num_words\n\n \n def get_data(self):\n '''Get the data array associated with the record\n\n '''\n c = self.file._c_interface\n file = self.file\n data_type, nwords = c.get_type_and_num_words(self.int_hdr)\n\n return c.read_record_data(file.fd,\n self.data_offset,\n self.disk_length,\n file.byte_ordering,\n file.word_size,\n self.int_hdr,\n self.real_hdr,\n data_type, \n nwords)\n\n\n#--- End: class\n\n\nif __name__ == '__main__':\n import sys\n \n path = sys.argv[1]\n f = File(path)\n print(f.format, f.byte_ordering, f.word_size)\n print(\"num variables: %s\" % len(f.vars))\n for varno, var in enumerate(f.vars):\n print() \n print(\"var %s: nz = %s, nt = %s\" % (varno, var.nz, var.nt))\n for recno, rec in enumerate(var.recs):\n print(\"var %s record %s\" % (varno, recno))\n print(\"hdr offset: %s\" % rec.hdr_offset)\n print(\"data offset: %s\" % rec.data_offset)\n print(\"disk length: %s\" % rec.disk_length)\n print(\"int hdr: %s\" % rec.int_hdr)\n print(\"real hdr: %s\" % rec.real_hdr)\n print(\"data: %s\" % rec.get_data())\n print(\"extra_data: %s\" % rec.get_extra_data())\n print(\"type %s, num words: %s\" % rec.get_type_and_num_words())\n # if recno == 1:\n # rec._extra_data['y'] += .01\n # print \"massaged_extra_data: %s\" % rec.get_extra_data()\n print(\"-----------------------\")\n \n print(\"all records\", var.recs)\n print(\"records grouped by extra data \", var.group_records_by_extra_data())\n print(\"===============================\")\n \n f.close_fd()\n \n # also read a record using saved metadata\n if f.vars:\n\n format = f.format\n byte_ordering = f.byte_ordering\n word_size = f.word_size\n myrec = f.vars[0].recs[0]\n hdr_offset = myrec.hdr_offset\n data_offset = myrec.data_offset\n disk_length = myrec.disk_length\n\n del(f)\n\n fnew = File(path,\n format = format,\n byte_ordering = byte_ordering,\n word_size = word_size,\n parse = False)\n\n rnew = Rec.from_file_and_offsets(fnew, hdr_offset, data_offset, disk_length)\n print(\"record read using saved file type and offsets:\")\n print(\"int hdr: %s\" % rnew.int_hdr)\n print(\"real hdr: %s\" % rnew.real_hdr)\n print(\"data: %s\" % rnew.get_data())\n print(\"extra data: %s\" % rnew.get_extra_data())\n print(\"nx = %s\" % rnew.int_hdr[18])\n print(\"ny = %s\" % rnew.int_hdr[17])\n rdata = open(\"recdata0.txt\", \"w\")\n for value in rnew.get_data():\n rdata.write(\"%s\\n\" % value)\n rdata.close()\n"
] |
[
[
"numpy.dtype"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ojipadeson/NLPGNN
|
[
"b9ecec2c6df1b3e40a54511366dcb6085cf90c34"
] |
[
"tests/GNN/nodes_graph_classfication/train_graphsage.py"
] |
[
"#! encoding:utf-8\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport sys\nfrom tqdm import tqdm\nfrom nlpgnn.datas import TUDataset\nfrom nlpgnn.metrics import Losess, Metric\nfrom nlpgnn.models import GraphSAGE\nfrom nlpgnn.gnn.utils import merge_batch_graph\nfrom sklearn.metrics import classification_report\n\ndim = 100\nnum_class = 2\ndrop_rate = 0.5\nepoch = 200\n\nlr = 0.001\nsplit = 10 # 10-fold\n\naccs_all = []\ndataloader = TUDataset(name=\"MUTAG\", split=split)\n\nfor block_index in range(split):\n\n model = GraphSAGE(dim, num_class, drop_rate)\n\n optimize = tf.optimizers.Adam(lr)\n\n cross_entropy = Losess.MaskSparseCategoricalCrossentropy()\n acc_score = Metric.SparseAccuracy()\n\n train_data, test_data = dataloader.load(block_index=block_index)\n train_bar = tqdm(range(epoch), unit=\"epoch\", file=sys.stdout)\n for i in train_bar:\n t = time.time()\n label_train = []\n predict_train = []\n loss_train = []\n for x, y, edge_index, edge_attr, batch in dataloader.sample(train_data,iterator_per_epoch=6,\n\n batch_size=32, mode=\"train\"):\n x, y, edge_index, edge_attr, batch = merge_batch_graph(x, y, edge_index,\n edge_attr, batch)\n x = tf.cast(x, tf.float32)\n with tf.GradientTape() as tape:\n predict = model(x, edge_index, batch, training=True)\n loss = cross_entropy(y, predict)\n predict_train.extend(tf.argmax(predict, -1))\n label_train.extend(y)\n loss_train.append(loss)\n\n grads = tape.gradient(loss, model.trainable_variables)\n optimize.apply_gradients(grads_and_vars=zip(grads, model.trainable_variables))\n report = classification_report(label_train, predict_train, digits=4, output_dict=True)\n acc = report[\"accuracy\"]\n train_bar.set_description('loss: {:.4f}, acc: {:.0f}%'.format(np.mean(loss_train), 100. * acc))\n if i != 0 and i % 50 == 0:\n lr_rate = optimize._get_hyper(\"learning_rate\")\n optimize._set_hyper('learning_rate', lr_rate * 0.5)\n # ------------------------------------------------------------------------\n label_test = []\n predict_test = []\n for x, y, edge_index, edge_attr, batch in dataloader.sample(test_data,iterator_per_epoch=6,\n batch_size=32, mode=\"test\"):\n x, y, edge_index, edge_attr, batch = merge_batch_graph(x, y, edge_index,\n edge_attr, batch)\n x = tf.cast(x, tf.float32)\n t_predict = model.predict(x, edge_index, batch, training=False)\n predict_test.extend(tf.argmax(t_predict, -1))\n label_test.extend(y)\n report = classification_report(label_test, predict_test, digits=4, output_dict=True)\n acc = report[\"accuracy\"]\n accs_all.append(acc)\n print(\"Test: Acc {:.5f}\".format(acc))\n\nprint(\"ACC: {:.4f}±{:.4f}\".format(np.mean(accs_all), np.std(accs_all)))\n"
] |
[
[
"tensorflow.cast",
"numpy.std",
"numpy.mean",
"tensorflow.optimizers.Adam",
"tensorflow.argmax",
"sklearn.metrics.classification_report",
"tensorflow.GradientTape"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"1.10",
"1.12"
]
}
] |
uvashisth/Sonification-using-Deep-Learning
|
[
"a0917e785c35aa5fadcbb258e938c58071b4e482"
] |
[
"Temporal-Based Approach/generate_music.py"
] |
[
"import torch\nimport torch.nn.functional as F\nimport configparser\nimport matplotlib.pyplot as plt\nimport os\nimport numpy as np\nplt.figure(figsize=(20,5))\n\nimport ast\n\nimport sys\n#to import parent-level modules\nos.chdir('Temporal-Based Approach')\nsys.path.append('..')\n\n\nfrom model.StackedLSTM import StackedLSTM\nfrom utils.normalize_testdata import normalize_testdata\nfrom influence import prediction_with_influence\nfrom postprocessing.postprocessing import PostProcessing\n\n\n#read the configuration file\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nbatch_size = int(config['Test']['test_batch_size'])\ninput_size = int(config['Common']['input_size'])\nhidden_size = int(config['Common']['hidden_size'])\nnum_layer = int(config['Common']['num_layer'])\nsequence_length = int(config['Common']['sequence_length'])\noutput_size = int(config['Common']['output_size'])\ntest_dir = config['Test']['test_dir']\nweights_loc = config['Common']['weights_loc']\n\n\ninitial_seq = torch.Tensor(ast.literal_eval(config['Save']['initial_seq']))\n# max_note = int(config['Save']['max_note'])\n# min_note = int(config['Save']['min_note'])\n\n#check if CUDA is available\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\ninitial_seq = initial_seq.to(device)\n\n#load the weights of the LSTM model\nmodel = StackedLSTM(input_size,hidden_size,num_layer,output_size, batch_size)\nmodel.load_state_dict(torch.load('{}'.format(weights_loc)))\n\n#set the model in evaluation mode\nmodel.eval()\nmodel.to(device)\n\n\n\ntest_list = os.listdir(test_dir)\nfor each_test_file in test_list:\n\n test_file_path = os.path.join(test_dir,each_test_file).replace('\\\\','/')\n testing_data = np.array(normalize_testdata(test_file_path, 50, 89))\n\n predicted_notes_list = prediction_with_influence(model, testing_data, initial_seq)\n\n print(predicted_notes_list)\n\n #convert tensor to list\n for i in range(len(predicted_notes_list)):\n predicted_notes_list[i]=predicted_notes_list[i].detach().cpu().numpy().tolist()\n\n\n postprocessing = PostProcessing()\n postprocessing.stich_notes(predicted_notes_list)\n postprocessing.music_generation(testing_data*89, each_test_file)\n\n\n \n"
] |
[
[
"torch.cuda.is_available",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
StarxSky/TF2_GPT-2
|
[
"770dc7bc559be4f24c65e94d4d21bbe1bb00703e"
] |
[
"iGPT/Core/Function.py"
] |
[
"import torch\r\nimport random\r\nimport numpy as np\r\n\r\nfrom torch.nn import functional as F\r\n\r\n\r\n\r\n# ==============================================\r\n# 设置种子\r\ndef set_seed(seed):\r\n np.random.seed(seed)\r\n random.seed(seed)\r\n torch.manual_seed(seed)\r\n torch.cuda.manual_seed_all(seed)\r\n# ==============================================\r\n\r\n\r\n# ==============================================\r\n# 设置 K值\r\ndef top_k_logits(logits, k):\r\n v, ix = torch.topk(logits, k)\r\n out = logits.clone()\r\n out[out < v[:, [-1]]] = -float('Inf')\r\n return out\r\n# ==============================================\r\n# 编写k-means函数\r\ndef kmeans(x, ncluster, niter=10):\r\n N, D = x.size()\r\n c = x[torch.randperm(N)[:ncluster]] # 随机初始化数据集群\r\n for i in range(niter):\r\n\r\n a = ((x[:, None, :] - c[None, :, :])**2).sum(-1).argmin(1) # 将所有像素分配给最近的标本元素\r\n # move each codebook element to be the mean of the pixels that assigned to it\r\n c = torch.stack([x[a==k].mean(0) for k in range(ncluster)])\r\n # re-assign any poorly positioned codebook elements\r\n nanix = torch.any(torch.isnan(c), dim=1)\r\n ndead = nanix.sum().item()\r\n print('done step %d/%d, re-initialized %d dead clusters' % (i+1, niter, ndead))\r\n c[nanix] = x[torch.randperm(N)[:ndead]] # re-init dead clusters\r\n return c\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# ==============================================\r\n\r\n# 生成实力参数调整,和功能适配\r\[email protected]_grad()\r\ndef sample(model, x, steps, temperature=1.0, sample=False, top_k=None):\r\n \"\"\"\r\n take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in\r\n the sequence, feeding the predictions back into the model each time. Clearly the sampling\r\n has quadratic complexity unlike an RNN that is only linear, and has a finite context window\r\n of block_size, unlike an RNN that has an infinite context window.\r\n \"\"\"\r\n block_size = model.get_block_size()\r\n model.eval()\r\n for k in range(steps):\r\n x_cond = x if x.size(1) <= block_size else x[:, -block_size:] # crop context if needed\r\n logits, _ = model(x_cond)\r\n # pluck the logits at the final step and scale by temperature\r\n logits = logits[:, -1, :] / temperature\r\n # optionally crop probabilities to only the top k options\r\n if top_k is not None:\r\n logits = top_k_logits(logits, top_k)\r\n # apply softmax to convert to probabilities\r\n probs = F.softmax(logits, dim=-1)\r\n # sample from the distribution or take the most likely\r\n if sample:\r\n ix = torch.multinomial(probs, num_samples=1)\r\n else:\r\n _, ix = torch.topk(probs, k=1, dim=-1)\r\n # append to the sequence and continue\r\n x = torch.cat((x, ix), dim=1)\r\n\r\n return x\r\n\r\n# ==============================================\r\n\r\n\r\n\r\ndef Conver_ONNX(model,dummy_input,save_model_name:str):\r\n # set the model to inference mode\r\n model.eval()\r\n\r\n\r\n # Export the model\r\n torch.onnx.export(model,\r\n # model being run\r\n dummy_input, # model input (or a tuple for multiple inputs)\r\n save_model_name, # where to save the model\r\n export_params=True, # store the trained parameter weights inside the model file\r\n opset_version=10, # the ONNX version to export the model to\r\n do_constant_folding=True, # whether to execute constant folding for optimization\r\n input_names=['modelInput'], # the model's input names\r\n output_names=['modelOutput'], # the model's output names\r\n dynamic_axes={'modelInput': {0: 'batch_size'}, # variable length axes\r\n 'modelOutput': {0: 'batch_size'}})\r\n print(\" \")\r\n print('Model has been converted to ONNX')\r\n\r\n"
] |
[
[
"torch.onnx.export",
"torch.nn.functional.softmax",
"numpy.random.seed",
"torch.cat",
"torch.isnan",
"torch.manual_seed",
"torch.randperm",
"torch.multinomial",
"torch.no_grad",
"torch.cuda.manual_seed_all",
"torch.topk"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tbloch1/HelioML
|
[
"ae308b1881bfd08d9dd7add53d304446423a3342"
] |
[
"book/_build/jupyter_execute/08/notebook.py"
] |
[
"#!/usr/bin/env python\n# coding: utf-8\n\n# # Notebook\n# \n# **Authors:** Colin Small ([email protected]), Matthew Argall ([email protected]), Marek Petrik ([email protected])\n\n# [](https://upload.wikimedia.org/wikipedia/commons/c/c9/NASA_Spacecraft_Finds_New_Magnetic_Process_in_Turbulent_Space.webm)\n\n# ## Introduction\n# Global-scale energy flow throughout Earth’s magnetosphere is catalyzed by processes that occur at Earth’s magnetopause (MP) in the electron diffusion region (EDR) of magnetic reconnection. Until the launch of the Magnetospheric Multiscale (MMS) mission, only rare, fortuitous circumstances permitted a glimpse of the electron dynamics that break magnetic field lines and energize plasma. MMS employs automated burst triggers onboard the spacecraft and a Scientist-in-the-Loop (SITL) on the ground to select intervals likely to contain diffusion regions. Only low-resolution survey data is available to the SITL, which is insufficient to resolve electron dynamics. A strategy for the SITL, then, is to select all MP crossings. This has resulted in over 35 potential MP EDR encounters but is labor- and resource-intensive; after manual reclassification, just ∼ 0.7% of MP crossings, or 0.0001% of the mission lifetime during MMS’s first two years contained an EDR.\n# \n# In this notebook, we develop a Long-Short Term Memory (LSTM) neural network to detect magnetopause crossings and automate the SITL classification process. An LSTM developed with this notebook has been implemented in the MMS data stream to provide automated predictions to the SITL.\n# \n# \n# This model facilitates EDR studies and helps free-up mission operation costs by consolidating manual classification processes into automated routines.\n\n# **Authors' notes:** \n# \n# 1. This notebook was developed after the development of the original model in use at the SDC. We have tried our best to replicate the development steps and hyperparameters of that model, but we cannot guarantee that models developed with this notebook will exactly match the performance of the original.\n# \n# 2. This notebook was designed on, and is best run on, Google Colab. It must either be run on Colab or on a machine with an NVIDIA GPU and cuDNN installed. If your machine does not have an NVIDIA GPU, does not have cuDNN installed, or if you run into issues running this notebook yourself, please open the notebook in Google Colab, which provides you with a virtual GPU to run the notebook. (If TF Keras is unable to identify a GPU to run on, make sure the notebook is set to use one by clicking the \"Runtime\" tab in the top menu bar, selecting \"Change runtime type\", selecting \"GPU\" in the dropdown menu under \"Hardware accelerator\", and clicking save. Colab will refresh your timetime, and you will need to re-run all cells.):\n\n# <a href=\"https://colab.research.google.com/drive/1Mh7GEQfXCR5xKvtKmbG9Uh8yAlOtFgwO?usp=sharing\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n# \n\n# ## Import Libraries\n# \n# To start, we import the neccesary libraries for this notebook.\n\n# In[1]:\n\n\nget_ipython().system('pip install nasa-pymms')\n\n\n# In[2]:\n\n\nfrom pathlib import Path\nfrom sklearn import preprocessing\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, LSTM, CuDNNLSTM, BatchNormalization, Bidirectional, Reshape, TimeDistributed\nfrom tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint\nfrom matplotlib import pyplot\nfrom sklearn.metrics import roc_curve, auc, confusion_matrix\nfrom keras import backend as K\nfrom pymms.sdc import mrmms_sdc_api as mms\nimport keras.backend.tensorflow_backend as tfb\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nplt.rcParams.update({'font.size': 18})\nimport datetime as dt\nimport os\nimport time\nimport sklearn\nimport scipy\nimport pickle\nimport random\nimport requests\n\n\n# ## Download, Preprocess, and Format MMS Data\n\n# After installing and importinng the neccesary libraries, we download our training and validation data. \n\n# In[3]:\n\n\nget_ipython().system('wget -O training_data.csv https://zenodo.org/record/3884266/files/original_training_data.csv?download=1')\nget_ipython().system('wget -O validation_data.csv https://zenodo.org/record/3884266/files/original_validation_data.csv?download=1')\n\n\n# After downloading the training and validation data, we preprocess our training data in preparation for training the neural network.\n\n# We first load the data we downloaded above. The data is a table of measurements from the MMS spacecraft, where each row represents individual measurements taken at a given time and where each column represents a feature (variable) recorded at that time. There is an additional column representing the ground truths for each measurement (whether this measurement was selected by a SITL or not). Then, we will adjust the formatting and datatypes of several of the columns and sort the data by the time of the measurement.\n\n# In[4]:\n\n\nmms_data = pd.read_csv('training_data.csv', index_col=0, infer_datetime_format=True,\n\t\t\t\t\t\t parse_dates=[0])\n\n\n# In[5]:\n\n\nmms_data[mms_data['selected'] == False]\n\n\n# We save references to data's index and column names for later use and additionally pop off the ground truths column. We will reattach the ground truths column after standardizing and interpolating the data.\n\n# In[6]:\n\n\nindex = mms_data.index\nselections = mms_data.pop(\"selected\")\ncolumn_names = mms_data.columns\n\n\n# Since there exists a possibility that the training contains missing data or data misreported by the MMS spacecraft (reported as either infinity or negative infinity), we need to fill in (interpolate) any missing data.\n\n# In[7]:\n\n\nmms_data = mms_data.replace([np.inf, -np.inf], np.nan)\nmms_data = mms_data.interpolate(method='time', limit_area='inside')\n\n\n# We normalize all features with standardization:\n# \n# \n# \n# Where x̄ is the mean of the data, and σ is the standard deviation of the data.\n# \n# Normalization ensures that the numerical values of all features of the data fall within a range from one to negative one and are centered around their mean (zero-mean and unit variance). Normalization improves the speed and performance of training neural networks as it unifies the scale by which differences in the data are represented without altering the data themselves.\n\n# In[8]:\n\n\nscaler = preprocessing.StandardScaler()\nmms_data = scaler.fit_transform(mms_data)\nmms_data = pd.DataFrame(mms_data, index, column_names)\nmms_data = mms_data.join(selections)\n\n\n# Next, we calculate class weights for our data classes (selected data points and non-selected data points). Since the distribution of our data is heavily skewed towards non-selected data points (just 1.9% of all data points in our training data were selected), it's important to give the class of selected data points a higher weight when training. In fact, without establishing these class weights our model would quickly acheive 98% accuracy by naively leaving all data points unselected.\n\n# In[9]:\n\n\nfalse_weight = len(mms_data)/(2*np.bincount(mms_data['selected'].values)[0])\ntrue_weight = len(mms_data)/(2*np.bincount(mms_data['selected'].values)[1])\n\n\n# Our entire dataset is not contigous, and it contains time intervals with no observations. Therefore, we break it up into contigous chunks. We can do so by breaking up the data into the windows that the SITLs used to review the data.\n\n# In[10]:\n\n\nsitl_windows = mms.mission_events('sroi', mms_data.index[0].to_pydatetime(), mms_data.index[-1].to_pydatetime(), sc='mms1')\nwindows = []\nfor start, end in zip(sitl_windows['tstart'], sitl_windows['tend']):\n window = mms_data[start:end]\n if not window.empty and len(window[window['selected']==True])>1:\n windows.append(window)\n\n\n# In[11]:\n\n\nwindows\n\n\n# Finally, we break up our data into individual sequences that will be fed to our neural network.\n\n# We define a SEQ_LEN variable that will determine the length of our sequences. This variable will also be passed to our network so that it knows how long of a data sequence to expect while training. The choice of sequence length is largely arbitrary.\n\n# In[12]:\n\n\nSEQ_LEN = 250\n\n\n# For each window, we assemble two sequences: an X_sequence containing individual data points from our training data and a y_sequence containing the truth values for those data points (whether or not those data points were selected by a SITL). \n# \n# We add those sequences to four collections: X_train and y_train containing X_sequences and y_sequences for our training data and X_test and y_test containing X_sequences and y_sequences for our testing data. We allocate 80% of the sequences to trainining and the remaining 20% to testing. \n\n# In[13]:\n\n\nwhile True:\n X_train, X_test, y_train, y_test = [], [], [], []\n\n sequences = []\n for i in range(len(windows)):\n X_sequence = []\n y_sequence = []\n\n if random.random() < 0.6:\n for value in windows[i].values:\n X_sequence.append(value[:-1])\n y_sequence.append(value[-1])\n if len(X_sequence) == SEQ_LEN:\n X_train.append(X_sequence.copy())\n \n y_train.append(y_sequence.copy())\n\n X_sequence = []\n y_sequence = []\n\n else:\n for value in windows[i].values:\n X_sequence.append(value[:-1])\n y_sequence.append(value[-1])\n if len(X_sequence) == SEQ_LEN:\n X_test.append(X_sequence.copy())\n \n y_test.append(y_sequence.copy())\n\n X_sequence = []\n y_sequence = []\n\n X_train = np.array(X_train)\n X_test = np.array(X_test)\n y_train = np.expand_dims(np.array(y_train), axis=2)\n y_test = np.expand_dims(np.array(y_test), axis=2)\n\n if len(X_train) > len(X_test):\n break\n\n\n# We can see how many sequences of data we have for training and testing, respectively:\n\n# In[14]:\n\n\nprint(f\"Number of sequences in training data: {len(X_train)}\")\nprint(f\"Number of sequences in test data: {len(X_test)}\")\n\n\n# ## Define and Train LSTM\n# \n# Now that we have processed our data into our training and test sets, we can begin to build and train and our LSTM.\n\n# First, we need to define a custom F1 score and weighted binary crossentropy functions.\n\n# An F1 score is a measure of a model's accuracy, calculated as a balance of the model's precision (the number of true positives predicted by the model divided by the total number of positives predicted by the model) and recall (the number of true positives predicted by the model divided by the number of actual positives in the data):\n# \n# \n# \n# We will evaluate our model using the F1 score since we want to strike a balance between the model's precision and recall. Remember, we cannot use true accuracy (the number of true positives and true negatives divided by the number of data points in the data) because of the imbalance between our classes.\n# \n\n# In[15]:\n\n\n# (Credit: Paddy and Kev1n91 from https://stackoverflow.com/a/45305384/3988976)\ndef f1(y_true, y_pred):\n def recall(y_true, y_pred):\n \"\"\"Recall metric.\n\n Only computes a batch-wise average of recall.\n\n Computes the recall, a metric for multi-label classification of\n how many relevant items are selected.\n \"\"\"\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n\n def precision(y_true, y_pred):\n \"\"\"Precision metric.\n\n Only computes a batch-wise average of precision.\n\n Computes the precision, a metric for multi-label classification of\n how many selected items are relevant.\n \"\"\"\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n precision = precision(y_true, y_pred)\n recall = recall(y_true, y_pred)\n return 2*((precision*recall)/(precision+recall+K.epsilon()))\n\n\n# Cross-entropy is a function used to determine the loss between a set of predictions and their truth values. The larger the difference between a prediction and its true value, the larger the loss will be. In general, many machine learning architectures (including our LSTM) are designed to minimize their given loss function. A perfect model will have a loss of 0.\n# \n# Binary cross-entropy is used when we only have two classes (in our case, selected or not selected) and weighted binary cross-entropy allows us to assign a weight to one of the classes. This weight can effectively increase or decrease the loss of that class. In our case, we have previously defined a variable *true_weight* to be the class weight for positive (selected) datapoints. We will pass that weight into the function.\n# \n# This cross-entropy function will be passed in to our model as our loss function.\n# \n# (Because the loss function of a model needs to be differentiable to perform gradient descent, we cannot use our F1 score as our loss function.)\n\n# In[16]:\n\n\n# (Credit: tobigue from https://stackoverflow.com/questions/42158866/neural-network-for-multi-label-classification-with-large-number-of-classes-outpu)\ndef weighted_binary_crossentropy(target, output):\n \"\"\"\n Weighted binary crossentropy between an output tensor \n and a target tensor. POS_WEIGHT is used as a multiplier \n for the positive targets.\n\n Combination of the following functions:\n * keras.losses.binary_crossentropy\n * keras.backend.tensorflow_backend.binary_crossentropy\n * tf.nn.weighted_cross_entropy_with_logits\n \"\"\"\n # transform back to logits\n _epsilon = tfb._to_tensor(tfb.epsilon(), output.dtype.base_dtype)\n output = tf.clip_by_value(output, _epsilon, 1 - _epsilon)\n output = tf.log(output / (1 - output))\n # compute weighted loss\n loss = tf.nn.weighted_cross_entropy_with_logits(targets=target,\n logits=output,\n pos_weight=true_weight)\n return tf.reduce_mean(loss, axis=-1)\n\n\n# Before building our LSTM, we define several hyperparameters that will define how the model is trained:\n# \n# EPOCHS: The number of times the model trains through our entire dataset\n# \n# BATCH_SIZE: The number of sequences that our model trains using at any given point\n# \n# LAYER_SIZE: The number of LSTM internal to each layer of the model.\n# \n# Choices for these hyperparameters are largely arbitrary and can be altered to tune our LSTM.\n\n# In[17]:\n\n\nEPOCHS = 100\nBATCH_SIZE = 128\nLAYER_SIZE = 300\n\n\n# We now define our LSTM.\n# \n# For this version of the model, we two bidirectional LSTM layers, two dropout layers, and one time distributed dense layer.\n# \n# Internally, an LSTM layer uses a for loop to iterate over the timesteps of a sequence, while maintaining states that encode information from those timesteps. Using these internal states, the LSTM learns the characteristics of our data (the X_sequences we defined earlier) and how those data relate to our expected output (the y_sequences we defined earlier). Normal (unidirectional) LSTMs only encode information from prior-seen timesteps. Bidirectional LSTMs can can encode information prior to and after a given timestep.\n# \n# With the addition of a dense layer, the LSTM will output a value between 0 and 1 that corresponds to the model's certainty about whether or not a timestep was selected by the SITL.\n# \n\n# In[18]:\n\n\nmodel_name = f\"{SEQ_LEN}-SEQ_LEN-{BATCH_SIZE}-BATCH_SIZE-{LAYER_SIZE}-LAYER_SIZE-{int(time.time())}\"\n\nmodel = Sequential()\n\nmodel.add(Bidirectional(LSTM(LAYER_SIZE, return_sequences=True), input_shape=(None, X_train.shape[2])))\n\nmodel.add(Dropout(0.4))\n\nmodel.add(Bidirectional(LSTM(LAYER_SIZE, return_sequences=True), input_shape=(None, X_train.shape[2])))\n\nmodel.add(Dropout(0.4))\n\nmodel.add(TimeDistributed(Dense(1, activation='sigmoid')))\n\nopt = tf.keras.optimizers.Adam()\n\nmodel.compile(loss=weighted_binary_crossentropy,\n optimizer=opt,\n metrics=['accuracy', f1, tf.keras.metrics.Precision()])\n\n\n# In[19]:\n\n\nmodel.summary()\n\n\n# We set our training process to save the best versions of our model according to the previously defined F1 score. Each epoch, if a version of the model is trained with a higher F1 score than the previous best, the model saved on disk will be overwritten with the current best model.\n\n# In[20]:\n\n\nfilepath = \"mp-dl-unh\" \ncheckpoint = ModelCheckpoint(filepath, monitor='val_f1', verbose=1, save_best_only=True, mode='max')\n\n\n# The following will train the model and save the training history for later visualization.\n\n# In[21]:\n\n\nhistory = model.fit(\n x=X_train, y=y_train,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n validation_data=(X_test, y_test),\n callbacks=[checkpoint],\n verbose=1,\n shuffle=False\n)\n\n\n# ## Performance Visualization\n\n# To evaluate the training of our model over time, we visualize the model's loss on its training and testing data.\n\n# In[22]:\n\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model Training Loss vs. Testing Loss by Epoch')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['train', 'testing'], loc='upper right')\nplt.show()\n\n\n# In[23]:\n\n\nplt.plot(history.history['f1'])\nplt.plot(history.history['val_f1'])\nplt.title('Model Training F1 vs. Testing F1 by Epoch')\nplt.ylabel('F1')\nplt.xlabel('Epoch')\nplt.legend(['train', 'testing'], loc='upper right')\nplt.show()\n\n\n# In[24]:\n\n\nplt.plot(history.history['precision'])\nplt.plot(history.history['val_precision'])\nplt.title('Model Training Precision vs. Testing Precision by Epoch')\nplt.ylabel('Precision')\nplt.xlabel('Epoch')\nplt.legend(['train', 'testing'], loc='upper right')\nplt.show()\n\n\n# (We can see that the model performs much better on its training data. This is expected, as the model learns to recreate the selections of the training data. We can also see that the performance of the model on the testing data decreases over time. This is evidence of the model overfitting. At some point, the model begins to naively recreate the selections of the training data rather than truly learning how to make selections. In practice, we effectively ignore this as we have already saved the version of the model with the best performance on the testing data - mitigating any overfitting.)\n\n# In[25]:\n\n\nmodel = tf.keras.models.load_model('/content/mp-dl-unh', {'weighted_binary_crossentropy':weighted_binary_crossentropy, 'f1':f1})\n\n\n# ## Model Performance Visualization\n# \n# Now that we have trained the model, we will visualize its selection-making ability compared to the SITLs.\n\n# Since we've already preprocessed the testing/training data into a format suitable for model training, we reload that data to preprocess it into a format suitable for evaluation.\n\n# In[26]:\n\n\nvalidation_data = pd.read_csv('training_data.csv', index_col=0, infer_datetime_format=True,\n\t\t\t\t\t\t parse_dates=[0])\n\n\n# We apply the same preprocessing steps to this data as we did for the original training and testing data.\n\n# In[27]:\n\n\nindex = validation_data.index\nselections = validation_data.pop(\"selected\")\ncolumn_names = validation_data.columns\n\n\n# In[28]:\n\n\nvalidation_data = validation_data.replace([np.inf, -np.inf], np.nan)\nvalidation_data = validation_data.interpolate(method='time', limit_area='inside')\n\n\n# In[29]:\n\n\nvalidation_data = scaler.transform(validation_data)\nvalidation_data = pd.DataFrame(validation_data, index, column_names)\nvalidation_data = validation_data.join(selections)\n\n\n# In[30]:\n\n\nvalidation_X = validation_data.values[:,:-1]\nvalidation_y = validation_data.values[:,-1]\n\n\n# Using the model we trainend earlier, we make test predctions on our validation data.\n\n# In[31]:\n\n\ntest_predictions = model.predict(np.expand_dims(validation_X, axis=0))\n\n\n# We visualize the true SITL selections made over the validation data by plotting the ground truth values for each datapoint in the data (where a 1 denotes that an individual datapoint was selected and a 0 denotes that it wasn't).\n# \n\n# In[32]:\n\n\nplt.figure(figsize=(28, 5))\nplt.plot(validation_y.astype(int))\nplt.title(\"Ground Truth (SITL) Selections by Datapoint\")\nplt.ylabel('Selected (1) or not (0)')\nplt.xlabel('Datapoint')\nplt.show()\n\n\n# ...and we do the same for the model's predictions.\n\n# In[33]:\n\n\nplt.figure(figsize=(28, 5))\nplt.plot(test_predictions.squeeze())\nplt.title(\"Model Predicted Selections by Datapoint\")\nplt.ylabel('Selection confidence (continous)')\nplt.xlabel('Datapoint')\nplt.show()\n\n\n# From this plot, we can see the continuous nature of the model's predictions. As mentioned earlier, the model outputs a continuous value between 0 and 1 for each datapoint that(very roughly) corresponds to its confidence in the selection of a point (i.e. an outputted value of 0.95 for a datapoint roughly means that the model is 95% certain that that point should be selected).\n\n# With this in mind, we filter the model's predictions so that only those predictions with a >= 50% probability of being a magnetopause crossing are kept. This choice of probability/certainty is known as the threshold. \n# \n# This choice of threshold is chosen to optimize between over-selecting datapoints (resulting in more false-positives) and under-selecting them (resulting in more false-negatives).\n# \n# As an example, consider an email server's spam-detection system. Such a system might have a fairly high threshold (>99%), as you don't want to accidentally send a user's non-spam email to their spam inbox. At the same time, it's okay if a handful of spam emails make it through their regular inbox.\n# \n# In our case, we can afford to over-select datapoints as we do not want to miss out on any potential magnetopause crossings.\n\n# In[34]:\n\n\nt_output = [0 if x < 0.5 else 1 for x in test_predictions.squeeze()]\nplt.figure(figsize=(28, 5))\nplt.plot(t_output)\nplt.title(\"Filtered Model Predictions by Datapoint\")\nplt.ylabel('Selected (1) or not (0)')\nplt.xlabel('Datapoint')\nplt.show()\n\n\n# ## Model Validation\n# \n# Although we have already validated our model on data it has not seen (the testing set), we need to make sure that its ability to select magnetopause crossings is transferable to another range of data.\n\n# We load a third set of data, the validation set, which serves as an independent check on the model. \n\n# In[35]:\n\n\nvalidation_data = pd.read_csv('validation_data.csv', index_col=0, infer_datetime_format=True,\n\t\t\t\t\t\t parse_dates=[0])\n\n\n# We apply the same preprocessing steps to the validation data as we did for the training and testing data.\n\n# In[36]:\n\n\nindex = validation_data.index\nselections = validation_data.pop(\"selected\")\ncolumn_names = validation_data.columns\n\n\n# In[37]:\n\n\nvalidation_data = validation_data.replace([np.inf, -np.inf], np.nan)\nvalidation_data = validation_data.interpolate(method='time', limit_area='inside')\n\n\n# However, we standardize the validation data to the scale of the training/testing data.\n\n# In[38]:\n\n\nvalidation_data = scaler.transform(validation_data)\nvalidation_data = pd.DataFrame(validation_data, index, column_names)\nvalidation_data = validation_data.join(selections)\n\n\n# In[39]:\n\n\nvalidation_X = validation_data.values[:,:-1]\nvalidation_y = validation_data.values[:,-1]\n\n\n# Using the model we trained earlier, we make test predctions on our validation data.\n\n# In[40]:\n\n\ntest_predictions = model.predict(np.expand_dims(validation_X, axis=0))\n\n\n# We visualize the true SITL selections made over the validation data in the same way we did above.\n# \n\n# In[41]:\n\n\nplt.figure(figsize=(28, 5))\nplt.plot(validation_y.astype(int))\nplt.title(\"Ground Truth (SITL) Selections by Datapoint\")\nplt.ylabel('Selected (1) or not (0)')\nplt.xlabel('Datapoints')\nplt.show()\n\n\n# ...and we do the same for the model's predictions.\n\n# In[42]:\n\n\nplt.figure(figsize=(28, 5))\nplt.plot(test_predictions.squeeze())\nplt.title(\"Model Predicted Selections by Datapoint\")\nplt.ylabel('Selection confidence (continous)')\nplt.xlabel('Datapoints')\nplt.show()\n\n\n# Once again, we filter the model's predictions so that only those predictions with a >= 50% probability of being a magnetopause crossing are kept.\n\n# In[43]:\n\n\nt_output = [0 if x < 0.5 else 1 for x in test_predictions.squeeze()]\nplt.figure(figsize=(28, 5))\nplt.plot(t_output)\nplt.title(\"Filtered Model Predictions by Datapoint\")\nplt.ylabel('Selected (1) or not (0)')\nplt.xlabel('Datapoints')\nplt.show()\n\n\n# We now plot a receiver operating characteristic (ROC) curve based on the model's performance over the evaluation data. \n# \n# An ROC curve will plot a model's true-positive vs. false positive rates of predictions for varying choices of thresholds. As the threshold approaches 1, the false positive rate and the true positive rates approach 0, as every prediction made is over the threshold and is thus considered a selection. As the threshold approaches 1, the false positive rate and the true positive rates approach 0, as no prediction made surpasses the threshold of 1.\n# \n# While we can use the plot to determine where we want to set our threshold (considering the importance of under-selecting or over-selecting points), it is more often used to get a sense of the performance of our model.\n# \n# To do so, we calculate the total area under the ROC curve. This area is equal to the probability that the model will output a higher prediction value for a randomly chosen datapoint whose ground truth was \"selected\" than for a randomly chosen datapoint whose ground truth value was \"not selected\".\n\n# In[44]:\n\n\nfpr, tpr, thresholds = roc_curve(validation_y.astype(int), test_predictions.squeeze())\nlw = 2\nplt.plot(fpr, tpr, color='darkorange',\n lw=lw, label='ROC curve')\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.0])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('ROC curve - AUC = {:.2f}'.format(auc(fpr, tpr)))\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\n# Finally, we generate a list of predicted selection windows. The following code groups contiguous selected datapoints into windows and list the start and dates of those windows.\n# \n\n# In[45]:\n\n\npredicts_df = pd.DataFrame()\npredicts_df.insert(0, \"time\", validation_data.index)\npredicts_df.insert(1, \"prediction\", t_output)\npredicts_df['group'] = (predicts_df.prediction != predicts_df.prediction.shift()).cumsum()\npredicts_df = predicts_df.loc[predicts_df['prediction'] == True]\nselections = pd.DataFrame({'BeginDate' : predicts_df.groupby('group').time.first(), \n 'EndDate' : predicts_df.groupby('group').time.last()})\nselections = selections.set_index('BeginDate')\n\n\n# In[46]:\n\n\nselections\n\n\n# ## Conclusion\n# \n# The above steps have walked you through the development of the GLS-MP model currently deployed at NASA to assist SITLs with data selection. \n# \n# Since being implemented into the near real-time data stream, the GLS-MP model has selected 78% of SITL-identified MP crossings in the outbound leg of its orbit, 44% more than the existing MP-crossing selection algorithm onboard MMS spacecraft (ABS). \n# \n# The model and its associated paper represent the first attempt to introduce machine learning into critical mission operations. \n# \n# Additionally, the nature of the model and its training make it easily adoptable for use in other phenomena-detection tasks, such as identifying reconnection jets or Kelvin-Helmholtz waves in the magntopause. By expanding GLS-MP into a hierarchy of machine learning models, MMS progresses toward full autonomy in its burst management system, thereby reducing operations costs and transferring information and resources back to answering fundamental science questions.\n"
] |
[
[
"matplotlib.pyplot.legend",
"tensorflow.keras.models.load_model",
"numpy.expand_dims",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.rcParams.update",
"tensorflow.keras.layers.Dropout",
"pandas.read_csv",
"tensorflow.keras.models.Sequential",
"matplotlib.pyplot.figure",
"tensorflow.keras.callbacks.ModelCheckpoint",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.metrics.Precision",
"sklearn.metrics.auc",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"tensorflow.clip_by_value",
"tensorflow.reduce_mean",
"matplotlib.pyplot.xlim",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.LSTM",
"tensorflow.log",
"numpy.bincount",
"matplotlib.pyplot.xlabel",
"sklearn.preprocessing.StandardScaler",
"tensorflow.nn.weighted_cross_entropy_with_logits"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
IshmaelAsabere/Machine_Learning-Various-Topics
|
[
"2c663ab73e2631522dac0fa1ec49042aa2088da4",
"2c663ab73e2631522dac0fa1ec49042aa2088da4",
"2c663ab73e2631522dac0fa1ec49042aa2088da4"
] |
[
"04 How To Load Machine Learning Data/load_csv_np_url.py",
"24 Compare Machine Learning Algorithms/race_algorithms.py",
"04 How To Load Machine Learning Data/load_csv_np.py"
] |
[
"# Load CSV from URL using NumPy\nfrom numpy import loadtxt\nfrom urllib.request import urlopen\nurl = 'https://goo.gl/bDdBiA'\nraw_data = urlopen(url)\ndataset = loadtxt(raw_data, delimiter=\",\")\nprint(dataset.shape)\n",
"# Compare Algorithms\nfrom pandas import read_csv\nfrom matplotlib import pyplot\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n# load dataset\nfilename = 'pima-indians-diabetes.data.csv'\nnames = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']\ndataframe = read_csv(filename, names=names)\narray = dataframe.values\nX = array[:,0:8]\nY = array[:,8]\n# prepare models\nmodels = []\nmodels.append(('LR', LogisticRegression(solver='liblinear')))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('CART', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('SVM', SVC()))\n# evaluate each model in turn\nresults = []\nnames = []\nscoring = 'accuracy'\nfor name, model in models:\n\tkfold = KFold(n_splits=10, random_state=7, shuffle=True)\n\tcv_results = cross_val_score(model, X, Y, cv=kfold, scoring=scoring)\n\tresults.append(cv_results)\n\tnames.append(name)\n\tmsg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n\tprint(msg)\n# boxplot algorithm comparison\nfig = pyplot.figure()\nfig.suptitle('Algorithm Comparison')\nax = fig.add_subplot(111)\npyplot.boxplot(results)\nax.set_xticklabels(names)\npyplot.show()\n",
"# Load CSV using NumPy\nfrom numpy import loadtxt\nfilename = 'pima-indians-diabetes.data.csv'\nraw_data = open(filename, 'rt')\ndata = loadtxt(raw_data, delimiter=\",\")\nprint(data.shape)\n"
] |
[
[
"numpy.loadtxt"
],
[
"matplotlib.pyplot.boxplot",
"pandas.read_csv",
"sklearn.model_selection.cross_val_score",
"sklearn.linear_model.LogisticRegression",
"sklearn.naive_bayes.GaussianNB",
"sklearn.model_selection.KFold",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.svm.SVC",
"sklearn.discriminant_analysis.LinearDiscriminantAnalysis",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
],
[
"numpy.loadtxt"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kniazevgeny/GPT2sQA-1
|
[
"b319016f51847a25ea3e9cd9c8450d58831cc42a"
] |
[
"gpt2sqa/gpt2/gpt2lmhead.py"
] |
[
"from torch import nn\n\n\nclass GPT2LMHead(nn.Module):\n \"\"\" Language Model Head for the transformer \"\"\"\n\n def __init__(self, model_embeddings_weights, config):\n super(GPT2LMHead, self).__init__()\n self.n_embd = config.n_embd\n self.set_embeddings_weights(model_embeddings_weights)\n\n def set_embeddings_weights(self, model_embeddings_weights):\n embed_shape = model_embeddings_weights.shape\n self.decoder = nn.Linear(embed_shape[1], embed_shape[0], bias=False)\n self.decoder.weight = model_embeddings_weights # Tied weights\n\n def forward(self, hidden_state):\n # Truncated Language modeling logits (we remove the last token)\n # h_trunc = h[:, :-1].contiguous().view(-1, self.n_embd)\n lm_logits = self.decoder(hidden_state)\n return lm_logits\n\n\nclass GPT2MultipleChoiceHead(nn.Module):\n \"\"\" Classifier Head for the transformer \"\"\"\n\n def __init__(self, config):\n super(GPT2MultipleChoiceHead, self).__init__()\n self.n_embd = config.n_embd\n self.linear = nn.Linear(config.n_embd, 1)\n\n nn.init.normal_(self.linear.weight, std=0.02)\n nn.init.normal_(self.linear.bias, 0)\n\n def forward(self, hidden_states, mc_token_ids):\n # Classification logits\n # hidden_state (bsz, num_choices, seq_length, hidden_size)\n # mc_token_ids (bsz, num_choices)\n mc_token_ids = mc_token_ids.unsqueeze(-1).unsqueeze(-1).expand(-1, -1, -1, hidden_states.size(-1))\n # (bsz, num_choices, 1, hidden_size)\n multiple_choice_h = hidden_states.gather(2, mc_token_ids).squeeze(2)\n # (bsz, num_choices, hidden_size)\n multiple_choice_logits = self.linear(multiple_choice_h).squeeze(-1)\n # (bsz, num_choices)\n return multiple_choice_logits\n"
] |
[
[
"torch.nn.Linear",
"torch.nn.init.normal_"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
k920049/brunch-hgru
|
[
"f832de2d7d8e1e74a58e1a4851f57dfa6751e717",
"f832de2d7d8e1e74a58e1a4851f57dfa6751e717",
"f832de2d7d8e1e74a58e1a4851f57dfa6751e717"
] |
[
"model.py",
"pipeline/tensorflow/Datasets.py",
"torchmodel.py"
] |
[
"import tensorflow as tf\nimport numpy as np\nimport datetime\n\nfrom model.tensorflow.Wrapper import HierarchicalRNNCell\nfrom model.tensorflow.Loss import RankingLoss\nfrom pipeline.tensorflow.Datasets import Datasets\n\nfrom tensorflow.python.keras.layers.recurrent import RNN, GRUCell\nfrom tensorflow.python.keras.layers.embeddings import Embedding\nfrom tensorflow.python.keras.layers.wrappers import TimeDistributed\nfrom tensorflow.python.keras.callbacks import ModelCheckpoint, TensorBoard\n\n\ndef custom_loss(y_true, y_pred):\n return tf.reduce_sum(y_pred)\n\ndef custom_acc(y_true, y_pred):\n y_true = tf.squeeze(y_true, axis=2)\n y_pred = tf.squeeze(y_pred, axis=2)\n\n num_item = tf.math.reduce_sum(y_true, axis=1, keepdims=True)\n accuracy = y_true - y_pred\n accuracy = tf.math.reduce_sum(accuracy, axis=1, keepdims=True)\n accuracy = tf.divide(accuracy, num_item)\n\n return 1.0 - tf.math.reduce_mean(accuracy)\n\n\nclass HierarchicalRecommender(object):\n\n def __init__(self,\n history_length=30,\n num_negatives=4,\n num_units=256,\n batch_size=256,\n epoch=10):\n self.history_length = history_length\n self.num_negatives = num_negatives\n self.num_units = num_units\n self.batch_size = batch_size\n self.epoch = epoch\n\n self.embedding_mx = np.load(\"./data/brunch/embedding.npy\")\n self.embedding_mx = np.concatenate([self.embedding_mx, np.zeros((1, self.embedding_mx.shape[1]))], axis=0)\n self.vocab_size = self.embedding_mx.shape[0]\n self.embedding_dim = self.embedding_mx.shape[1]\n\n self.model = self._build_model()\n\n def _build_model(self):\n with tf.name_scope(\"inputs\"):\n user_input = tf.keras.Input(shape=(self.history_length, 3))\n label_input = tf.keras.Input(shape=(self.history_length, 1))\n mask_input = tf.keras.Input(shape=(self.history_length, 1))\n\n with tf.name_scope(\"layers\"):\n embedding = Embedding(input_dim=self.vocab_size,\n output_dim=self.embedding_dim,\n weights=[self.embedding_mx],\n trainable=False)\n session_cells = [\n GRUCell(units=self.num_units, name=\"sesion_rnn_01\"),\n GRUCell(units=self.num_units, name=\"sesion_rnn_02\")\n # GRUCell(units=self.num_units, name=\"sesion_rnn_03\")\n ]\n user_cells = [\n GRUCell(units=self.num_units, name=\"user_rnn_01\"),\n GRUCell(units=self.num_units, name=\"user_rnn_02\")\n # GRUCell(units=self.num_units, name=\"user_rnn_03\")\n ]\n cell = HierarchicalRNNCell(user_cells=user_cells,\n session_cells=session_cells,\n embedding_layer=embedding)\n recurrent = RNN(cell=cell,\n return_sequences=True,\n return_state=True)\n\n with tf.name_scope(\"loss\"):\n\n loss = RankingLoss(num_units=self.num_units,\n num_sampled=self.num_negatives,\n num_classes=self.vocab_size - 1,\n num_true=1,\n history_length=self.history_length,\n remove_accidental_hits=True)\n\n time_distributed = TimeDistributed(loss, input_shape=(self.history_length, self.num_units + 1))\n\n with tf.name_scope(\"model\"):\n tensor = recurrent(inputs=user_input)\n outputs = tensor[0]\n outputs = tf.concat([outputs, label_input], axis=2)\n tensor = time_distributed(outputs)\n # loss\n loss = tf.gather(tensor, [0], axis=2)\n loss = tf.multiply(loss, mask_input, name=\"loss\")\n # prediction\n prediction = tf.gather(tensor, [1], axis=2)\n prediction = tf.multiply(prediction, mask_input, name=\"prediction\")\n # build the model\n model = tf.keras.Model(inputs=[user_input, label_input, mask_input], outputs=[loss, prediction])\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),\n loss={'tf_op_layer_loss': custom_loss,\n 'tf_op_layer_prediction': 'binary_crossentropy'},\n loss_weights={'tf_op_layer_loss': 1.0,\n 'tf_op_layer_prediction': 0.0},\n metrics={'tf_op_layer_prediction': custom_acc})\n return model\n\n def train(self):\n dataset = Datasets(\"./data/brunch\")\n data, label, mask = dataset.read()\n print(data.shape, label.shape, mask.shape)\n # save model every 5 epoch\n filepath = \"./data/checkpoints/init/model-{epoch:02d}.hdf5\"\n checkpoint = ModelCheckpoint(filepath,\n save_weights_only=False,\n verbose=1)\n # display tensorboard\n log_dir = \"./data/logs/fit/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n tensorboard_callback = TensorBoard(log_dir=log_dir, histogram_freq=1)\n\n self.model.fit(x=[data, label, mask],\n y=[mask, mask],\n steps_per_epoch=None,\n batch_size=self.batch_size,\n shuffle=True,\n epochs=10,\n validation_split=0.1,\n callbacks=[checkpoint, tensorboard_callback])\n\n\nif __name__ == \"__main__\":\n HierarchicalRecommender().train()\n",
"import pandas as pd\nimport numpy as np\nimport os\n\nfrom fire import Fire\nfrom pipeline.tensorflow.Reader import Reader\n\nclass Datasets(Reader):\n\n def __init__(self, data_path):\n\n self.data_path = data_path\n\n super(Datasets, self).__init__()\n\n def read(self):\n\n train_file = os.path.join(self.data_path, \"train.npy\")\n label_file = os.path.join(self.data_path, \"label.npy\")\n mask_file = os.path.join(self.data_path, \"mask.npy\")\n\n candidate_train = np.transpose(np.load(train_file), axes=[0, 2, 1])\n candidate_label = np.transpose(np.load(label_file), axes=[0, 2, 1])\n candidate_mask = np.transpose(np.load(mask_file), axes=[0, 2, 1])\n\n message = \"At least one of the dimension in the input data doesn't match with others\"\n assert len(candidate_train) == len(candidate_label), message\n assert len(candidate_label) == len(candidate_mask), message\n assert len(candidate_mask) == len(candidate_train), message\n\n train = []\n label = []\n mask = []\n for i in range(len(candidate_train)):\n if np.sum(candidate_mask[i]) >= 10.0:\n train.append(candidate_train[i])\n label.append(candidate_label[i])\n mask.append(candidate_mask[i])\n\n return np.array(train)[0:5000], np.array(label)[0:5000], np.array(mask)[0:5000]\n\n def write(self):\n pass\n\n def show(self, n):\n train, label, mask = self.read()\n\n print(train.shape, label.shape, mask.shape)\n\n # train = train[:n]\n # label = label[:n]\n # mask = mask[:n]\n #\n # for t, l, m in zip(train, label, mask):\n # for elem_t, elem_l, elem_m in zip(t, l, m):\n # print(elem_t, elem_l, elem_m)\n\n\nif __name__ == \"__main__\":\n Fire(Datasets)",
"import torch\n\nfrom torch import optim\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch import Tensor\n\nfrom fire import Fire\nfrom tqdm import tqdm\nimport numpy as np\n\nfrom model.torch.Wrapper import HierarchicalRNN\nfrom model.torch.Loss import SampledSoftmax\nfrom pipeline.torch.Dataset import BrunchDataset, generate_batches\n\n\nclass HierarchicalRecommender(object):\n\n def __init__(self,\n epoch=10,\n batch_size=128,\n history_length=128,\n hidden_size=256,\n nsampled=4,\n bptt_step=128,\n optimizer=\"adam\",\n pretrained_weight=\"./data/brunch/embedding.npy\",\n model_path=\"./data/checkpoints/torch/best_model.ckpt\"):\n\n self.epoch = epoch\n self.batch_size = batch_size\n self.history_length = history_length\n self.bptt_step = bptt_step\n self.optimizer = optimizer\n self.model_path = model_path\n\n self.pretrained_weight = np.load(pretrained_weight)\n self.ntokens = self.pretrained_weight.shape[0]\n self.embedding_dim = self.pretrained_weight.shape[1]\n self.hidden_size = hidden_size\n\n self.train_dataset = BrunchDataset()\n\n self.embedding = torch.nn.Embedding.from_pretrained(torch.FloatTensor(self.pretrained_weight))\n\n self.rnn = HierarchicalRNN(word_vec_dim=self.embedding_dim,\n hidden_size=hidden_size,\n session_num_layers=2,\n user_num_layers=2,\n dropout_p=0.1,\n bptt_step=bptt_step)\n\n self.sampled_softmax = SampledSoftmax(ntokens=self.ntokens,\n nsampled=nsampled,\n nhid=hidden_size,\n tied_weight=None)\n\n parameters = [elem for elem in self.rnn.parameters()] + [elem for elem in self.sampled_softmax.parameters()]\n self.optimizer = optim.Adam(params=parameters,\n lr=0.001)\n\n def train(self):\n try:\n best_loss = float(\"Inf\")\n\n for idx in range(1, self.epoch + 1):\n self.train_epoch(idx)\n loss = self.eval_epoch(idx)\n\n if loss < best_loss:\n with open(self.model_path, 'wb') as f:\n model_state = {\n 'cell': self.cell,\n 'sampled_softmax': self.sampled_softmax,\n }\n torch.save(model_state, f)\n best_loss = loss\n\n except KeyboardInterrupt:\n print('Exiting from training early')\n\n def train_epoch(self, epoch):\n \"\"\"\n Train one more epoch\n :return: Nothing\n \"\"\"\n self.train_dataset.set_split(\"train\")\n self.embedding.train()\n self.rnn.train()\n self.sampled_softmax.train()\n progress_bar = tqdm(generate_batches(self.train_dataset,\n batch_size=self.batch_size))\n\n for batch_idx, batch_dict in enumerate(progress_bar):\n\n self.optimizer.zero_grad()\n total_loss = 0\n\n session_input = batch_dict[\"session_input\"].long()\n session_output = batch_dict[\"session_output\"].long()\n session_mask = batch_dict[\"session_mask\"].float()\n user_mask = batch_dict[\"user_mask\"].float()\n mask = batch_dict[\"mask\"].float()\n\n session_state = None\n user_state = None\n\n for step in range(0, session_input.size(1), self.bptt_step):\n session_state = self.repackage_hidden(session_state)\n user_state = self.repackage_hidden(user_state)\n\n input_embedding = self.embedding(session_input[:, step: step + self.bptt_step])\n output, session_state, user_state = self.rnn(input_embedding,\n session_state=session_state,\n user_state=user_state,\n session_mask=session_mask[:, step: step + self.bptt_step],\n user_mask=user_mask[:, step: step + self.bptt_step])\n # compute the top-1 ranking loss\n current_session_output = session_output[:, step: step + self.bptt_step].contiguous()\n curent_mask = mask[:, step: step + self.bptt_step].contiguous()\n logits, new_targets = self.sampled_softmax(output.view(-1, output.size(2)), current_session_output.view(-1))\n\n true_logit = logits[:, 0].unsqueeze(1)\n sampled_logit = logits[:, 1:]\n loss = torch.sigmoid(sampled_logit - true_logit) + torch.sigmoid(torch.mul(sampled_logit, sampled_logit))\n loss = torch.mean(loss, dim=1)\n loss = torch.mul(loss, curent_mask.view(-1))\n loss = torch.sum(loss)\n\n loss.backward()\n\n torch.nn.utils.clip_grad_norm(self.rnn.parameters(), 0.25)\n torch.nn.utils.clip_grad_norm(self.sampled_softmax.parameters(), 0.25)\n self.optimizer.step()\n\n total_loss = total_loss + loss.data\n\n message = '| Train | epoch {:3d} | {:5d}/{:5d} batches | loss {:5.2f} |'.format(\n epoch,\n batch_idx * self.batch_size,\n len(self.train_dataset),\n total_loss)\n progress_bar.set_description(message)\n\n def eval_epoch(self, epoch):\n \"\"\"\n Evaluate what we have learned\n :return: loss\n \"\"\"\n\n self.train_dataset.set_split(\"valid\")\n self.embedding.eval()\n self.rnn.eval()\n self.sampled_softmax.eval()\n\n total_loss = 0\n idx = 0\n\n for batch_idx, batch_dict in enumerate(generate_batches(self.train_dataset, batch_size=self.batch_size)):\n\n idx = batch_idx\n\n session_input = pad_sequence(batch_dict[\"session_input\"], batch_first=True)\n session_output = pad_sequence(batch_dict[\"session_output\"], batch_first=True)\n session_mask = pad_sequence(batch_dict[\"session_mask\"], batch_first=True)\n user_mask = pad_sequence(batch_dict[\"user_mask\"], batch_first=True)\n mask = pad_sequence(batch_dict[\"mask\"], batch_first=True)\n\n session_state = None\n user_state = None\n\n for step in range(0, session_input.size(1), self.bptt_step):\n input_embedding = self.embedding(session_input[:, step + self.bptt_step])\n output, session_state, user_state = self.rnn(input_embedding,\n session_state=session_state,\n user_state=user_state,\n session_mask=session_mask[:, step + self.bptt_step],\n user_mask=user_mask[:, step + self.bptt_step])\n # compute the top-1 ranking loss\n session_output = session_output[:, step: step + self.bptt_step].contiguous()\n mask = mask[:, step: step + self.bptt_step].contiguous()\n logits, new_targets = self.sampled_softmax(output.view(-1, output.size(2)), session_output.view(-1))\n true_logit = logits[:, 0]\n sampled_logit = logits[:, 1:]\n loss = torch.sigmoid(sampled_logit - true_logit) + torch.sigmoid(torch.mul(sampled_logit, sampled_logit))\n loss = torch.mean(loss, dim=1)\n loss = torch.mul(loss, mask.view(-1))\n loss = torch.sum(loss)\n\n total_loss = total_loss + loss\n\n message = '| Evaluation | epoch {:3d} | loss {:5.2f} |'.format(epoch, total_loss / idx)\n print(message)\n return total_loss\n\n def repackage_hidden(self, h):\n \"\"\"Wraps hidden states in new Variables, to detach them from their history.\"\"\"\n if h is None:\n return h\n if type(h) == Tensor:\n return h.detach()\n else:\n return tuple(self.repackage_hidden(v) for v in h)\n\n\nif __name__ == \"__main__\":\n # Fire(HierarchicalRecommender)\n HierarchicalRecommender().train()\n"
] |
[
[
"tensorflow.python.keras.layers.recurrent.GRUCell",
"tensorflow.concat",
"tensorflow.python.keras.callbacks.TensorBoard",
"tensorflow.reduce_sum",
"tensorflow.python.keras.layers.recurrent.RNN",
"tensorflow.keras.Input",
"tensorflow.squeeze",
"tensorflow.divide",
"tensorflow.gather",
"tensorflow.math.reduce_sum",
"tensorflow.name_scope",
"numpy.load",
"numpy.zeros",
"tensorflow.python.keras.layers.embeddings.Embedding",
"tensorflow.keras.Model",
"tensorflow.python.keras.callbacks.ModelCheckpoint",
"tensorflow.python.keras.layers.wrappers.TimeDistributed",
"tensorflow.multiply",
"tensorflow.math.reduce_mean",
"tensorflow.keras.optimizers.Adam"
],
[
"numpy.load",
"numpy.array",
"numpy.sum"
],
[
"torch.optim.Adam",
"torch.mean",
"torch.sigmoid",
"torch.nn.utils.rnn.pad_sequence",
"torch.sum",
"torch.mul",
"torch.FloatTensor",
"numpy.load",
"torch.save"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mobbslab/foraging_paper
|
[
"d1d3f68ce3980112e274633be6fe4d4e9f7d0367"
] |
[
"code/foraging_firstlevel_univariate.py"
] |
[
"# Limit the number of threads used by numpy\nimport os\nos.environ[\"MKL_NUM_THREADS\"] = \"1\" \nos.environ[\"NUMEXPR_NUM_THREADS\"] = \"1\" \nos.environ[\"OPENBLAS_NUM_THREADS\"] = \"1\"\nos.environ[\"OMP_NUM_THREADS\"] = \"1\" \n\nimport os\nimport re\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import scale\nimport nibabel as nb\nimport itertools\nfrom lyman import glm, signals\nfrom lyman.utils import matrix_to_image, image_to_matrix\nimport time\nimport time\nfrom nipype.interfaces.base import Bunch\nimport json\nfrom joblib import dump, load\nimport uuid\nimport shutil\n\n\nif __name__ == \"__main__\":\n \n testing = False\n n_test = 50 \n\n # Get slurm run ID\n try:\n runID = int(os.environ['SLURM_ARRAY_TASK_ID'])\n except:\n runID = 72\n\n # Select subject, session and run to be processed\n subs = pd.read_csv('../subject_list.txt', header=None)\n sub_sess_run = list(itertools.product(subs[0], ['d1', 'd2'], range(4)))\n subject, this_session, this_run = sub_sess_run[runID-1]\n \n print(\"RUNNING SUBJECT {0}, SESSION {1}, RUN {2}\".format(subject, this_session, this_run))\n print(\"Parallel processing with {0} cores\".format(len(os.sched_getaffinity(0))))\n \n\n # Important variabkles\n base_dir = os.path.abspath('../data/derivatives/')\n output_dir = os.path.join(base_dir, 'univariate', 'first_level', \n 'sub-{0}'.format(subject), 'sess-{0}'.format(this_session), 'run-{0}'.format(this_run))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n print(\"OUTPUT DIRECTORY = {0}\".format(output_dir))\n \n # Load confounds\n conf = pd.read_csv(os.path.join(base_dir, \n 'fmriprep/sub-{0}/ses-{1}/func/sub-{0}_ses-{1}_'\n 'task-mos_run-0{2}_desc-confounds_regressors.tsv'.format(subject, this_session, this_run+1)), sep='\\t')\n confounds= conf[['dvars', 'framewise_displacement', 'trans_x', 'trans_y', \n 'trans_z', 'rot_x', 'rot_y', 'rot_z', 'csf', 'white_matter']]\n \n \n # Get events\n trial_types = []\n\n ev = pd.read_csv(os.path.join(base_dir, \n 'fmriprep/sub-{0}/ses-{1}/func/sub-{0}_ses-{1}_'\n 'task-mos_run-0{2}_events.tsv'.format(subject, this_session, this_run+1)))[['trial_type', \n 'onset', \n 'duration', \n 'competitor_difference']]\n ev.loc[ev['trial_type'].isin(['blocked_with_decision_safe', \n 'blocked_with_decision_threat']), \n 'trial_type'] = ev.loc[ev['trial_type'].isin(['blocked_with_decision_safe', \n 'blocked_with_decision_threat']), \n 'trial_type'] + '_' + \\\n ev.loc[ev['trial_type'].isin(['blocked_with_decision_safe', \n 'blocked_with_decision_threat']), \n 'competitor_difference'].astype(str)\n ev = ev[['trial_type', 'onset', 'duration']]\n trial_types += ev['trial_type'].unique().tolist()\n ev.columns = ['Stim', 'Onset', 'Duration']\n ev[['Onset', 'Duration']] /= 1000\n ev['id'] = range(len(ev))\n \n # CORRECT TRIAL NUMBER DRIFT\n ev['trial_number'] = 0\n \n for i in ev[ev['Stim'] == 'decision_end'].index:\n if not i == len(ev) - 1:\n if 'antic' in ev.loc[i+1]['Stim']:\n ev['trial_number'][i+2:] += 1\n else:\n ev['trial_number'][i+1:] += 1\n \n # CORRECT DRIFT CAUSED BY TASK CODE DROPPING SAMPLES\n # Task code occasionally dropped samples which means the behavioural timings and the \n # imaging go out of sync over the course of the task. Thankfully the amount of drift\n # is consistent on every trial so we can just use this to correct the onsets.\n ev['Onset'] += ev['trial_number'] * .26\n ev['Onset'] -= .13\n \n ev = ev.iloc[:, :4]\n events = ev\n \n # Assign unique IDs to each condition label to line up with behavioural data\n unique_conditions = [i for i in list(set(trial_types)) if 'blocked' in i and 'decision' in i]\n\n for cond in unique_conditions:\n events.loc[events['Stim'] == cond, 'Stim'] = \\\n events.loc[events['Stim'] == cond, 'Stim'] + \\\n '_Ses-{0}_Run-{1}_id-'.format(this_session, this_run) + events.loc[events['Stim'] == cond, 'id'].astype(str)\n \n # Get behavioural modelling data\n decision_data = pd.read_csv('../data/decision_data_REVISED.csv')\n decision_data = decision_data[decision_data['subject'] == subject]\n decision_data['decision_current'] = decision_data['left_or_right'].shift(1) # Shift decision to next trial so we know which patch they're currently \"in\"\n decision_data.loc[decision_data['trial_index'] == 0, 'decision_current'] = np.nan # No current patch for first trial\n\n # GET SESSION INFO\n # This is compiled to a format nipype can use, although we end up not using nipype\n trialinfo = events\n confoundinfo = confounds\n \n # Get decision variables\n run_decision_data = decision_data[(decision_data['day'] == int(this_session[1:])) & (decision_data['block'] == this_run + 1)]\n \n # Scale confounds\n confoundinfo[confoundinfo.columns] = scale(confoundinfo[confoundinfo.columns])\n\n # For some reason the final decision_end period is NaN\n if np.any(trialinfo.isnull()):\n nan_idx = np.where(trialinfo.isnull())[0][0]\n if nan_idx == len(trialinfo) - 1: # Final event\n trialinfo.loc[nan_idx, 'Duration'] = 7 # Ends after 7 seconds\n else:\n trialinfo.loc[nan_idx, 'Duration'] = trialinfo.loc[nan_idx:nan_idx + 1, 'Onset'].diff().values[1]\n \n # Check data\n assert np.any(~trialinfo.isnull()), 'NaNs present in trial info'\n assert np.all(trialinfo[['Onset', 'Duration']] >= 0), 'Something is wrong - onsets or durations below zero'\n \n conditions = []\n onsets = []\n durations = []\n\n for group in trialinfo.groupby('Stim'):\n conditions.append(group[0])\n onsets.append(list(group[1].Onset))\n durations.append(group[1].Duration.tolist())\n \n # Collapse conditions and onsets for univariate analysis\n decision_ids = [int(re.search('(?<=id-)\\d+', i).group()) for i in conditions if 'blocked_with' in i]\n\n new_conditions = list(set([re.sub('_(safe)?(threat)?_-?\\d\\.0_Ses-[A-Za-z0-9-_]+', '', i) for i in conditions]))\n\n new_conditions.append('Competitors_diff_pmod')\n new_conditions.append('Competitors_alternative_pmod')\n new_conditions.append('Competitors_current_pmod')\n\n new_conditions.append('SV_diff_pmod')\n new_conditions.append('SV_alternative_pmod')\n new_conditions.append('SV_current_pmod')\n \n new_conditions.append('threat')\n\n new_onsets = dict(zip(new_conditions, [[] for i in range(len(new_conditions))]))\n new_durations = dict(zip(new_conditions, [[] for i in range(len(new_conditions))]))\n amplitudes = dict(zip(new_conditions, [[] for i in range(len(new_conditions))]))\n\n\n for n, cond in enumerate(conditions):\n new_cond = re.sub('_(safe)?(threat)?_-?\\d\\.0_Ses-[A-Za-z0-9-_]+', '', cond)\n new_onsets[new_cond] += onsets[n]\n new_durations[new_cond] += durations[n]\n amplitudes[new_cond] += [1 for i in onsets[n]]\n\n if 'blocked_with_decision' in new_cond:\n\n # Get decision variables\n decision_id = int(re.search('(?<=id-)\\d+', cond).group())\n trial_decision_data = run_decision_data[run_decision_data['id'] == decision_id]\n\n if not trial_decision_data['decision_current'].isnull().any():\n current_decision = int(trial_decision_data['decision_current'].values[0])\n\n current_comp = trial_decision_data[['left_conspecifics_number', 'right_conspecifics_number']].values[0][current_decision]\n alternative_comp = trial_decision_data[['left_conspecifics_number', 'right_conspecifics_number']].values[0][1-current_decision]\n comp_diff = current_comp - alternative_comp\n\n current_sv = trial_decision_data[['survival_value_left_Z', 'survival_value_right_Z']].values[0][current_decision]\n alternative_sv = trial_decision_data[['survival_value_left_Z', 'survival_value_right_Z']].values[0][1-current_decision]\n sv_diff = current_sv - alternative_sv\n\n amplitudes['Competitors_diff_pmod'].append(comp_diff)\n amplitudes['Competitors_alternative_pmod'].append(alternative_comp)\n amplitudes['Competitors_current_pmod'].append(current_comp)\n\n amplitudes['SV_diff_pmod'].append(sv_diff)\n amplitudes['SV_alternative_pmod'].append(alternative_sv)\n amplitudes['SV_current_pmod'].append(current_sv)\n\n amplitudes['threat'].append(int('threat' in cond))\n \n amplitudes[new_cond].append(1)\n\n # Add onsets\n for c in ['Competitors_diff_pmod', 'Competitors_alternative_pmod', 'Competitors_current_pmod', \n 'SV_diff_pmod', 'SV_alternative_pmod', 'SV_current_pmod', 'threat']:\n new_onsets[c] += onsets[n]\n new_durations[c] += durations[n]\n \n # Make sure conditions are in the same order to facilitate lining up across runs\n new_conditions = sorted(new_conditions)\n\n session_info = Bunch(conditions=new_conditions,\n onsets=[new_onsets[k] for k in new_conditions],\n durations=[new_durations[k] for k in new_conditions],\n amplitudes=[list(scale(amplitudes[k]) + 1) for k in new_conditions], # Mean center, mean of 1 (Mumford et al., 2015)\n regressors=[list(confoundinfo.framewise_displacement.fillna(0)),\n list(confoundinfo.trans_x),\n list(confoundinfo.trans_y),\n list(confoundinfo.trans_z),\n list(confoundinfo.rot_x),\n list(confoundinfo.rot_y),\n list(confoundinfo.rot_z),\n list(confoundinfo.csf),\n list(confoundinfo.white_matter),\n list(np.ones_like(confoundinfo.white_matter)) # INTERCEPT\n ])\n\n # print(session_info.conditions) \n\n # Load fMRI data\n fMRI_data = os.path.join(base_dir, \n 'fmriprep/sub-{0}/ses-{1}/func/sub-{0}_ses-{1}_task-mos_run-0{2}_'\n 'space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz'.format(subject, this_session, this_run+1))\n\n # Useful function to convert nipype-style session info to a datafrae\n def session_info_to_df(session_info):\n df_info = {'condition': [], 'onset': [], 'duration': [], 'value': []}\n for n, condition_onsets in enumerate(session_info.onsets):\n cond_name = session_info.conditions[n]\n for trial, onset in enumerate(condition_onsets):\n df_info['condition'].append(cond_name)\n df_info['onset'].append(onset)\n df_info['duration'].append(session_info.durations[n][trial])\n df_info['value'].append(session_info.amplitudes[n][trial])\n \n return pd.DataFrame(df_info)\n \n # Load the data\n print(\"LOADING DATA\")\n ts_img = nb.load(fMRI_data)\n mask_img = nb.load(os.path.join(base_dir, \n 'fmriprep/sub-{0}/ses-{1}/func/sub-{0}_ses-{1}_'\n 'task-mos_run-0{2}_space-MNI152NLin2009cAsym_'\n 'desc-brain_mask.nii.gz'.format(subject, this_session, this_run+1)))\n\n #### !!!!TESTING!!! #####\n if testing:\n ts_img_data = ts_img.get_fdata()\n ts_img_short = nb.Nifti1Image(ts_img_data[..., :n_test], ts_img.affine, ts_img.header)\n ts_img = ts_img_short\n print(ts_img_short.shape)\n # raise TypeError()\n ##########################\n \n \"\"\"\n *First-level modelling*\n \n This part uses functions from Lyman (http://www.cns.nyu.edu/~mwaskom/software/lyman/index.html), which\n basically implements FSL's GLM fitting methods in Python and makes them much faster. We have a lot of\n data here so this speedup helps.\n\n This uses a fork of Lyman that implements parallelisation and optimisation using Numba to make it even faster. \n The end result is that a model that takes ~10 hours to fit in FSL takes about 45 minutes.\n\n A lot of this code is modified from this script: https://github.com/mwaskom/lyman/blob/master/lyman/workflows/model.py \n\n \"\"\"\n\n # Smooth the data\n print(\"SMOOTHING\")\n ts_img_affine = ts_img.affine\n ts_img_header = ts_img.header\n ts_img_dtype = ts_img.get_data_dtype()\n n_tp = ts_img.shape[-1]\n\n ts_img = signals.smooth_volume(ts_img, 8, mask_img=mask_img, inplace=False)\n\n data = ts_img.get_fdata()\n mean = data.mean(axis=-1)\n mean_img = nb.Nifti1Image(mean, ts_img_affine, ts_img_header)\n\n del ts_img\n\n # Calculate mask\n mask = mask_img.get_fdata()\n mask = (mask > 0)\n mask_img = nb.Nifti1Image(mask.astype(np.uint8), mask_img.affine, mask_img.header)\n n_vox = mask.sum()\n\n # Set up GLM\n print(\"SETTING UP GLM\")\n \n # Temporally filter the data\n hpf_matrix = glm.highpass_filter_matrix(n_tp, 128, 1)\n data[mask] = np.dot(hpf_matrix, data[mask].T).T\n data[mask] -= data[mask].mean(axis=-1, keepdims=True)\n \n # Temporally filter the nuisance regressors\n for n, i in enumerate(session_info.regressors):\n ### !!!TESTING!! ###########\n if testing:\n session_info.regressors[n] = hpf_matrix.dot(i[:n_test]) \n ############################\n else:\n session_info.regressors[n] = hpf_matrix.dot(i) \n \n # --- Design matrix construction\n\n # Build the regressor sub-matrix\n tps = np.arange(0, n_tp * 1, 1)\n confound_cols = [f\"confound_{i+1}\" for i in range(len(session_info.regressors))]\n \n regressors = pd.DataFrame(np.array(session_info.regressors).T, tps, confound_cols)\n\n # Build the full design matrix\n design = session_info_to_df(session_info)\n \n # #### !!!!TESTING!!! #####\n # if testing:\n # design = design[design['onset'] < n_test - 5]\n # ##########################\n\n hrf_model = glm.GammaBasis(time_derivative=False,\n disp_derivative=False) \n X = glm.build_design_matrix(design, hrf_model,\n regressors=regressors,\n n_tp=n_tp, tr=1,\n hpf_matrix=hpf_matrix)\n \n # Save the design matrix\n model_file = os.path.join(output_dir, 'sub-{0}_sess-{1}_run-{2}_design_matrix.csv'.format(subject, this_session, this_run))\n X.to_csv(model_file, index=False)\n\n # --- Model estimation\n data[~mask] = 0 \n \n # Prewhiten the data\n print(\"PREWHITENING\")\n ts_img = nb.Nifti1Image(data, ts_img_affine)\n del data\n WY, WX = glm.prewhiten_image_data(ts_img, mask_img, X.values)\n\n # np.save('WX', WX)\n # np.save('WY', WY)\n\n # WX = np.load('WX.npy')\n # WY = np.load('WY.npy')\n\n # Reshape - seems faster with voxels first\n WX = WX.transpose((2, 0, 1))\n WY = WY.T\n # UID for temp storage\n uid = uuid.uuid4().hex\n folder = '/central/scratchio/tobywise/temp_' + str(uid)\n try:\n os.makedirs(folder)\n except FileExistsError:\n pass\n\n # Memmap the data so it's not held in memory\n print('Temp directory = {0}'.format(folder))\n WX_filename_memmap = os.path.join(folder, 'X_memmap')\n WY_filename_memmap = os.path.join(folder, 'Y_memmap')\n dump(WX, WX_filename_memmap)\n dump(WY, WY_filename_memmap)\n WX_memmap = load(WX_filename_memmap, mmap_mode='r')\n WY_memmap = load(WY_filename_memmap, mmap_mode='r')\n\n # Clean things up\n del ts_img\n del WX\n del WY\n \n # FIT THE GLM\n # This uses modified fitting code from Lyman to enable parallel processing\n # Parallel processing is not straightforward here because there is so much data\n # Joblib's Loky backend (which is the most straightforward to use) forks processes by default\n # meaning memory usage is basically copied for every process. The data for each run takes\n # up around 40GB of memory (in addition to the fMRI data, the design matrix has a separate)\n # set of regressors for each voxel, making it n_tp x n_vox x n_regressors. This means that \n # each process seems to use over 40GB of memory, making things difficult.\n\n # The solution to this is to memmap the arrays (as done above), so that they are not held in memory,\n # and each process just reads in the bit it needs. However, if we literally do this on each iteration\n # of the fitting procedure (i.e. for each voxel), we end up being limited by I/O speed. Therefore,\n # the way this works is to memmap the data, then within each process read in all the data necessary\n # for the chunk being processed, then write that back to the memmapped array.\n print(h.heap())\n start = time.time()\n B, SS, XtXinv, E = glm.iterative_ols_fit(WY_memmap, WX_memmap, n_jobs=len(os.sched_getaffinity(0)))\n end = time.time()\n print('GLM fitting took {0} seconds'.format(end - start))\n \n try:\n shutil.rmtree(folder)\n except: # noqa\n print('Could not clean-up automatically.')\n\n # # Convert outputs to image format\n beta_img = matrix_to_image(B.T, mask_img)\n error_img = matrix_to_image(SS, mask_img)\n XtXinv_flat = XtXinv.reshape(n_vox, -1)\n ols_img = matrix_to_image(XtXinv_flat.T, mask_img)\n resid_img = matrix_to_image(E, mask_img)\n\n # Save everything\n print(\"SAVING\")\n nb.save(beta_img, os.path.join(output_dir, 'beta.nii.gz'))\n nb.save(error_img, os.path.join(output_dir, 'error.nii.gz'))\n nb.save(ols_img, os.path.join(output_dir, 'ols.nii.gz'))\n nb.save(mask_img, os.path.join(output_dir, 'mask.nii.gz'))\n nb.save(resid_img, os.path.join(output_dir, 'resid.nii.gz'))\n\n np.save(os.path.join(output_dir, 'B'), B)\n np.save(os.path.join(output_dir, 'SS'), SS)\n np.save(os.path.join(output_dir, 'XtXinv'), XtXinv)\n np.save(os.path.join(output_dir, 'E'), E)\n\n print(\"ESTIMATING CONTRASTS\")\n # Contrast estimates\n param_names = X.columns\n non_confound_names = [i for i in param_names if not 'confound' in i]\n\n # Reshape the matrix form data to what the glm functions expect\n # B = B.T\n n_vox, n_ev = B.shape\n # XtXinv = XtXinv.reshape(n_ev, n_ev, n_vox).T\n\n # Define contrasts\n contrasts = []\n\n for cond in non_confound_names:\n contrasts.append([cond, [cond], [1]])\n \n contrasts.append(['Competitors_current-alternative', ['Competitors_current_pmod', 'Competitors_alternative_pmod'], [1, -1]])\n contrasts.append(['SV_current-alternative', ['SV_current_pmod', 'SV_alternative_pmod'], [1, -1]])\n\n for con in contrasts:\n if len(con[-1]) > 1:\n assert np.sum(con[-1]) == 0, 'Contrasts {0} do not sum to zero'.format(con[-1])\n\n # Save contrast specification to json\n with open(os.path.join(output_dir, 'contrasts.json'), 'w') as f:\n json.dump(contrasts, f)\n\n # Obtain list of contrast matrices\n C = []\n names = []\n for contrast_spec in contrasts:\n name, params, _ = contrast_spec\n if set(params) <= set(param_names):\n C.append(glm.contrast_matrix(contrast_spec, X))\n names.append(name)\n\n # Estimate the contrasts, variances, and statistics in each voxel\n G, V, T = glm.iterative_contrast_estimation(B, SS, XtXinv, C)\n contrast_img = matrix_to_image(G.T, mask_img)\n variance_img = matrix_to_image(V.T, mask_img)\n tstat_img = matrix_to_image(T.T, mask_img)\n\n print(\"SAVING CONTRAST ESTIMATES\")\n # Write out the output files\n nb.save(contrast_img, os.path.join(output_dir, 'contrast.nii.gz'))\n nb.save(variance_img, os.path.join(output_dir, 'variance.nii.gz'))\n nb.save(tstat_img, os.path.join(output_dir, 'tstat.nii.gz'))\n\n name_file = os.path.join(output_dir, 'sub-{0}_sess-{1}_run-{2}_contrast.txt'.format(subject, this_session, this_run))\n np.savetxt(name_file, names, \"%s\")\n\n print(\"DONE\")\n\n"
] |
[
[
"numpy.dot",
"pandas.read_csv",
"numpy.ones_like",
"numpy.arange",
"pandas.DataFrame",
"numpy.all",
"numpy.savetxt",
"numpy.array",
"sklearn.preprocessing.scale",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
bicycle315/qiskit-experiments
|
[
"894dcf41ac69ace9e6a0a3c4800d4b6994ac3b5a",
"7c2b83beb1566a6b9985e0c7adf38cd8b8f30953"
] |
[
"qiskit_experiments/library/tomography/fitters/lininv.py",
"test/calibration/experiments/test_fine_drag.py"
] |
[
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\"\"\"\nLinear inversion MLEtomography fitter.\n\"\"\"\n\nfrom typing import Dict, Tuple, Optional, Sequence\nfrom functools import lru_cache\nimport numpy as np\nfrom qiskit_experiments.library.tomography.basis.fitter_basis import (\n FitterMeasurementBasis,\n FitterPreparationBasis,\n)\n\n\ndef linear_inversion(\n outcome_data: np.ndarray,\n shot_data: np.ndarray,\n measurement_data: np.ndarray,\n preparation_data: np.ndarray,\n measurement_basis: Optional[FitterMeasurementBasis] = None,\n preparation_basis: Optional[FitterPreparationBasis] = None,\n) -> Tuple[np.ndarray, Dict]:\n r\"\"\"Linear inversion tomography fitter.\n\n Overview\n This fitter uses linear inversion to reconstructs the maximum-likelihood\n estimate of the least-squares log-likelihood function\n\n .. math::\n \\hat{\\rho}\n &= -\\mbox{argmin }\\log\\mathcal{L}{\\rho} \\\\\n &= \\mbox{argmin }\\sum_i (\\mbox{Tr}[E_j\\rho] - \\hat{p}_i)^2 \\\\\n &= \\mbox{argmin }\\|Ax - y \\|_2^2\n\n where\n\n * :math:`A = \\sum_j |j \\rangle\\!\\langle\\!\\langle E_j|` is the matrix of measured\n basis elements.\n * :math:`y = \\sum_j \\hat{p}_j |j\\rangle` is the vector of estimated measurement\n outcome probabilites for each basis element.\n * :math:`x = |\\rho\\rangle\\!\\rangle` is the vectorized density matrix.\n\n Additional Details\n The linear inversion solution is given by\n\n .. math::\n \\hat{\\rho} = \\sum_i \\hat{p}_i D_i\n\n where measurement probabilities :math:`\\hat{p}_i = f_i / n_i` are estimated\n from the observed count frequencies :math:`f_i` in :math:`n_i` shots for each\n basis element :math:`i`, and :math:`D_i` is the *dual basis* element constructed\n from basis :math:`\\{E_i\\}` via:\n\n .. math:\n\n |D_i\\rangle\\!\\rangle = M^{-1}|E_i \\rangle\\!\\rangle \\\\\n M = \\sum_j |E_j\\rangle\\!\\rangle\\!\\langle\\!\\langle E_j|\n\n .. note::\n\n Linear inversion is only possible if the input bases are a spanning set\n for the vector space of the reconstructed matrix\n (*tomographically complete*). If the basis is not tomographically complete\n the :func:`~qiskit_experiments.library.tomography.fitters.scipy_linear_lstsq`\n function can be used to solve the same objective function via\n least-squares optimization.\n\n Args:\n outcome_data: measurement outcome frequency data.\n shot_data: basis measurement total shot data.\n measurement_data: measurement basis indice data.\n preparation_data: preparation basis indice data.\n measurement_basis: Optional, measurement matrix basis.\n preparation_basis: Optional, preparation matrix basis.\n\n Raises:\n AnalysisError: If the fitted vector is not a square matrix\n\n Returns:\n The fitted matrix rho.\n \"\"\"\n # Construct dual bases\n if measurement_basis:\n meas_dual_basis = dual_measurement_basis(measurement_basis)\n else:\n meas_dual_basis = None\n if preparation_basis:\n prep_dual_basis = dual_preparation_basis(preparation_basis)\n else:\n prep_dual_basis = None\n\n if shot_data is None:\n shot_data = np.ones(len(outcome_data))\n\n # Construct linear inversion matrix\n rho_fit = 0.0\n for i, outcomes in enumerate(outcome_data):\n shots = shot_data[i]\n midx = measurement_data[i]\n pidx = preparation_data[i]\n\n # Get prep basis component\n if prep_dual_basis:\n p_mat = np.transpose(prep_dual_basis.matrix(pidx))\n else:\n p_mat = None\n\n # Get probabilities and optional measurement basis component\n for outcome, freq in enumerate(outcomes):\n if freq == 0:\n # Skip component with zero probability\n continue\n\n if meas_dual_basis:\n dual_op = meas_dual_basis.matrix(midx, outcome)\n if prep_dual_basis:\n dual_op = np.kron(p_mat, dual_op)\n else:\n dual_op = p_mat\n\n # Add component to linear inversion reconstruction\n prob = freq / shots\n rho_fit = rho_fit + prob * dual_op\n\n return rho_fit, {}\n\n\n@lru_cache(2)\ndef dual_preparation_basis(basis: FitterPreparationBasis):\n \"\"\"Construct a dual preparation basis for linear inversion\"\"\"\n return FitterPreparationBasis(_dual_states(basis._mats), name=f\"Dual_{basis.name}\")\n\n\n@lru_cache(2)\ndef dual_measurement_basis(basis: FitterMeasurementBasis):\n \"\"\"Construct a dual preparation basis for linear inversion\"\"\"\n # Vectorize basis and basis matrix of outcome projectors\n states = []\n extra = []\n num_basis = len(basis._basis)\n for i in range(num_basis):\n for outcome, povm in basis._basis[i].items():\n states.append(povm)\n extra.append([i, outcome])\n dpovm = basis._outcome_default[i]\n if dpovm is not None:\n states.append(dpovm)\n extra.append([i, None])\n\n # Compute dual states and convert back to dicts\n dbasis = _dual_states(states)\n dual_basis = [{} for i in range(num_basis)]\n for povm, (idx, outcome) in zip(dbasis, extra):\n dual_basis[idx][outcome] = povm\n\n return FitterMeasurementBasis(dual_basis, name=f\"Dual_{basis.name}\")\n\n\ndef _dual_states(states: Sequence[np.ndarray]):\n \"\"\"Construct a dual preparation basis for linear inversion\"\"\"\n mats = np.asarray(states)\n size, dim1, dim2 = np.shape(mats)\n vec_basis = np.reshape(mats, (size, dim1 * dim2))\n basis_mat = np.sum([np.outer(i, np.conj(i)) for i in vec_basis], axis=0)\n\n try:\n inv_mat = np.linalg.inv(basis_mat)\n except np.linalg.LinAlgError as ex:\n raise ValueError(\n \"Cannot construct dual basis states. Input states\" \" are not tomographically complete\"\n ) from ex\n\n vec_dual = np.tensordot(inv_mat, vec_basis, axes=([1], [1])).T\n dual_mats = np.reshape(vec_dual, (size, dim1, dim2))\n return dual_mats\n",
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Test fine drag calibration experiment.\"\"\"\n\nfrom test.base import QiskitExperimentsTestCase\nimport copy\nimport numpy as np\n\nfrom qiskit import transpile\nfrom qiskit.circuit import QuantumCircuit, Gate\nfrom qiskit.test.mock import FakeArmonk\nimport qiskit.pulse as pulse\n\nfrom qiskit_experiments.library import FineDrag, FineXDrag, FineDragCal\nfrom qiskit_experiments.test.mock_iq_backend import DragBackend\nfrom qiskit_experiments.calibration_management import Calibrations\nfrom qiskit_experiments.calibration_management.basis_gate_library import FixedFrequencyTransmon\n\n\nclass FineDragTestBackend(DragBackend):\n \"\"\"A simple and primitive backend, to be run by the rough drag tests.\"\"\"\n\n def _compute_probability(self, circuit: QuantumCircuit) -> float:\n \"\"\"Returns the probability based on the beta, number of gates, and leakage.\"\"\"\n n_gates = circuit.count_ops().get(\"rz\", 0) // 2\n\n return 0.5 * np.sin(n_gates * self._freq) + 0.5\n\n\nclass TestFineDrag(QiskitExperimentsTestCase):\n \"\"\"Tests of the fine DRAG experiment.\"\"\"\n\n def setUp(self):\n \"\"\"Setup test variables.\"\"\"\n super().setUp()\n\n with pulse.build(name=\"Drag\") as schedule:\n pulse.play(pulse.Drag(160, 0.5, 40, 0.3), pulse.DriveChannel(0))\n\n self.schedule = schedule\n\n def test_circuits(self):\n \"\"\"Test the circuits of the experiment.\"\"\"\n\n drag = FineDrag(0, Gate(\"Drag\", num_qubits=1, params=[]))\n drag.set_experiment_options(schedule=self.schedule)\n drag.backend = FakeArmonk()\n for circuit in drag.circuits()[1:]:\n for idx, name in enumerate([\"Drag\", \"rz\", \"Drag\", \"rz\"]):\n self.assertEqual(circuit.data[idx][0].name, name)\n\n def test_end_to_end(self):\n \"\"\"A simple test to check if the experiment will run and fit data.\"\"\"\n\n drag = FineDrag(0, Gate(\"Drag\", num_qubits=1, params=[]))\n drag.set_experiment_options(schedule=self.schedule)\n drag.set_transpile_options(basis_gates=[\"rz\", \"Drag\", \"sx\"])\n exp_data = drag.run(FineDragTestBackend())\n self.assertExperimentDone(exp_data)\n\n self.assertEqual(exp_data.analysis_results(0).quality, \"good\")\n\n def test_end_to_end_no_schedule(self):\n \"\"\"Test that we can run without a schedule.\"\"\"\n\n exp_data = FineXDrag(0).run(FineDragTestBackend())\n self.assertExperimentDone(exp_data)\n\n self.assertEqual(exp_data.analysis_results(0).quality, \"good\")\n\n def test_experiment_config(self):\n \"\"\"Test converting to and from config works\"\"\"\n exp = FineDrag(0, Gate(\"Drag\", num_qubits=1, params=[]))\n config = exp.config()\n loaded_exp = FineDrag.from_config(config)\n self.assertNotEqual(exp, loaded_exp)\n self.assertEqual(config, loaded_exp.config())\n\n\nclass TestFineDragCal(QiskitExperimentsTestCase):\n \"\"\"Test the calibration version of the fine drag experiment.\"\"\"\n\n def setUp(self):\n \"\"\"Setup the test.\"\"\"\n super().setUp()\n\n library = FixedFrequencyTransmon()\n\n self.backend = FineDragTestBackend()\n self.cals = Calibrations.from_backend(self.backend, library)\n\n def test_experiment_config(self):\n \"\"\"Test converting to and from config works\"\"\"\n exp = FineDragCal(0, self.cals, schedule_name=\"x\")\n config = exp.config()\n loaded_exp = FineDragCal.from_config(config)\n self.assertNotEqual(exp, loaded_exp)\n self.assertEqual(config, loaded_exp.config())\n\n def test_update_cals(self):\n \"\"\"Test that the calibrations are updated.\"\"\"\n\n init_beta = 0.0\n\n drag_cal = FineDragCal(0, self.cals, \"x\", self.backend)\n\n transpile_opts = copy.copy(drag_cal.transpile_options.__dict__)\n transpile_opts[\"initial_layout\"] = list(drag_cal.physical_qubits)\n circs = transpile(\n drag_cal.circuits(), inst_map=self.cals.default_inst_map, **transpile_opts\n )\n\n with pulse.build(name=\"x\") as expected_x:\n pulse.play(pulse.Drag(160, 0.5, 40, 0), pulse.DriveChannel(0))\n\n with pulse.build(name=\"sx\") as expected_sx:\n pulse.play(pulse.Drag(160, 0.25, 40, 0), pulse.DriveChannel(0))\n\n self.assertEqual(circs[5].calibrations[\"x\"][((0,), ())], expected_x)\n self.assertEqual(circs[5].calibrations[\"sx\"][((0,), ())], expected_sx)\n\n # run the calibration experiment. This should update the beta parameter of x which we test.\n exp_data = drag_cal.run(self.backend)\n self.assertExperimentDone(exp_data)\n d_theta = exp_data.analysis_results(1).value.n\n sigma = 40\n target_angle = np.pi\n new_beta = -np.sqrt(np.pi) * d_theta * sigma / target_angle**2\n\n transpile_opts = copy.copy(drag_cal.transpile_options.__dict__)\n transpile_opts[\"initial_layout\"] = list(drag_cal.physical_qubits)\n circs = transpile(\n drag_cal.circuits(), inst_map=self.cals.default_inst_map, **transpile_opts\n )\n\n x_cal = circs[5].calibrations[\"x\"][((0,), ())]\n\n # Requires allclose due to numerical precision.\n self.assertTrue(np.allclose(x_cal.blocks[0].pulse.beta, new_beta))\n self.assertFalse(np.allclose(x_cal.blocks[0].pulse.beta, init_beta))\n self.assertEqual(circs[5].calibrations[\"sx\"][((0,), ())], expected_sx)\n"
] |
[
[
"numpy.conj",
"numpy.asarray",
"numpy.linalg.inv",
"numpy.reshape",
"numpy.kron",
"numpy.shape",
"numpy.tensordot"
],
[
"numpy.sqrt",
"numpy.allclose",
"numpy.sin"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
paulorauber/rpg
|
[
"bd668c361a2c0367c58c6d30b961eec604365c54"
] |
[
"rpg/environments/maze.py"
] |
[
"import numpy as np\n\nfrom gym import Env\nfrom gym import spaces\nfrom gym import Wrapper\n\n\nclass TimedEnvironmentWrapper(Wrapper):\n def __init__(self, env, max_steps):\n Wrapper.__init__(self, env)\n self._max_steps = max_steps\n\n def reset(self):\n self._n_steps = 0\n return self._reset()\n\n def step(self, a):\n self._n_steps += 1\n\n obs, reward, done, info = self._step(a)\n if self._max_steps <= self._n_steps:\n done = True\n\n return obs, reward, done, info\n\n\nclass Maze(Env):\n def __init__(self, layout, entries, exits, traps=None, can_stay=False,\n step_reward=-1, stay_reward=-1, exit_reward=10,\n trap_reward=-100):\n self.metadata = {'render.modes': ['human']}\n\n self.layout = np.array(layout, dtype=np.int)\n validx, validy = np.nonzero(self.layout)\n self.valid_positions = set(zip(validx, validy))\n\n self.entries = set(entries)\n self.exits = set(exits)\n\n self.traps = set()\n if traps is not None:\n self.traps = self.traps.union(traps)\n\n self.check_consistency()\n\n self.step_reward = step_reward\n self.stay_reward = stay_reward\n self.exit_reward = exit_reward\n self.trap_reward = trap_reward\n\n self.action_space = spaces.Discrete(4 + can_stay)\n self.observation_space = None\n\n def check_consistency(self):\n given_positions = self.entries.union(self.exits, self.traps)\n\n if not given_positions.issubset(self.valid_positions):\n raise Exception('Invalid entry, exit, or trap.')\n\n c = len(self.entries) + len(self.exits) + len(self.traps)\n if len(given_positions) < c:\n raise Exception('Two artifacts on same location.')\n\n def observation(self):\n raise NotImplementedError()\n\n def _reset(self):\n i = np.random.choice(len(self.entries))\n self.position = sorted(self.entries)[i]\n\n return self.observation()\n\n def _step(self, a):\n \"\"\"a: up, down, left, right, stay\"\"\"\n if a >= self.action_space.n:\n raise Exception('Invalid action')\n\n moves = [(-1, 0), (1, 0), (0, -1), (0, 1), (0, 0)]\n\n newx = self.position[0] + moves[a][0]\n newy = self.position[1] + moves[a][1]\n\n if (newx, newy) in self.valid_positions:\n self.position = (newx, newy)\n\n done = False\n\n if self.position in self.exits:\n done = True\n reward = self.exit_reward\n\n if self.position in self.traps:\n done = True\n reward = self.trap_reward\n\n if not done:\n reward = self.step_reward if a != 4 else self.stay_reward\n\n return self.observation(), reward, done, {}\n\n def _render(self, mode='human', close=False):\n if not close:\n print(self.__repr__())\n\n def __repr__(self):\n s = []\n\n for i in range(len(self.layout)):\n for j in range(len(self.layout[0])):\n if (i, j) == self.position:\n s.append('@')\n elif (i, j) in self.exits:\n s.append('$')\n elif (i, j) in self.traps:\n s.append('X')\n else:\n s.append('.' if self.layout[i, j] else '#')\n s.append('\\n')\n\n return ''.join(s)\n\n\nclass MarkovianMaze(Maze):\n def __init__(self, layout, entries, exits, traps=None, can_stay=False,\n step_reward=-1, stay_reward=-1, exit_reward=10,\n trap_reward=-100):\n Maze.__init__(self, layout, entries, exits, traps, can_stay,\n step_reward, stay_reward, exit_reward, trap_reward)\n\n self.observation_space = spaces.Box(-1, 1, shape=self.layout.size)\n\n def observation(self):\n obs = np.array(self.layout, dtype=np.float)\n obs[self.position] = -1\n\n return obs.reshape(-1)\n\n\nclass NonMarkovianMaze(Maze):\n def __init__(self, layout, entries, exits, traps=None, can_stay=False,\n step_reward=-1, stay_reward=-1, exit_reward=10,\n trap_reward=-100, color_walls=False):\n Maze.__init__(self, layout, entries, exits, traps, can_stay,\n step_reward, stay_reward, exit_reward, trap_reward)\n\n self.observation_space = spaces.Box(0, 1, shape=4)\n\n if color_walls:\n self.colors = (1 - self.layout)*np.random.random(self.layout.shape)\n self.colors = self.colors*0.5 + self.layout\n else:\n self.colors = np.array(self.layout)\n\n def observation(self):\n moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n obs = np.zeros(4, dtype=np.float)\n\n xmax, ymax = self.layout.shape\n for i, move in enumerate(moves):\n newx, newy = self.position[0] + move[0], self.position[1] + move[1]\n\n if 0 <= newx < xmax and 0 <= newy < ymax:\n obs[i] = self.colors[newx, newy]\n else:\n obs[i] = 0.0\n\n return obs\n\n\ndef make_random_layout(h, w):\n \"\"\"Adapted from https://rosettacode.org/wiki/Maze_generation.\"\"\"\n maze_string = ''\n\n vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]\n ver = [[\"| \"] * w + ['|'] for _ in range(h)] + [[]]\n hor = [[\"+-\"] * w + ['+'] for _ in range(h + 1)]\n\n def walk(x, y):\n vis[y][x] = 1\n\n d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]\n np.random.shuffle(d)\n for (xx, yy) in d:\n if vis[yy][xx]:\n continue\n if xx == x:\n hor[max(y, yy)][x] = \"+ \"\n if yy == y:\n ver[y][max(x, xx)] = \" \"\n walk(xx, yy)\n\n walk(np.random.randint(w), np.random.randint(h))\n for (a, b) in zip(hor, ver):\n maze_string += ''.join(a + ['\\n'] + b) + '\\n'\n\n A = [[]]\n for c in maze_string[: -2]:\n if c == '\\n':\n A.append([])\n elif c == ' ':\n A[-1].append(1)\n else:\n A[-1].append(0)\n\n return np.array(A, dtype=np.int)\n\n\ndef make_random_maze(h, w, markovian=True, can_stay=False, step_reward=-1.0,\n stay_reward=-1.0, exit_reward=None, trap_reward=-10):\n layout = make_random_layout(h, w)\n shape = layout.shape\n\n MazeClass = MarkovianMaze if markovian else NonMarkovianMaze\n\n entries = [(1, 1)]\n exits = [(shape[0] - 2, shape[1] - 2)]\n\n if exit_reward is None:\n exit_reward = 2*(h + w)\n\n maze = MazeClass(layout, entries, exits, None, can_stay, step_reward,\n stay_reward, exit_reward, trap_reward)\n\n return maze\n\n\ndef make_cheese_maze(markovian=True, can_stay=False, step_reward=-1.0,\n stay_reward=-1.0, exit_reward=5, trap_reward=-10):\n \"\"\"Adapted from Bakker, Pieter Bram. The state of mind. 2004, pg. 155\"\"\"\n layout = np.ones(shape=(3, 5), dtype=np.int)\n\n layout[1:, 1] = 0\n layout[1:, 3] = 0\n\n exits = set([(2, 2)])\n\n entries = set([(2, 0), (2, 4)])\n\n MazeClass = MarkovianMaze if markovian else NonMarkovianMaze\n\n maze = MazeClass(layout, entries, exits, None, can_stay, step_reward,\n stay_reward, exit_reward, trap_reward)\n\n return maze\n\n\ndef make_wine_maze(markovian=True, can_stay=False, step_reward=-1,\n stay_reward=-1, exit_reward=8, trap_reward=-10):\n \"\"\"Adapted from Bakker, Pieter Bram. The state of mind. 2004, pg. 155\"\"\"\n layout = np.array([[0, 1, 1, 1, 1, 1, 0],\n [1, 1, 0, 1, 0, 1, 1],\n [0, 1, 0, 1, 0, 1, 0],\n [1, 1, 0, 1, 0, 1, 1],\n [0, 1, 1, 1, 1, 1, 0]], dtype=np.int)\n\n exits = set([(3, 6)])\n\n entries = set([(1, 0), (3, 0)])\n\n MazeClass = MarkovianMaze if markovian else NonMarkovianMaze\n\n maze = MazeClass(layout, entries, exits, None, can_stay, step_reward,\n stay_reward, exit_reward, trap_reward)\n\n return maze\n\n\nclass TMazeWrapper(Wrapper):\n def __init__(self, length, markovian=True, can_stay=False):\n layout = np.zeros(shape=(3, length+1), dtype=np.int)\n\n layout[:, 0] = 1\n layout[1, :] = 1\n layout[:, -1] = 1\n\n entries = [(0, 0), (2, 0)]\n exits = [(0, length)]\n traps = [(2, length)]\n\n MazeClass = MarkovianMaze if markovian else NonMarkovianMaze\n\n maze = MazeClass(layout, entries, exits, traps, can_stay, -1.0, -1.0,\n length + 1, -1)\n\n Wrapper.__init__(self, maze)\n\n def reset(self):\n self._reset()\n\n length = self.env.layout.shape[1] - 1\n\n self.env.exits = set([(0, length)])\n self.env.traps = set([(2, length)])\n\n if self.env.position == (2, 0):\n self.env.exits, self.env.traps = self.env.traps, self.env.exits\n\n return self.env.observation()\n\n\ndef make_tmaze(length, markovian=True, can_stay=False):\n return TMazeWrapper(length, markovian, can_stay)\n\n\ndef play(maze, show_observations=True, show_rewards=True):\n udlrx = ['w', 's', 'a', 'd', 'x']\n\n obs, r, done = maze.reset(), 0., False\n\n while not done:\n print('State:')\n maze.render()\n\n if show_observations:\n print('Observation:\\n{0}.'.format(obs))\n if show_rewards:\n print('Reward: {0}.'.format(r))\n\n c = input('Move:')\n if c not in udlrx:\n raise Exception('Invalid action')\n\n print('')\n\n obs, r, done, _ = maze.step(udlrx.index(c))\n\n print('State:')\n maze.render()\n if show_observations:\n print('Observation:\\n{0}.'.format(obs))\n if show_rewards:\n print('Reward: {0}.'.format(r))\n\n\ndef main():\n np.random.seed(0)\n\n maze = make_tmaze(4, markovian=False)\n maze = TimedEnvironmentWrapper(maze, max_steps=10)\n\n print('Maze:\\n')\n\n play(maze)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.random.random",
"numpy.nonzero",
"numpy.random.seed",
"numpy.random.shuffle",
"numpy.ones",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mehrdad-shokri/ludwig
|
[
"f167981683c067b50be6a3656cbf553efbf192e9",
"f167981683c067b50be6a3656cbf553efbf192e9"
] |
[
"ludwig/utils/math_utils.py",
"ludwig/data/dataset_synthesizer.py"
] |
[
"#! /usr/bin/env python\n# coding=utf-8\n# Copyright (c) 2019 Uber Technologies, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nimport math\n\nimport numpy as np\n\n\ndef softmax(x, temperature=1.0):\n e_x = np.exp((x - np.max(x)) / temperature)\n return e_x / e_x.sum()\n\n\ndef int_type(number):\n if number <= np.iinfo(np.int8).max:\n return np.int8\n elif number <= np.iinfo(np.int16).max:\n return np.int16\n elif number <= np.iinfo(np.int32).max:\n return np.int32\n else: # if number <= np.iinfo(np.int64).max:\n return np.int64\n\n\ndef convert_size(size_bytes):\n if size_bytes == 0:\n return '0B'\n size_name = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')\n i = int(math.floor(math.log(size_bytes, 1024)))\n p = math.pow(1024, i)\n s = round(size_bytes / p, 2)\n return '{} {}'.format(s, size_name[i])\n\n\ndef learning_rate_warmup_distributed(\n learning_rate,\n epoch,\n warmup_epochs,\n num_workers,\n curr_step,\n steps_per_epoch\n):\n \"\"\"Implements gradual learning rate warmup:\n `lr = initial_lr / hvd.size()` ---> `lr = initial_lr`\n `initial_lr` is the learning rate of the model optimizer at the start\n of the training. This technique was described in the paper\n \"Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour\".\n See https://arxiv.org/pdf/1706.02677.pdf for details.\n\n Inspired by Horovod's implementation:\n https://horovod.readthedocs.io/en/stable/api.html#horovod.tensorflow.keras.callbacks.LearningRateWarmupCallback\n Math recap:\n curr_step\n epoch = full_epochs + ---------------\n steps_per_epoch\n lr size - 1\n lr'(epoch) = ---- * (-------- * epoch + 1)\n size warmup\n lr\n lr'(epoch = 0) = ----\n size\n lr'(epoch = warmup) = lr\n \"\"\"\n if epoch > warmup_epochs:\n return learning_rate\n else:\n epoch_adjusted = float(epoch) + (curr_step / steps_per_epoch)\n return learning_rate / num_workers * (\n epoch_adjusted * (num_workers - 1) / warmup_epochs + 1)\n\n\ndef learning_rate_warmup(\n learning_rate,\n epoch,\n warmup_epochs,\n curr_step,\n steps_per_epoch\n):\n global_curr_step = 1 + curr_step + epoch * steps_per_epoch\n warmup_steps = warmup_epochs * steps_per_epoch\n\n warmup_percent_done = global_curr_step / warmup_steps\n warmup_learning_rate = learning_rate * warmup_percent_done\n\n is_warmup = int(global_curr_step < warmup_steps)\n interpolated_learning_rate = (\n (1.0 - is_warmup) * learning_rate +\n is_warmup * warmup_learning_rate\n )\n\n return interpolated_learning_rate\n\n\ndef round2precision(val, precision: int = 0, which: str = ''):\n assert precision >= 0\n val *= 10 ** precision\n round_callback = round\n if which.lower() == 'up':\n round_callback = math.ceil\n if which.lower() == 'down':\n round_callback = math.floor\n return '{1:.{0}f}'.format(precision, round_callback(val) / 10 ** precision)\n",
"#! /usr/bin/env python\n# coding=utf-8\n# Copyright (c) 2019 Uber Technologies, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nimport argparse\nimport logging\nimport os\nimport random\nimport string\nimport sys\nimport uuid\n\nimport numpy as np\nimport yaml\n\nfrom ludwig.constants import VECTOR, TYPE\nfrom ludwig.utils.data_utils import save_csv\nfrom ludwig.utils.h3_util import components_to_h3\nfrom ludwig.utils.misc_utils import get_from_registry\n\nlogger = logging.getLogger(__name__)\n\nletters = string.ascii_letters\n\nDATETIME_FORMATS = {\n '%m-%d-%Y': '{m:02d}-{d:02d}-{Y:04d}',\n '%m-%d-%Y %H:%M:%S': '{m:02d}-{d:02d}-{Y:04d} {H:02d}:{M:02d}:{S:02d}',\n '%m/%d/%Y': '{m:02d}/{d:02d}/{Y:04d}',\n '%m/%d/%Y %H:%M:%S': '{m:02d}/{d:02d}/{Y:04d} {H:02d}:{M:02d}:{S:02d}',\n '%m-%d-%y': '{m:02d}-{d:02d}-{y:02d}',\n '%m-%d-%y %H:%M:%S': '{m:02d}-{d:02d}-{y:02d} {H:02d}:{M:02d}:{S:02d}',\n '%m/%d/%y': '{m:02d}/{d:02d}/{y:02d}',\n '%m/%d/%y %H:%M:%S': '{m:02d}/{d:02d}/{y:02d} {H:02d}:{M:02d}:{S:02d}',\n '%d-%m-%Y': '{d:02d}-{m:02d}-{Y:04d}',\n '%d-%m-%Y %H:%M:%S': '{d:02d}-{m:02d}-{Y:04d} {H:02d}:{M:02d}:{S:02d}',\n '%d/%m/%Y': '{d:02d}/{m:02d}/{Y:04d}',\n '%d/%m/%Y %H:%M:%S': '{d:02d}/{m:02d}/{Y:04d} {H:02d}:{M:02d}:{S:02d}',\n '%d-%m-%y': '{d:02d}-{m:02d}-{y:02d}',\n '%d-%m-%y %H:%M:%S': '{d:02d}-{m:02d}-{y:02d} {H:02d}:{M:02d}:{S:02d}',\n '%d/%m/%y': '{d:02d}/{m:02d}/{y:02d}',\n '%d/%m/%y %H:%M:%S': '{d:02d}/{m:02d}/{y:02d} {H:02d}:{M:02d}:{S:02d}',\n '%y-%m-%d': '{y:02d}-{m:02d}-{d:02d}',\n '%y-%m-%d %H:%M:%S': '{y:02d}-{m:02d}-{d:02d} {H:02d}:{M:02d}:{S:02d}',\n '%y/%m/%d': '{y:02d}/{m:02d}/{d:02d}',\n '%y/%m/%d %H:%M:%S': '{y:02d}/{m:02d}/{d:02d} {H:02d}:{M:02d}:{S:02d}',\n '%Y-%m-%d': '{Y:04d}-{m:02d}-{d:02d}',\n '%Y-%m-%d %H:%M:%S': '{Y:04d}-{m:02d}-{d:02d} {H:02d}:{M:02d}:{S:02d}',\n '%Y/%m/%d': '{Y:04d}/{m:02d}/{d:02d}',\n '%Y/%m/%d %H:%M:%S': '{Y:04d}/{m:02d}/{d:02d} {H:02d}:{M:02d}:{S:02d}',\n '%y-%d-%m': '{y:02d}-{d:02d}-{m:02d}',\n '%y-%d-%m %H:%M:%S': '{y:02d}-{d:02d}-{m:02d} {H:02d}:{M:02d}:{S:02d}',\n '%y/%d/%m': '{y:02d}/{d:02d}/{m:02d}',\n '%y/%d/%m %H:%M:%S': '{y:02d}/{d:02d}/{m:02d} {H:02d}:{M:02d}:{S:02d}',\n '%Y-%d-%m': '{Y:04d}-{d:02d}-{m:02d}',\n '%Y-%d-%m %H:%M:%S': '{Y:04d}-{d:02d}-{m:02d} {H:02d}:{M:02d}:{S:02d}',\n '%Y/%d/%m': '{Y:04d}/{d:02d}/{m:02d}',\n '%Y/%d/%m %H:%M:%S': '{Y:04d}/{d:02d}/{m:02d} {H:02d}:{M:02d}:{S:02d}'\n}\n\n\ndef generate_string(length):\n sequence = []\n for _ in range(length):\n sequence.append(random.choice(letters))\n return ''.join(sequence)\n\n\ndef build_vocab(size):\n vocab = []\n for _ in range(size):\n vocab.append(generate_string(random.randint(2, 10)))\n return vocab\n\n\ndef return_none(feature):\n return None\n\n\ndef assign_vocab(feature):\n feature['idx2str'] = build_vocab(feature['vocab_size'])\n\n\ndef build_feature_parameters(features):\n feature_parameters = {}\n for feature in features:\n fearure_builder_function = get_from_registry(\n feature[TYPE],\n parameters_builders_registry\n )\n\n feature_parameters[feature['name']] = fearure_builder_function(feature)\n return feature_parameters\n\n\nparameters_builders_registry = {\n 'category': assign_vocab,\n 'text': assign_vocab,\n 'numerical': return_none,\n 'binary': return_none,\n 'set': assign_vocab,\n 'bag': assign_vocab,\n 'sequence': assign_vocab,\n 'timeseries': return_none,\n 'image': return_none,\n 'audio': return_none,\n 'date': return_none,\n 'h3': return_none,\n VECTOR: return_none\n}\n\n\ndef build_synthetic_dataset(dataset_size, features):\n build_feature_parameters(features)\n header = []\n for feature in features:\n header.append(feature['name'])\n\n yield header\n for _ in range(dataset_size):\n yield generate_datapoint(features)\n\n\ndef generate_datapoint(features):\n datapoint = []\n for feature in features:\n if ('cycle' in feature and feature['cycle'] is True and\n feature[TYPE] in cyclers_registry):\n cycler_function = cyclers_registry[feature[TYPE]]\n feature_value = cycler_function(feature)\n else:\n generator_function = get_from_registry(\n feature[TYPE],\n generators_registry\n )\n feature_value = generator_function(feature)\n datapoint.append(feature_value)\n return datapoint\n\n\ndef generate_category(feature):\n return random.choice(feature['idx2str'])\n\n\ndef generate_text(feature):\n text = []\n for _ in range(random.randint(feature['max_len'] -\n int(feature['max_len'] * 0.2),\n feature['max_len'])):\n text.append(random.choice(feature['idx2str']))\n return ' '.join(text)\n\n\ndef generate_numerical(feature):\n return random.uniform(\n feature['min'] if 'min' in feature else 0,\n feature['max'] if 'max' in feature else 1\n )\n\n\ndef generate_binary(feature):\n p = feature['prob'] if 'prob' in feature else 0.5\n return np.random.choice([True, False], p=[p, 1 - p])\n\n\ndef generate_sequence(feature):\n length = feature['max_len']\n if 'min_len' in feature:\n length = random.randint(feature['min_len'], feature['max_len'])\n\n sequence = [random.choice(feature['idx2str']) for _ in range(length)]\n\n return ' '.join(sequence)\n\n\ndef generate_set(feature):\n elems = []\n for _ in range(random.randint(0, feature['max_len'])):\n elems.append(random.choice(feature['idx2str']))\n return ' '.join(list(set(elems)))\n\n\ndef generate_bag(feature):\n elems = []\n for _ in range(random.randint(0, feature['max_len'])):\n elems.append(random.choice(feature['idx2str']))\n return ' '.join(elems)\n\n\ndef generate_timeseries(feature):\n series = []\n for _ in range(feature['max_len']):\n series.append(\n str(\n random.uniform(\n feature['min'] if 'min' in feature else 0,\n feature['max'] if 'max' in feature else 1\n )\n )\n )\n return ' '.join(series)\n\n\ndef generate_audio(feature):\n try:\n import soundfile\n except ImportError:\n logger.error(\n ' soundfile is not installed. '\n 'In order to install all audio feature dependencies run '\n 'pip install ludwig[audio]'\n )\n sys.exit(-1)\n\n audio_length = feature['preprocessing']['audio_file_length_limit_in_s']\n audio_dest_folder = feature['audio_dest_folder']\n sampling_rate = 16000\n num_samples = int(audio_length * sampling_rate)\n audio = np.sin(np.arange(num_samples) / 100 * 2 * np.pi) * 2 * (\n np.random.random(num_samples) - 0.5)\n audio_filename = uuid.uuid4().hex[:10].upper() + '.wav'\n\n try:\n if not os.path.exists(audio_dest_folder):\n os.makedirs(audio_dest_folder)\n\n audio_dest_path = os.path.join(audio_dest_folder, audio_filename)\n soundfile.write(audio_dest_path, audio, sampling_rate)\n\n except IOError as e:\n raise IOError(\n 'Unable to create a folder for audio or save audio to disk.'\n '{0}'.format(e))\n\n return audio_dest_path\n\n\ndef generate_image(feature):\n try:\n from skimage.io import imsave\n except ImportError:\n logger.error(\n ' scikit-image is not installed. '\n 'In order to install all image feature dependencies run '\n 'pip install ludwig[image]'\n )\n sys.exit(-1)\n\n # Read num_channels, width, height\n num_channels = feature['preprocessing']['num_channels']\n width = feature['preprocessing']['width']\n height = feature['preprocessing']['height']\n image_dest_folder = feature['destination_folder']\n\n if width <= 0 or height <= 0 or num_channels < 1:\n raise ValueError('Invalid arguments for generating images')\n\n # Create a Random Image\n if num_channels == 1:\n img = np.random.rand(width, height) * 255\n else:\n img = np.random.rand(width, height, num_channels) * 255.0\n\n # Generate a unique random filename\n image_filename = uuid.uuid4().hex[:10].upper() + '.jpg'\n\n # Save the image to disk either in a specified location/new folder\n try:\n if not os.path.exists(image_dest_folder):\n os.makedirs(image_dest_folder)\n\n image_dest_path = os.path.join(image_dest_folder, image_filename)\n imsave(image_dest_path, img.astype('uint8'))\n\n except IOError as e:\n raise IOError('Unable to create a folder for images/save image to disk.'\n '{0}'.format(e))\n\n return image_dest_path\n\n\ndef generate_datetime(feature):\n \"\"\"picking a format among different types.\n If no format is specified, the first one is used.\n \"\"\"\n if 'datetime_format' in feature:\n datetime_generation_format = DATETIME_FORMATS[\n feature['datetime_format']\n ]\n elif ('preprocessing' in feature and\n 'datetime_format' in feature['preprocessing']):\n datetime_generation_format = DATETIME_FORMATS[\n feature['preprocessing']['datetime_format']\n ]\n else:\n datetime_generation_format = DATETIME_FORMATS[0]\n\n y = random.randint(1, 99)\n Y = random.randint(1, 9999)\n m = random.randint(1, 12)\n d = random.randint(1, 28)\n H = random.randint(1, 12)\n M = random.randint(1, 59)\n S = random.randint(1, 59)\n\n return datetime_generation_format.format(y=y, Y=Y, m=m, d=d, H=H, M=M, S=S)\n\n\ndef generate_h3(feature):\n resolution = random.randint(0, 15) # valid values [0, 15]\n h3_components = {\n 'mode': 1, # we can avoid testing other modes\n 'edge': 0, # only used in other modes\n 'resolution': resolution,\n 'base_cell': random.randint(0, 121), # valid values [0, 121]\n # valid values [0, 7]\n 'cells': [random.randint(0, 7) for _ in range(resolution)]\n }\n\n return components_to_h3(h3_components)\n\n\ndef generate_vector(feature):\n # Space delimited string with floating point numbers\n return ' '.join(\n [str(100 * random.random()) for _ in range(feature['vector_size'])]\n )\n\n\ngenerators_registry = {\n 'category': generate_category,\n 'text': generate_sequence,\n 'numerical': generate_numerical,\n 'binary': generate_binary,\n 'set': generate_set,\n 'bag': generate_bag,\n 'sequence': generate_sequence,\n 'timeseries': generate_timeseries,\n 'image': generate_image,\n 'audio': generate_audio,\n 'h3': generate_h3,\n 'date': generate_datetime,\n VECTOR: generate_vector\n\n}\n\ncategory_cycle = 0\n\n\ndef cycle_category(feature):\n global category_cycle\n if category_cycle >= len(feature['idx2str']):\n category_cycle = 0\n category = feature['idx2str'][category_cycle]\n category_cycle += 1\n return category\n\n\nbinary_cycle = False\n\n\ndef cycle_binary(feature):\n global binary_cycle\n if binary_cycle:\n binary_cycle = False\n return True\n else:\n binary_cycle = True\n return False\n\n\ncyclers_registry = {\n 'category': cycle_category,\n 'binary': cycle_binary\n}\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='This script generates a synthetic dataset.')\n parser.add_argument('csv_file_path', help='output csv file path')\n parser.add_argument(\n '-d',\n '--dataset_size',\n help='size of the dataset',\n type=int,\n default=100\n )\n parser.add_argument(\n '-f',\n '--features',\n default='[\\\n {name: text_1, type: text, vocab_size: 20, max_len: 20}, \\\n {name: text_2, type: text, vocab_size: 20, max_len: 20}, \\\n {name: category_1, type: category, vocab_size: 10}, \\\n {name: category_2, type: category, vocab_size: 15}, \\\n {name: numerical_1, type: numerical}, \\\n {name: numerical_2, type: numerical}, \\\n {name: binary_1, type: binary}, \\\n {name: binary_2, type: binary}, \\\n {name: set_1, type: set, vocab_size: 20, max_len: 20}, \\\n {name: set_2, type: set, vocab_size: 20, max_len: 20}, \\\n {name: bag_1, type: bag, vocab_size: 20, max_len: 10}, \\\n {name: bag_2, type: bag, vocab_size: 20, max_len: 10}, \\\n {name: sequence_1, type: sequence, vocab_size: 20, max_len: 20}, \\\n {name: sequence_2, type: sequence, vocab_size: 20, max_len: 20}, \\\n {name: timeseries_1, type: timeseries, max_len: 20}, \\\n {name: timeseries_2, type: timeseries, max_len: 20}, \\\n ]',\n type=yaml.safe_load, help='dataset features'\n )\n args = parser.parse_args()\n\n dataset = build_synthetic_dataset(args.dataset_size, args.features)\n save_csv(args.csv_file_path, dataset)\n"
] |
[
[
"numpy.max",
"numpy.iinfo"
],
[
"numpy.arange",
"numpy.random.random",
"numpy.random.rand",
"numpy.random.choice"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chiahungyang/EEG_demo
|
[
"c76e8f88368ef7c5f24bc7443a556e36713c454c"
] |
[
"eegbci.py"
] |
[
"\"\"\"Utility module for the EEGBCI motor/imagery dataset.\"\"\"\n\n\nfrom multiprocessing.pool import RUN\nimport numpy as np\nimport pandas as pd\nimport mne\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, ConcatDataset, Subset\nimport pytorch_lightning as pl\nimport sklearn\nfrom typing import Callable, Optional\nfrom augs import UnitScale\n\n# Integer identifier of experimental tasks/events\nEVENT_ID = {\n 'rest/eye-open': 0,\n 'rest/eye-closed': 1,\n 'movement/left/fist': 2,\n 'movement/right/fist': 3,\n 'imagery/left/fist': 4,\n 'imagery/right/fist': 5,\n 'movement/both/fist': 6,\n 'movement/both/foot': 7,\n 'imagery/both/fist': 8,\n 'imagery/both/foot': 9\n}\n\n# Experimental runs and subjects\nNUM_SUBJECTS = 109\nSUBJECTS_EXCLUDED = [88, 92, 100] # outliers with a different sample frequency\nSUBJECTS = [i for i in range(1, NUM_SUBJECTS+1) if i not in SUBJECTS_EXCLUDED]\n\nNUM_RUNS = 14\nRUNS = [i for i in range(1, NUM_RUNS+1)]\n\n\ndef extract_windows(\n raw: mne.io.Raw,\n subject: int,\n run: int,\n event_id: dict,\n num_steps: int = 640,\n baseline_duration: float = 0.2\n):\n \"\"\"\n Return windows/epochs extracted from raw data.\n\n Arguments\n ---------\n raw: Raw data\n subject: Subject of recording\n run: Experimental run\n event_id: Mapping from tasks/events to integer identifiers\n num_steps: Number of time steps in a window (excluding baseline segment)\n baseline_duration: Duration of baseline for drift correction\n \n Note\n ----\n Baseline segments are not discarded from the returned windows.\n \"\"\"\n duration = (num_steps - 1) / raw.info['sfreq']\n events, focal_event_id = get_events(raw, run, event_id, duration)\n metadata = pd.DataFrame({\n 'start': events[:, 0] / raw.info['sfreq'], # start time of tasks\n 'task': events[:, -1], # identifier of experimental tasks\n 'subject': subject,\n 'run': run\n })\n event_mapping = {ind: key for key, ind in event_id.items()}\n epochs = mne.Epochs(\n raw,\n events,\n event_id={event_mapping[ind]: ind for ind in focal_event_id.values()},\n tmin=-baseline_duration,\n tmax=duration,\n metadata=metadata,\n verbose=False\n )\n drop_bad_epochs(\n epochs,\n raw,\n int(duration * raw.info['sfreq']),\n int(baseline_duration * raw.info['sfreq'])\n )\n return epochs\n\n\ndef get_events(\n raw: mne.io.Raw,\n run: int,\n event_id: dict,\n fixed_length_duration: float = 4.0\n):\n \"\"\"\n Return tuple of events and their integer-identifier-mapping according to\n the experimental run.\n\n Argmuments\n ----------\n raw: Raw data\n run: Experimental run\n event_id: Mapping from tasks/events to integer identifiers\n fixed_length_duration: Duration to create fixed-length events\n\n Note\n ----\n For runs with alternating experimental tasks, the rest-state periods in\n between will not be considered.\n \"\"\"\n if run in (1, 2):\n annotation = 'rest/eye-open' if run == 1 else 'rest/eye-closed'\n events = mne.make_fixed_length_events(\n raw,\n id=event_id[annotation],\n duration=fixed_length_duration\n )\n return events, {'T0': event_id[annotation] }\n elif run in (3, 7, 11):\n event_id = {\n 'T1': event_id['movement/left/fist'],\n 'T2': event_id['movement/right/fist']\n }\n return mne.events_from_annotations(raw, event_id, verbose=False)\n elif run in (4, 8, 12):\n event_id = {\n 'T1': event_id['imagery/left/fist'],\n 'T2': event_id['imagery/right/fist']\n }\n return mne.events_from_annotations(raw, event_id, verbose=False)\n elif run in (5, 9, 13):\n event_id = {\n 'T1': event_id['movement/both/fist'],\n 'T2': event_id['movement/both/foot']\n }\n return mne.events_from_annotations(raw, event_id, verbose=False)\n elif run in (6, 10, 14):\n event_id = {\n 'T1': event_id['imagery/both/fist'],\n 'T2': event_id['imagery/both/foot']\n }\n return mne.events_from_annotations(raw, event_id, verbose=False)\n else:\n raise ValueError('invalid experimental run.')\n\n\ndef drop_bad_epochs(\n epochs: mne.Epochs,\n raw: mne.io.Raw,\n epoch_steps: int,\n baseline_steps: int\n) -> None:\n \"\"\"\n In-place drop epochs that are too short or lack baseline data.\n\n Arguments\n ---------\n epochs: Epochs to manipulate\n raw: Raw data from which epochs were extracted\n epoch_steps: Number of time steps per epoch\n baseline_steps: Number of time steps of baseline period\n \"\"\"\n # Drop epochs with fewer steps than the pre-specified number\n mask = (raw.n_times - 1 - epochs.events[:, 0]) < epoch_steps\n epochs.drop(mask, reason='USER: TOO SHORT', verbose=False)\n # Drop epochs which lack baseline data\n mask = (epochs.events[:, 0] - baseline_steps) < 0\n epochs.drop(mask, reason='USER: NO BASELINE', verbose=False)\n\n\ndef download_eegbci(\n subjects: list,\n runs: list,\n dir: str = './'\n) -> None:\n \"\"\"\n Download the EEGBCI motor movement/imagery dat.\n\n Arguments\n ---------\n subjects: List of subjects of interest\n runs: List of experimental runs for each subject\n dir: Root directory path to the EEGBCI data\n \"\"\"\n for subject in subjects:\n mne.datasets.eegbci.load_data(subject, runs, path=dir)\n\n\ndef eegbci_epochs_collection(\n subjects: list,\n runs: list,\n dir: str = './',\n **kwargs\n) -> list:\n \"\"\"\n Return extracted windows/epochs from the EEGBCI motor movement/imagery data.\n\n Arguments\n ---------\n subjects: List of subjects of interest\n runs: List of experimental runs for each subject\n dir: Root directory path to the EEGBCI data\n kwargs: Keyword arguments passed to extract windows\n \n Note\n ----\n Baseline segments are not discarded from the returned windows.\n \"\"\"\n epochs_list = [\n extract_windows(\n mne.io.read_raw_edf(\n mne.datasets.eegbci.load_data(subject, run, path=dir)[0],\n verbose=False\n ),\n subject,\n run,\n EVENT_ID,\n **kwargs\n ) for subject in subjects for run in runs\n ]\n return epochs_list\n\n\nclass WindowDataset(Dataset):\n \"\"\"Dataset of extracted windows/epochs.\"\"\"\n\n def __init__(\n self,\n windows: mne.Epochs,\n get_label: Callable,\n transform: Callable = None,\n target_transform: Callable = None\n ):\n \"\"\"\n Arguments\n ---------\n windows: Extracted windows\n get_label: Function to extract label from metadata\n transform: Transformation upon data\n target_transform: Transformation upon labels\n \n Note\n ----\n Baseline segments are discarded from the returned windows.\n \"\"\"\n super().__init__()\n self.windows = windows\n self.get_label = get_label\n self.transform = transform\n self.target_transform = target_transform\n \n def __len__(self):\n return len(self.windows.events)\n \n def __getitem__(self, ind: int):\n window = self.windows[ind]\n data = window.get_data(tmin=0.0)[0] # baseline segment discarded\n data = torch.from_numpy(data).float() # convert to float32 tensor\n if self.transform: data = self.transform(data)\n label = self.get_label(window.metadata)\n if self.target_transform: label = self.target_transform(label)\n return data, label\n\n\nclass EEGBCIDataset(ConcatDataset):\n \"\"\"Dataset of the EEGBCI motor movement/imagery data.\"\"\"\n\n def __init__(\n self,\n subjects: list,\n runs: list,\n num_steps: int,\n get_label: Callable,\n transform: Callable = None,\n target_transform: Callable = None,\n **kwargs\n ):\n \"\"\"\n Arguments\n ---------\n subjects: List of subjects of interest\n runs: List of experimental runs for each subject\n num_steps: Number of time points in each extracted window\n get_label: Function to extract label from metadata\n transform: Transformation upon data\n target_transform: Transformation upon labels\n kwargs: Keyword arguments passed to extract windows\n \"\"\"\n epochs = eegbci_epochs_collection(\n subjects,\n runs,\n num_steps=num_steps,\n **kwargs\n )\n datasets = [\n WindowDataset(windows, get_label, transform, target_transform)\n for windows in epochs\n ]\n super().__init__(datasets)\n self.metadata = pd.concat([windows.metadata for windows in epochs])\n\n\nclass PretextDataModule(pl.LightningDataModule):\n \"\"\"EEGBCI motor movement/imagery datamodule for pretext training.\"\"\"\n\n def __init__(\n self,\n batch_size: int,\n num_steps: int,\n val_ratio: float = 0.2,\n dir: str = './'\n ):\n \"\"\"\n Arguments\n ---------\n batch_size: Batch size of training/validation sets\n num_steps: Number of time steps per data sample\n val_ratio: Ratio to split validation set from whole data\n dir: Directory path to store downloaded data\n \"\"\"\n super().__init__()\n self.batch_size = batch_size\n self.num_steps = num_steps\n self.val_ratio = val_ratio\n self.data_dir = dir\n self.subjects = SUBJECTS # all subjects\n self.runs = RUNS # all runs\n self.get_label = lambda x: -1 # constant (vaccum) get-label function\n \n def prepare_data(self):\n # Download data\n download_eegbci(self.subjects, self.runs, dir=self.data_dir)\n \n def setup(self, stage: Optional[str] = None):\n # Split data into train and validation sets\n dataset = EEGBCIDataset(\n self.subjects,\n self.runs,\n self.num_steps,\n self.get_label,\n dir=self.data_dir,\n transform=UnitScale()\n )\n num_val = int(len(dataset) * self.val_ratio)\n self.trainset, self.valset = torch.utils.data.random_split(\n dataset,\n [len(dataset) - num_val, num_val]\n )\n \n def train_dataloader(self):\n return DataLoader(self.trainset, batch_size=self.batch_size, shuffle=True)\n \n def val_dataloader(self):\n return DataLoader(self.valset, batch_size=self.batch_size)\n\n\ndef runs_classindex_by_case(downstream):\n \"\"\"\n Return the experimental runs and mapping of relevant events (identifiers)\n to class indices according to the given case of downstream task.\n \"\"\"\n if downstream == 'annotation':\n runs = RUNS\n class_ind = {ind: ind for ind in EVENT_ID.values()}\n elif downstream == 'left/right':\n runs = [3, 4, 7, 8, 11, 12]\n class_ind = {2: 0, 3: 1, 4: 0, 5: 1}\n elif downstream == 'movement/imagery':\n runs = list(range(3, 14 + 1))\n class_ind = {2: 0, 3: 0, 4: 1, 5: 1, 6: 0, 7: 0, 8: 1, 9: 1}\n elif downstream == 'fist/foot':\n runs = list(range(3, 14 + 1))\n class_ind = {2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 1, 8: 0, 9: 1}\n elif downstream == 'rest/unrest':\n runs = list(range(1, 14 + 1))\n class_ind = {0: 0, 1: 0, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1}\n else:\n raise ValueError('downstream task not recognized')\n return runs, class_ind\n\n\nclass DownstreamDataModule(pl.LightningDataModule):\n \"\"\"EEGBCI motor movement/imagery datamodule for downstream tasks.\"\"\"\n\n def __init__(\n self,\n downstream: str,\n batch_size: int,\n num_steps: int,\n val_ratio: float = 0.1,\n test_ratio: float = 0.1,\n dir: str = './'\n ):\n \"\"\"\n Arguments\n ---------\n downstream: String tag of the downstream task\n batch_size: Batch size of training/validation sets\n num_steps: Number of time steps per data sample\n val_ratio: Ratio to split validation set from whole data\n test_ratio: Ratio to split test set from whole data\n dir: Directory path to store downloaded data\n \"\"\"\n super().__init__()\n self.batch_size = batch_size\n self.num_steps = num_steps\n self.val_ratio = val_ratio\n self.test_ratio = test_ratio\n self.data_dir = dir\n self.subjects = SUBJECTS\n self.runs, class_ind = runs_classindex_by_case(downstream)\n # Function to get label for classification\n self.get_label = lambda meta: class_ind[meta['task'].values[0]]\n # Function to get annotation for stratified data splitting\n self.get_annotations = lambda meta: meta['task'].values\n \n def prepare_data(self):\n # Download data\n download_eegbci(self.subjects, self.runs, dir=self.data_dir)\n \n def setup(self, stage: Optional[str] = None):\n # Split data into train, validation, and test sets\n dataset = EEGBCIDataset(\n self.subjects,\n self.runs,\n self.num_steps,\n self.get_label,\n dir=self.data_dir,\n transform=UnitScale()\n )\n num_val = int(len(dataset) * self.val_ratio)\n num_test = int(len(dataset) * self.test_ratio)\n # Splitting is done in a stratified fashion based on annotations\n annts = self.get_annotations(dataset.metadata)\n train_val_inds, test_inds = sklearn.model_selection.train_test_split(\n np.arange(len(dataset)),\n test_size=num_test,\n stratify=annts\n )\n train_inds, val_inds = sklearn.model_selection.train_test_split(\n train_val_inds,\n test_size=num_val,\n stratify=annts[train_val_inds]\n )\n if stage == 'fit' or stage is None:\n self.trainset = Subset(dataset, train_inds)\n self.valset = Subset(dataset, val_inds)\n if stage == 'test' or stage is None:\n self.testset = Subset(dataset, test_inds)\n \n def train_dataloader(self):\n return DataLoader(self.trainset, batch_size=self.batch_size, shuffle=True)\n \n def val_dataloader(self):\n return DataLoader(self.valset, batch_size=self.batch_size)\n \n def test_dataloader(self):\n return DataLoader(self.testset, batch_size=self.batch_size)\n\n\ndef main():\n \"\"\"Empty main.\"\"\"\n return\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"pandas.concat",
"torch.utils.data.DataLoader",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"torch.from_numpy",
"torch.utils.data.Subset"
]
] |
[
{
"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": []
}
] |
braniii/prettypyplot
|
[
"39d7d133fe0dc6699fafd57e00a0ec07672fd344"
] |
[
"prettypyplot/plot.py"
] |
[
"\"\"\"Wrapper for matplotlib plotting functions.\n\nBSD 3-Clause License\nCopyright (c) 2020-2021, Daniel Nagel\nAll rights reserved.\n\n\"\"\"\n# ~~~ IMPORT ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nimport warnings\nfrom os import path\n\nimport numpy as np\nfrom matplotlib import legend as mlegend\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits import axes_grid1 as mpl_axes_grid1\n\nimport prettypyplot as _pplt\nfrom prettypyplot import tools\nfrom prettypyplot.style import Mode, Style\n\n\n# ~~~ FUNCTIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ndef imshow(*args, ax=None, **kwargs):\n \"\"\"Display an image, i.e. data on a 2D regular raster.\n\n This is a wrapper of pyplot.imshow(). In contrast to the original function\n the default value of `zorder` is increased to `1`.\n\n Parameters\n ----------\n ax : matplotlib axes, optional\n Matplotlib axes to plot in.\n\n args, kwargs\n See [pyplot.imshow()](MPL_DOC.pyplot.imshow.html)\n\n Returns\n -------\n im : matplolib.image.AxesImage\n Reference to plotted image.\n\n \"\"\"\n args, ax = tools.parse_axes(*args, ax=ax)\n\n if 'zorder' not in kwargs:\n kwargs['zorder'] = 1\n\n # plot\n return ax.imshow(*args, **kwargs)\n\n\ndef plot(*args, ax=None, **kwargs):\n \"\"\"Plot simple lineplot.\n\n Wrapping pyplot.plot() to adjust to style. For more information on the\n arguments see in matplotlib documentation.\n If STYLE='minimal', spines will be limited to plotting range.\n\n Parameters\n ----------\n ax : matplotlib axes\n Matplotlib axes to plot in.\n\n args, kwargs\n See [pyplot.plot()](MPL_DOC.pyplot.plot.html)\n\n Returns\n -------\n lines : list of matplolib.lines.Line2D\n A list of lines representing the plotted data.\n\n \"\"\"\n # parse axes\n args, ax = tools.parse_axes(*args, ax=ax)\n\n # plot\n lines = ax.plot(*args, **kwargs)\n\n if _pplt.STYLE == Style.MINIMAL:\n _set_spine_bounds(ax)\n\n return lines\n\n\ndef savefig(fname, use_canvas_size=True, **kwargs):\n \"\"\"Save figure as png and pdf.\n\n This methods corrects figsize for poster/beamer mode.\n\n Parameters\n ----------\n fname : str\n Output filename. If no file ending, pdf will be used.\n\n use_canvas_size : bool, optional\n If True the specified figsize will be used as canvas size.\n\n kwargs\n See [pyplot.savefig()](MPL_DOC.pyplot.savefig.html)\n\n \"\"\"\n fig = plt.gcf()\n ax = fig.get_axes()[0]\n figsize = fig.get_size_inches()\n\n # store figsize to reset it later\n set_figsize = figsize\n\n if _pplt.STYLE == Style.MINIMAL:\n _reduce_ticks(fig)\n\n if _pplt.MODE in {Mode.POSTER, Mode.BEAMER}:\n fig.set_size_inches(\n (3 * figsize[0], 3 * figsize[1]),\n )\n\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore')\n fig.tight_layout()\n\n # convert figsize to canvas size\n if use_canvas_size:\n x0, y0, width, height = ax.get_position().bounds\n figsize = (figsize[0] / width, figsize[1] / height)\n fig.set_size_inches(figsize)\n\n # save as pdf if not specified\n if 'format' not in kwargs:\n if path.splitext(fname)[1][1:] == '':\n fname = '{0}.pdf'.format(fname)\n\n # save fig\n plt.savefig(fname, **kwargs)\n\n # reset figsize, if user calls this function multiple times on same figure\n fig.set_size_inches(set_figsize)\n\n\ndef _reduce_ticks(fig):\n \"\"\"Reduce number of ticks by factor 1.5 if more than 4.\"\"\"\n # TODO: replace this by mpl built-in class\n tick_reduc = 1.5\n for axes in fig.get_axes():\n if len(axes.get_xticks()) > 4:\n axes.locator_params(\n tight=False,\n axis='x',\n nbins=len(axes.get_xticks()) / tick_reduc,\n )\n if len(axes.get_yticks()) > 4:\n axes.locator_params(\n tight=False,\n axis='y',\n nbins=len(axes.get_yticks()) / tick_reduc,\n )\n\n\ndef _legend_default_kwargs():\n \"\"\"Return default values of given outside positions.\"\"\"\n return {\n 'top': {\n 'bbox_to_anchor': (0.0, 1.0, 1.0, 0.01),\n 'mode': 'expand',\n 'loc': 'lower left',\n },\n 'bottom': {\n 'bbox_to_anchor': (0.0, 0.0, 1.0, 0.01),\n 'mode': 'expand',\n 'loc': 'upper left',\n },\n 'right': {\n 'bbox_to_anchor': (1.03, 0.5),\n 'loc': 'center left',\n },\n 'left': {\n 'bbox_to_anchor': (-0.03, 0.5),\n 'loc': 'center right',\n },\n }\n\n\ndef legend(*args, outside=False, ax=None, axs=None, **kwargs):\n \"\"\"Generate a nice legend.\n\n This is a wrapper of pyplot.legend(). Take a look there for the default\n arguments and options. The ticks and labels are moved to the opposite side.\n For `top` and `bottom` the default value of columns is set to the number of\n labels, for all other options to 1. In case of many labels this parameter\n needs to be adjusted.\n\n .. todo::\n Use handles and labels from *args if provided\n\n Parameters\n ----------\n outside : str or bool\n False, 'top', 'right', 'bottom' or 'left'.\n\n axs : list of mpl.axes.Axes\n List of axes which are used for extracting all labels.\n\n ax : mpl.axes.Axes\n Axes which is used for placing legend.\n\n args, kwargs\n See [pyplot.legend()](MPL_DOC.pyplot.legend.html)\n\n Returns\n -------\n leg : matplotlib.legend.Legend\n Matplotlib legend handle.\n\n Examples\n --------\n .. include:: ../gallery/legend/README.md\n\n \"\"\"\n default_kwargs = _legend_default_kwargs()\n if outside not in {False, *default_kwargs}:\n raise ValueError(\n 'Use for outside one of [False, {0}]'.format(\n ', '.join(['\"{0}\"'.format(dr) for dr in default_kwargs]),\n ),\n )\n\n # parse axes\n args, ax = tools.parse_axes(*args, ax=ax)\n\n # parse axs\n if axs is None:\n axs = [ax]\n else:\n axs = tools.get_axes(axs)\n\n # shift axis to opposite side.\n if outside:\n activate_axis(_opposite_side(outside))\n\n # set anchor, mode and location\n kwargs = {**default_kwargs.get(outside, {}), **kwargs}\n\n # get handles and labels of selected axes\n handles, labels = mlegend._get_legend_handles_labels(axs) # noqa: WPS437\n\n # set number of ncol to the number of items\n if outside in {'top', 'bottom'}:\n kwargs.setdefault('ncol', len(labels))\n\n # generate legend\n leg = ax.legend(handles, labels, *args, **kwargs)\n if _pplt.STYLE == Style.MINIMAL:\n leg.get_frame().set_linewidth(0.0)\n elif _pplt.STYLE == Style.DEFAULT:\n leg.get_frame().set_linewidth(plt.rcParams['axes.linewidth'])\n\n # shift title to the left if on top or bottom\n if outside in {'top', 'bottom'}:\n _shift_legend_title(leg)\n\n return leg\n\n\ndef _shift_legend_title(leg):\n \"\"\"Shift title to the left of the labels.\"\"\"\n # taken from: https://stackoverflow.com/a/53329898\n child = leg.get_children()[0]\n title = child.get_children()[0]\n hpack = child.get_children()[1]\n child._children = [hpack] # noqa: WPS437\n hpack._children = [title] + hpack.get_children() # noqa: WPS437\n\n\ndef _opposite_side(pos):\n \"\"\"Return opposite of 'top', 'bottom', 'left', 'right'.\"\"\"\n opposite = {\n 'top': 'bottom',\n 'bottom': 'top',\n 'right': 'left',\n 'left': 'right',\n }\n if pos not in opposite:\n raise ValueError(\n 'Pos needs to be one of [{0}].'.format(\n ', '.join('\"{0}\"'.format(position) for position in opposite),\n ),\n )\n\n return opposite[pos]\n\n\ndef activate_axis(position, ax=None):\n \"\"\"Shift the specified axis to the opposite side.\n\n Parameters\n ----------\n position : str or list of str\n Specify axis to flip, one of ['left', 'right', 'top', 'bottom'].\n\n ax : matplotlib axes\n Matplotlib axes to flip axis.\n\n \"\"\"\n # get axes\n ax = tools.gca(ax)\n\n # convert string to list of strings\n if isinstance(position, str):\n position = [position]\n\n # allowed values\n positions = {'bottom', 'top', 'left', 'right'}\n\n # move axes ticks and labels to opposite side of position\n for pos in position:\n if pos not in positions:\n raise ValueError(\n '{0:!r} is not a valid value for {1}; supported values are {2}'\n .format(pos, 'position', ', '.join(positions))\n )\n\n if pos in {'bottom', 'top'}:\n axis = ax.xaxis\n elif pos in {'left', 'right'}:\n axis = ax.yaxis\n axis.set_ticks_position(pos)\n axis.set_label_position(pos)\n\n\ndef colorbar(im, width='7%', pad='0%', position='right', label=None, **kwargs):\n \"\"\"Generate colorbar of same height as image.\n\n Wrapper around pyplot.colorbar which corrects the height.\n\n Parameters\n ----------\n im : matplotlib.axes.AxesImage\n Specify the object the colorbar belongs to, e.g. the return value of\n pyplot.imshow().\n\n width : str or float, optional\n The width between figure and colorbar stated relative as string ending\n with '%' or absolute value in inches.\n\n pad : str or float, optional\n The width between figure and colorbar stated relative as string ending\n with '%' or absolute value in inches.\n\n position : str, optional\n Specify the position relative to the image where the colorbar is\n plotted, choose one of ['left', 'top', 'right', 'bottom']\n\n label : str, optional\n Specify the colorbar label.\n\n kwargs\n Colorbar properties of\n [pyplot.colorbar()](MPL_DOC.pyplot.colorbar.html)\n\n Returns\n -------\n colorbar : matplotlib.colorbar.Colorbar\n Colorbar instance.\n\n \"\"\"\n orientation = 'vertical'\n if position in {'top', 'bottom'}:\n orientation = 'horizontal'\n\n # get axes\n if hasattr(im, 'axes'): # noqa: WPS421\n ax = im.axes\n elif hasattr(im, 'ax'): # noqa: WPS421\n ax = im.ax\n else:\n ax = plt.gca()\n\n # generate divider\n divider = mpl_axes_grid1.make_axes_locatable(ax)\n cax = divider.append_axes(position, width, pad=pad)\n\n cbar = plt.colorbar(im, cax=cax, orientation=orientation)\n if label:\n cbar.set_label(label)\n\n # set ticks and label of ticks to the outside\n activate_axis(position, ax=cax)\n # set the axis opposite to the colorbar to active\n activate_axis(_opposite_side(position), ax=ax)\n\n # invert width and pad\n pad_inv, width_inv = tools.invert_sign(pad), tools.invert_sign(width)\n cax_reset = divider.append_axes(position, width_inv, pad=pad_inv)\n cax_reset.set_visible(False)\n\n return cbar\n\n\ndef grid(*args, ax=None, **kwargs):\n \"\"\"Generate grid.\n\n This function will add a major and minor grid in case of STYLE='default',\n a major grid in case of 'none' and otherwise nothing.\n\n Parameters\n ----------\n ax : matplotlib axes\n Axes to plot grid.\n\n args, kwargs\n See [pyplot.grid()](MPL_DOC.pyplot.grid.html)\n\n \"\"\"\n # parse axes\n args, ax = tools.parse_axes(*args, ax=ax)\n\n if 'b' not in kwargs:\n boolargs = [arg for arg in args if isinstance(arg, bool)]\n if len(boolargs) > 1:\n raise ValueError('Only a single bool parameter is allowed.')\n elif len(boolargs) == 1:\n show_grid = boolargs[0]\n else:\n show_grid = True\n\n kwargs['b'] = show_grid\n\n if _pplt.STYLE == Style.DEFAULT:\n gr_maj = ax.grid(which='major', linestyle='--', **kwargs)\n gr_min = ax.grid(which='minor', linestyle='dotted', **kwargs)\n ax.set_axisbelow(True)\n return (gr_maj, gr_min)\n\n\ndef _xminmax(ax):\n \"\"\"Get xrange of plotted data.\"\"\"\n return _minmax(lim=ax.get_xlim(), rcparam='axes.xmargin')\n\n\ndef _yminmax(ax):\n \"\"\"Get yrange of plotted data.\"\"\"\n return _minmax(lim=ax.get_ylim(), rcparam='axes.ymargin')\n\n\ndef _minmax(lim, rcparam):\n \"\"\"Get range of plotted data.\"\"\"\n width = lim[1] - lim[0]\n margin = plt.rcParams[rcparam]\n return lim[0] + np.array([ # min max\n (margin + idx) / (1 + 2 * margin) * width\n for idx in (0, 1)\n ])\n\n\ndef _set_spine_bounds(ax):\n \"\"\"Limit spines to data range, keeping ticks unchanged.\"\"\"\n for minmax, ticks, poss in (\n (_xminmax(ax), ax.get_xticks(), ('bottom', 'top')),\n (_yminmax(ax), ax.get_yticks(), ('left', 'right')),\n ):\n if ticks.size:\n for pos in poss:\n ax.spines[pos].set_bounds(*minmax)\n"
] |
[
[
"matplotlib.pyplot.gca",
"matplotlib.legend._get_legend_handles_labels",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.colorbar",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
AbdullahKeteldijk/yahoo_fin
|
[
"b6753cf929965009a0e30450e2ad2fddad2e93fd"
] |
[
"yahoo_fin/stock_info.py"
] |
[
"import requests\r\nimport pandas as pd\r\nimport ftplib\r\nimport io\r\nimport re\r\nimport json\r\nimport datetime\r\n\r\ntry:\r\n from requests_html import HTMLSession\r\nexcept Exception:\r\n print(\"\"\"Warning - Certain functionality \r\n requires requests_html, which is not installed.\r\n \r\n Install using: \r\n pip install requests_html\r\n \r\n After installation, you may have to restart your Python session.\"\"\")\r\n\r\n \r\nbase_url = \"https://query1.finance.yahoo.com/v8/finance/chart/\"\r\n\r\ndef build_url(ticker, start_date = None, end_date = None, interval = \"1d\"):\r\n \r\n if end_date is None: \r\n end_seconds = int(pd.Timestamp(\"now\").timestamp())\r\n \r\n else:\r\n end_seconds = int(pd.Timestamp(end_date).timestamp())\r\n \r\n if start_date is None:\r\n start_seconds = 7223400 \r\n \r\n else:\r\n start_seconds = int(pd.Timestamp(start_date).timestamp())\r\n \r\n site = base_url + ticker\r\n \r\n params = {\"period1\": start_seconds, \"period2\": end_seconds,\r\n \"interval\": interval.lower(), \"events\": \"div,splits\"}\r\n \r\n \r\n return site, params\r\n\r\n\r\ndef force_float(elt):\r\n \r\n try:\r\n return float(elt)\r\n except:\r\n return elt\r\n \r\ndef _convert_to_numeric(s):\r\n\r\n if \"M\" in s:\r\n s = s.strip(\"M\")\r\n return force_float(s) * 1_000_000\r\n \r\n if \"B\" in s:\r\n s = s.strip(\"B\")\r\n return force_float(s) * 1_000_000_000\r\n \r\n return force_float(s)\r\n\r\n\r\ndef get_data(ticker, start_date = None, end_date = None, index_as_date = True,\r\n interval = \"1d\", headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\r\n):\r\n '''Downloads historical stock price data into a pandas data frame. Interval\r\n must be \"1d\", \"1wk\", \"1mo\", or \"1m\" for daily, weekly, monthly, or minute data.\r\n Intraday minute data is limited to 7 days.\r\n \r\n @param: ticker\r\n @param: start_date = None\r\n @param: end_date = None\r\n @param: index_as_date = True\r\n @param: interval = \"1d\"\r\n '''\r\n \r\n if interval not in (\"1d\", \"1wk\", \"1mo\", \"1m\"):\r\n raise AssertionError(\"interval must be of of '1d', '1wk', '1mo', or '1m'\")\r\n \r\n \r\n # build and connect to URL\r\n site, params = build_url(ticker, start_date, end_date, interval)\r\n resp = requests.get(site, params = params, headers = headers)\r\n \r\n \r\n if not resp.ok:\r\n raise AssertionError(resp.json())\r\n \r\n \r\n # get JSON response\r\n data = resp.json()\r\n \r\n # get open / high / low / close data\r\n frame = pd.DataFrame(data[\"chart\"][\"result\"][0][\"indicators\"][\"quote\"][0])\r\n\r\n # get the date info\r\n temp_time = data[\"chart\"][\"result\"][0][\"timestamp\"]\r\n\r\n if interval != \"1m\":\r\n \r\n # add in adjclose\r\n frame[\"adjclose\"] = data[\"chart\"][\"result\"][0][\"indicators\"][\"adjclose\"][0][\"adjclose\"] \r\n frame.index = pd.to_datetime(temp_time, unit = \"s\")\r\n frame.index = frame.index.map(lambda dt: dt.floor(\"d\"))\r\n frame = frame[[\"open\", \"high\", \"low\", \"close\", \"adjclose\", \"volume\"]]\r\n \r\n else:\r\n\r\n frame.index = pd.to_datetime(temp_time, unit = \"s\")\r\n frame = frame[[\"open\", \"high\", \"low\", \"close\", \"volume\"]]\r\n \r\n \r\n frame['ticker'] = ticker.upper()\r\n \r\n if not index_as_date: \r\n frame = frame.reset_index()\r\n frame.rename(columns = {\"index\": \"date\"}, inplace = True)\r\n \r\n return frame\r\n\r\n\r\n\r\ndef tickers_sp500(include_company_data = False):\r\n '''Downloads list of tickers currently listed in the S&P 500 '''\r\n # get list of all S&P 500 stocks\r\n sp500 = pd.read_html(\"https://en.wikipedia.org/wiki/List_of_S%26P_500_companies\")[0]\r\n sp500[\"Symbol\"] = sp500[\"Symbol\"].str.replace(\".\", \"-\", regex=True)\r\n\r\n if include_company_data:\r\n return sp500\r\n\r\n sp_tickers = sp500.Symbol.tolist()\r\n sp_tickers = sorted(sp_tickers)\r\n \r\n return sp_tickers\r\n\r\n\r\ndef tickers_nasdaq(include_company_data = False):\r\n \r\n '''Downloads list of tickers currently listed in the NASDAQ'''\r\n \r\n ftp = ftplib.FTP(\"ftp.nasdaqtrader.com\")\r\n ftp.login()\r\n ftp.cwd(\"SymbolDirectory\")\r\n \r\n r = io.BytesIO()\r\n ftp.retrbinary('RETR nasdaqlisted.txt', r.write)\r\n \r\n if include_company_data:\r\n r.seek(0)\r\n data = pd.read_csv(r, sep = \"|\")\r\n return data\r\n \r\n info = r.getvalue().decode()\r\n splits = info.split(\"|\")\r\n \r\n \r\n tickers = [x for x in splits if \"\\r\\n\" in x]\r\n tickers = [x.split(\"\\r\\n\")[1] for x in tickers if \"NASDAQ\" not in x != \"\\r\\n\"]\r\n tickers = [ticker for ticker in tickers if \"File\" not in ticker] \r\n \r\n ftp.close() \r\n\r\n return tickers\r\n \r\n \r\n\r\ndef tickers_other(include_company_data = False):\r\n '''Downloads list of tickers currently listed in the \"otherlisted.txt\"\r\n file on \"ftp.nasdaqtrader.com\" '''\r\n ftp = ftplib.FTP(\"ftp.nasdaqtrader.com\")\r\n ftp.login()\r\n ftp.cwd(\"SymbolDirectory\")\r\n \r\n r = io.BytesIO()\r\n ftp.retrbinary('RETR otherlisted.txt', r.write)\r\n \r\n if include_company_data:\r\n r.seek(0)\r\n data = pd.read_csv(r, sep = \"|\")\r\n return data\r\n \r\n info = r.getvalue().decode()\r\n splits = info.split(\"|\") \r\n \r\n tickers = [x for x in splits if \"\\r\\n\" in x]\r\n tickers = [x.split(\"\\r\\n\")[1] for x in tickers]\r\n tickers = [ticker for ticker in tickers if \"File\" not in ticker] \r\n \r\n ftp.close() \r\n\r\n return tickers\r\n \r\n \r\ndef tickers_dow(include_company_data = False):\r\n \r\n '''Downloads list of currently traded tickers on the Dow'''\r\n\r\n site = \"https://en.wikipedia.org/wiki/Dow_Jones_Industrial_Average\"\r\n \r\n table = pd.read_html(site, attrs = {\"id\":\"constituents\"})[0]\r\n \r\n if include_company_data:\r\n return table\r\n\r\n dow_tickers = sorted(table['Symbol'].tolist())\r\n \r\n return dow_tickers \r\n \r\n\r\ndef tickers_ibovespa(include_company_data = False):\r\n \r\n '''Downloads list of currently traded tickers on the Ibovespa, Brazil'''\r\n\r\n table = pd.read_html(\"https://pt.wikipedia.org/wiki/Lista_de_companhias_citadas_no_Ibovespa\")[0]\r\n table.columns = [\"Symbol\", \"Share\", \"Sector\", \"Type\", \"Site\"]\r\n \r\n if include_company_data:\r\n return table\r\n \r\n ibovespa_tickers = sorted(table.Symbol.tolist())\r\n \r\n return ibovespa_tickers \r\n\r\n\r\n\r\ndef tickers_nifty50(include_company_data = False, headers = {'User-agent': 'Mozilla/5.0'}):\r\n\r\n '''Downloads list of currently traded tickers on the NIFTY 50, India'''\r\n\r\n site = \"https://finance.yahoo.com/quote/%5ENSEI/components?p=%5ENSEI\"\r\n table = pd.read_html(requests.get(site, headers=headers).text)[0]\r\n \r\n if include_company_data:\r\n return table\r\n \r\n nifty50 = sorted(table['Symbol'].tolist())\r\n\r\n return nifty50\r\n\r\ndef tickers_niftybank():\r\n ''' Currently traded tickers on the NIFTY BANK, India '''\r\n \r\n niftybank = ['AXISBANK', 'KOTAKBANK', 'HDFCBANK', 'SBIN', 'BANKBARODA', 'INDUSINDBK', 'PNB', 'IDFCFIRSTB', 'ICICIBANK', 'RBLBANK', 'FEDERALBNK', 'BANDHANBNK']\r\n \r\n return niftybank\r\n\r\n\r\n\r\ndef tickers_ftse100(include_company_data = False):\r\n \r\n '''Downloads a list of the tickers traded on the FTSE 100 index'''\r\n \r\n table = pd.read_html(\"https://en.wikipedia.org/wiki/FTSE_100_Index\", attrs = {\"id\": \"constituents\"})[0]\r\n \r\n if include_company_data:\r\n return table\r\n \r\n return sorted(table.EPIC.tolist())\r\n \r\n\r\ndef tickers_ftse250(include_company_data = False):\r\n \r\n \r\n '''Downloads a list of the tickers traded on the FTSE 250 index'''\r\n \r\n table = pd.read_html(\"https://en.wikipedia.org/wiki/FTSE_250_Index\", attrs = {\"id\": \"constituents\"})[0]\r\n \r\n table.columns = [\"Company\", \"Ticker\"]\r\n \r\n if include_company_data:\r\n return table\r\n \r\n return sorted(table.Ticker.tolist())\r\n \r\n\r\n\r\n\r\ndef get_quote_table(ticker , dict_result = True, headers = {'User-agent': 'Mozilla/5.0'}): \r\n \r\n '''Scrapes data elements found on Yahoo Finance's quote page \r\n of input ticker\r\n \r\n @param: ticker\r\n @param: dict_result = True\r\n '''\r\n\r\n site = \"https://finance.yahoo.com/quote/\" + ticker + \"?p=\" + ticker\r\n \r\n tables = pd.read_html(requests.get(site, headers=headers).text)\r\n \r\n data = tables[0].append(tables[1])\r\n\r\n data.columns = [\"attribute\" , \"value\"]\r\n \r\n quote_price = pd.DataFrame([\"Quote Price\", get_live_price(ticker)]).transpose()\r\n quote_price.columns = data.columns.copy()\r\n \r\n data = data.append(quote_price)\r\n \r\n data = data.sort_values(\"attribute\")\r\n \r\n data = data.drop_duplicates().reset_index(drop = True)\r\n \r\n data[\"value\"] = data.value.map(force_float)\r\n\r\n if dict_result:\r\n \r\n result = {key : val for key,val in zip(data.attribute , data.value)}\r\n return result\r\n \r\n return data \r\n \r\n \r\ndef get_stats(ticker, headers = {'User-agent': 'Mozilla/5.0'}):\r\n \r\n '''Scrapes information from the statistics tab on Yahoo Finance \r\n for an input ticker \r\n \r\n @param: ticker\r\n '''\r\n\r\n stats_site = \"https://finance.yahoo.com/quote/\" + ticker + \\\r\n \"/key-statistics?p=\" + ticker\r\n \r\n\r\n tables = pd.read_html(requests.get(stats_site, headers=headers).text)\r\n \r\n tables = [table for table in tables[1:] if table.shape[1] == 2]\r\n \r\n table = tables[0]\r\n for elt in tables[1:]:\r\n table = table.append(elt)\r\n\r\n table.columns = [\"Attribute\" , \"Value\"]\r\n \r\n table = table.reset_index(drop = True)\r\n \r\n return table\r\n\r\n\r\ndef get_stats_valuation(ticker, headers = {'User-agent': 'Mozilla/5.0'}):\r\n \r\n '''Scrapes Valuation Measures table from the statistics tab on Yahoo Finance \r\n for an input ticker \r\n \r\n @param: ticker\r\n '''\r\n\r\n stats_site = \"https://finance.yahoo.com/quote/\" + ticker + \\\r\n \"/key-statistics?p=\" + ticker\r\n \r\n \r\n tables = pd.read_html(requests.get(stats_site, headers=headers).text)\r\n \r\n tables = [table for table in tables if \"Trailing P/E\" in table.iloc[:,0].tolist()]\r\n \r\n \r\n table = tables[0].reset_index(drop = True)\r\n \r\n return table\r\n\r\n\r\n\r\n\r\n\r\ndef _parse_json(url, headers = {'User-agent': 'Mozilla/5.0'}):\r\n html = requests.get(url=url, headers = headers).text\r\n\r\n json_str = html.split('root.App.main =')[1].split(\r\n '(this)')[0].split(';\\n}')[0].strip()\r\n \r\n try:\r\n data = json.loads(json_str)[\r\n 'context']['dispatcher']['stores']['QuoteSummaryStore']\r\n except:\r\n return '{}'\r\n else:\r\n # return data\r\n new_data = json.dumps(data).replace('{}', 'null')\r\n new_data = re.sub(r'\\{[\\'|\\\"]raw[\\'|\\\"]:(.*?),(.*?)\\}', r'\\1', new_data)\r\n\r\n json_info = json.loads(new_data)\r\n\r\n return json_info\r\n\r\n\r\ndef _parse_table(json_info):\r\n\r\n df = pd.DataFrame(json_info)\r\n \r\n if df.empty:\r\n return df\r\n \r\n del df[\"maxAge\"]\r\n\r\n df.set_index(\"endDate\", inplace=True)\r\n df.index = pd.to_datetime(df.index, unit=\"s\")\r\n \r\n df = df.transpose()\r\n df.index.name = \"Breakdown\"\r\n\r\n return df\r\n\r\n\r\ndef get_income_statement(ticker, yearly = True):\r\n \r\n '''Scrape income statement from Yahoo Finance for a given ticker\r\n \r\n @param: ticker\r\n '''\r\n \r\n income_site = \"https://finance.yahoo.com/quote/\" + ticker + \\\r\n \"/financials?p=\" + ticker\r\n\r\n json_info = _parse_json(income_site)\r\n \r\n if yearly:\r\n temp = json_info[\"incomeStatementHistory\"][\"incomeStatementHistory\"]\r\n else:\r\n temp = json_info[\"incomeStatementHistoryQuarterly\"][\"incomeStatementHistory\"]\r\n \r\n return _parse_table(temp) \r\n \r\n\r\ndef get_balance_sheet(ticker, yearly = True):\r\n \r\n '''Scrapes balance sheet from Yahoo Finance for an input ticker \r\n \r\n @param: ticker\r\n ''' \r\n \r\n balance_sheet_site = \"https://finance.yahoo.com/quote/\" + ticker + \\\r\n \"/balance-sheet?p=\" + ticker\r\n \r\n\r\n json_info = _parse_json(balance_sheet_site)\r\n \r\n try:\r\n if yearly:\r\n temp = json_info[\"balanceSheetHistory\"][\"balanceSheetStatements\"]\r\n else:\r\n temp = json_info[\"balanceSheetHistoryQuarterly\"][\"balanceSheetStatements\"]\r\n except:\r\n temp = []\r\n \r\n return _parse_table(temp) \r\n\r\n\r\ndef get_cash_flow(ticker, yearly = True):\r\n \r\n '''Scrapes the cash flow statement from Yahoo Finance for an input ticker \r\n \r\n @param: ticker\r\n '''\r\n \r\n cash_flow_site = \"https://finance.yahoo.com/quote/\" + \\\r\n ticker + \"/cash-flow?p=\" + ticker\r\n \r\n \r\n json_info = _parse_json(cash_flow_site)\r\n \r\n if yearly:\r\n temp = json_info[\"cashflowStatementHistory\"][\"cashflowStatements\"]\r\n else:\r\n temp = json_info[\"cashflowStatementHistoryQuarterly\"][\"cashflowStatements\"]\r\n \r\n return _parse_table(temp) \r\n\r\n\r\ndef get_financials(ticker, yearly = True, quarterly = True):\r\n\r\n '''Scrapes financials data from Yahoo Finance for an input ticker, including\r\n balance sheet, cash flow statement, and income statement. Returns dictionary\r\n of results.\r\n \r\n @param: ticker\r\n @param: yearly = True\r\n @param: quarterly = True\r\n '''\r\n\r\n if not yearly and not quarterly:\r\n raise AssertionError(\"yearly or quarterly must be True\")\r\n \r\n financials_site = \"https://finance.yahoo.com/quote/\" + ticker + \\\r\n \"/financials?p=\" + ticker\r\n \r\n json_info = _parse_json(financials_site)\r\n \r\n result = {}\r\n \r\n if yearly:\r\n\r\n temp = json_info[\"incomeStatementHistory\"][\"incomeStatementHistory\"]\r\n table = _parse_table(temp)\r\n result[\"yearly_income_statement\"] = table\r\n \r\n temp = json_info[\"balanceSheetHistory\"][\"balanceSheetStatements\"]\r\n table = _parse_table(temp)\r\n result[\"yearly_balance_sheet\"] = table\r\n \r\n temp = json_info[\"cashflowStatementHistory\"][\"cashflowStatements\"]\r\n table = _parse_table(temp)\r\n result[\"yearly_cash_flow\"] = table\r\n\r\n if quarterly:\r\n temp = json_info[\"incomeStatementHistoryQuarterly\"][\"incomeStatementHistory\"]\r\n table = _parse_table(temp)\r\n result[\"quarterly_income_statement\"] = table\r\n \r\n temp = json_info[\"balanceSheetHistoryQuarterly\"][\"balanceSheetStatements\"]\r\n table = _parse_table(temp)\r\n result[\"quarterly_balance_sheet\"] = table\r\n \r\n temp = json_info[\"cashflowStatementHistoryQuarterly\"][\"cashflowStatements\"]\r\n table = _parse_table(temp)\r\n result[\"quarterly_cash_flow\"] = table\r\n\r\n \r\n return result\r\n\r\n\r\ndef get_holders(ticker, headers = {'User-agent': 'Mozilla/5.0'}):\r\n \r\n '''Scrapes the Holders page from Yahoo Finance for an input ticker \r\n \r\n @param: ticker\r\n ''' \r\n \r\n holders_site = \"https://finance.yahoo.com/quote/\" + \\\r\n ticker + \"/holders?p=\" + ticker\r\n \r\n \r\n tables = pd.read_html(requests.get(holders_site, headers=headers).text)\r\n \r\n \r\n table_names = [\"Major Holders\" , \"Direct Holders (Forms 3 and 4)\" ,\r\n \"Top Institutional Holders\" , \"Top Mutual Fund Holders\"]\r\n \r\n \r\n table_mapper = {key : val for key,val in zip(table_names , tables)}\r\n \r\n \r\n return table_mapper \r\n\r\ndef get_analysts_info(ticker, headers = {'User-agent': 'Mozilla/5.0'}):\r\n \r\n '''Scrapes the Analysts page from Yahoo Finance for an input ticker \r\n \r\n @param: ticker\r\n ''' \r\n \r\n \r\n analysts_site = \"https://finance.yahoo.com/quote/\" + ticker + \\\r\n \"/analysts?p=\" + ticker\r\n \r\n tables = pd.read_html(requests.get(analysts_site, headers=headers).text)\r\n \r\n table_names = [table.columns[0] for table in tables]\r\n\r\n table_mapper = {key : val for key , val in zip(table_names , tables)}\r\n \r\n\r\n return table_mapper\r\n \r\n\r\ndef get_live_price(ticker):\r\n \r\n '''Gets the live price of input ticker\r\n \r\n @param: ticker\r\n ''' \r\n \r\n df = get_data(ticker, end_date = pd.Timestamp.today() + pd.DateOffset(10))\r\n \r\n \r\n return df.close[-1]\r\n \r\n \r\ndef _raw_get_daily_info(site):\r\n \r\n session = HTMLSession()\r\n \r\n resp = session.get(site)\r\n \r\n tables = pd.read_html(resp.html.raw_html) \r\n \r\n df = tables[0].copy()\r\n \r\n df.columns = tables[0].columns\r\n \r\n del df[\"52 Week Range\"]\r\n \r\n df[\"% Change\"] = df[\"% Change\"].map(lambda x: float(x.strip(\"%+\").replace(\",\", \"\")))\r\n \r\n\r\n fields_to_change = [x for x in df.columns.tolist() if \"Vol\" in x \\\r\n or x == \"Market Cap\"]\r\n \r\n for field in fields_to_change:\r\n \r\n if type(df[field][0]) == str:\r\n df[field] = df[field].map(_convert_to_numeric)\r\n \r\n session.close()\r\n \r\n return df\r\n \r\n\r\ndef get_day_most_active(count: int = 100):\r\n\r\n return _raw_get_daily_info(f\"https://finance.yahoo.com/most-active?offset=0&count={count}\")\r\n\r\n\r\ndef get_day_gainers(count: int = 100):\r\n\r\n return _raw_get_daily_info(f\"https://finance.yahoo.com/gainers?offset=0&count={count}\")\r\n\r\n\r\ndef get_day_losers(count: int = 100):\r\n\r\n return _raw_get_daily_info(f\"https://finance.yahoo.com/losers?offset=0&count={count}\")\r\n\r\n\r\ndef get_top_crypto():\r\n \r\n '''Gets the top 100 Cryptocurrencies by Market Cap''' \r\n\r\n session = HTMLSession()\r\n \r\n resp = session.get(\"https://finance.yahoo.com/cryptocurrencies?offset=0&count=100\")\r\n \r\n tables = pd.read_html(resp.html.raw_html) \r\n \r\n df = tables[0].copy()\r\n\r\n \r\n df[\"% Change\"] = df[\"% Change\"].map(lambda x: float(str(x).strip(\"%\").\\\r\n strip(\"+\").\\\r\n replace(\",\", \"\")))\r\n del df[\"52 Week Range\"]\r\n del df[\"Day Chart\"]\r\n \r\n fields_to_change = [x for x in df.columns.tolist() if \"Volume\" in x \\\r\n or x == \"Market Cap\" or x == \"Circulating Supply\"]\r\n \r\n for field in fields_to_change:\r\n \r\n if type(df[field][0]) == str:\r\n df[field] = df[field].map(lambda x: _convert_to_numeric(str(x)))\r\n \r\n \r\n session.close() \r\n \r\n return df\r\n \r\n \r\ndef get_dividends(ticker, start_date = None, end_date = None, index_as_date = True, \r\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\r\n):\r\n '''Downloads historical dividend data into a pandas data frame.\r\n \r\n @param: ticker\r\n @param: start_date = None\r\n @param: end_date = None\r\n @param: index_as_date = True\r\n '''\r\n \r\n # build and connect to URL\r\n site, params = build_url(ticker, start_date, end_date, \"1d\")\r\n resp = requests.get(site, params = params, headers = headers)\r\n \r\n \r\n if not resp.ok:\r\n return pd.DataFrame()\r\n \r\n \r\n # get JSON response\r\n data = resp.json()\r\n \r\n # check if there is data available for dividends\r\n if \"events\" not in data[\"chart\"][\"result\"][0] or \"dividends\" not in data[\"chart\"][\"result\"][0]['events']:\r\n return pd.DataFrame()\r\n \r\n # get the dividend data\r\n frame = pd.DataFrame(data[\"chart\"][\"result\"][0]['events']['dividends'])\r\n \r\n frame = frame.transpose()\r\n \r\n frame.index = pd.to_datetime(frame.index, unit = \"s\")\r\n frame.index = frame.index.map(lambda dt: dt.floor(\"d\"))\r\n \r\n # sort in chronological order\r\n frame = frame.sort_index()\r\n \r\n frame['ticker'] = ticker.upper()\r\n \r\n # remove old date column\r\n frame = frame.drop(columns='date')\r\n \r\n frame = frame.rename({'amount': 'dividend'}, axis = 'columns')\r\n \r\n if not index_as_date: \r\n frame = frame.reset_index()\r\n frame.rename(columns = {\"index\": \"date\"}, inplace = True)\r\n \r\n return frame\r\n\r\n\r\n\r\ndef get_splits(ticker, start_date = None, end_date = None, index_as_date = True,\r\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\r\n):\r\n '''Downloads historical stock split data into a pandas data frame.\r\n \r\n @param: ticker\r\n @param: start_date = None\r\n @param: end_date = None\r\n @param: index_as_date = True\r\n '''\r\n \r\n # build and connect to URL\r\n site, params = build_url(ticker, start_date, end_date, \"1d\")\r\n resp = requests.get(site, params = params, headers = headers)\r\n \r\n \r\n if not resp.ok:\r\n raise AssertionError(resp.json())\r\n \r\n \r\n # get JSON response\r\n data = resp.json()\r\n \r\n # check if there is data available for splits\r\n if \"splits\" not in data[\"chart\"][\"result\"][0]['events']:\r\n raise AssertionError(\"There is no data available on stock splits, or none have occured\")\r\n \r\n # get the split data\r\n frame = pd.DataFrame(data[\"chart\"][\"result\"][0]['events']['splits'])\r\n \r\n frame = frame.transpose()\r\n \r\n frame.index = pd.to_datetime(frame.index, unit = \"s\")\r\n frame.index = frame.index.map(lambda dt: dt.floor(\"d\"))\r\n \r\n # sort in to chronological order\r\n frame = frame.sort_index()\r\n \r\n frame['ticker'] = ticker.upper()\r\n \r\n # remove unnecessary columns\r\n frame = frame.drop(columns=['date', 'denominator', 'numerator'])\r\n \r\n if not index_as_date: \r\n frame = frame.reset_index()\r\n frame.rename(columns = {\"index\": \"date\"}, inplace = True)\r\n \r\n return frame\r\n \r\n \r\n\r\n\r\ndef get_earnings(ticker):\r\n \r\n '''Scrapes earnings data from Yahoo Finance for an input ticker \r\n \r\n @param: ticker\r\n '''\r\n\r\n result = {\r\n \"quarterly_results\": pd.DataFrame(),\r\n \"yearly_revenue_earnings\": pd.DataFrame(),\r\n \"quarterly_revenue_earnings\": pd.DataFrame()\r\n }\r\n\r\n financials_site = \"https://finance.yahoo.com/quote/\" + ticker + \\\r\n \"/financials?p=\" + ticker\r\n\r\n json_info = _parse_json(financials_site)\r\n\r\n if \"earnings\" not in json_info:\r\n return result\r\n\r\n temp = json_info[\"earnings\"]\r\n\r\n if temp == None:\r\n return result\r\n \r\n result[\"quarterly_results\"] = pd.DataFrame.from_dict(temp[\"earningsChart\"][\"quarterly\"])\r\n \r\n result[\"yearly_revenue_earnings\"] = pd.DataFrame.from_dict(temp[\"financialsChart\"][\"yearly\"])\r\n \r\n result[\"quarterly_revenue_earnings\"] = pd.DataFrame.from_dict(temp[\"financialsChart\"][\"quarterly\"])\r\n \r\n return result\r\n\r\n\r\n\r\n### Earnings functions\r\ndef _parse_earnings_json(url, headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\r\n):\r\n resp = requests.get(url, headers = headers)\r\n \r\n content = resp.content.decode(encoding='utf-8', errors='strict')\r\n \r\n page_data = [row for row in content.split(\r\n '\\n') if row.startswith('root.App.main = ')][0][:-1]\r\n \r\n page_data = page_data.split('root.App.main = ', 1)[1]\r\n \r\n return json.loads(page_data)\r\n\r\ndef get_next_earnings_date(ticker):\r\n \r\n base_earnings_url = 'https://finance.yahoo.com/quote'\r\n new_url = base_earnings_url + \"/\" + ticker\r\n\r\n parsed_result = _parse_earnings_json(new_url)\r\n \r\n temp = parsed_result['context']['dispatcher']['stores']['QuoteSummaryStore']['calendarEvents']['earnings']['earningsDate'][0]['raw']\r\n\r\n return datetime.datetime.fromtimestamp(temp)\r\n\r\n\r\ndef get_earnings_history(ticker):\r\n \r\n '''Inputs: @ticker\r\n Returns the earnings calendar history of the input ticker with \r\n EPS actual vs. expected data.'''\r\n\r\n url = 'https://finance.yahoo.com/calendar/earnings?symbol=' + ticker\r\n \r\n result = _parse_earnings_json(url)\r\n \r\n return result[\"context\"][\"dispatcher\"][\"stores\"][\"ScreenerResultsStore\"][\"results\"][\"rows\"]\r\n\r\n\r\n\r\ndef get_earnings_for_date(date, offset = 0, count = 1):\r\n\r\n '''Inputs: @date\r\n Returns a dictionary of stock tickers with earnings expected on the\r\n input date. The dictionary contains the expected EPS values for each\r\n stock if available.'''\r\n \r\n base_earnings_url = 'https://finance.yahoo.com/calendar/earnings'\r\n \r\n if offset >= count:\r\n return []\r\n \r\n temp = pd.Timestamp(date)\r\n date = temp.strftime(\"%Y-%m-%d\")\r\n\r\n dated_url = '{0}?day={1}&offset={2}&size={3}'.format(\r\n base_earnings_url, date, offset, 100)\r\n \r\n result = _parse_earnings_json(dated_url)\r\n \r\n stores = result['context']['dispatcher']['stores']\r\n \r\n earnings_count = stores['ScreenerCriteriaStore']['meta']['total']\r\n\r\n new_offset = offset + 100\r\n \r\n more_earnings = get_earnings_for_date(date, new_offset, earnings_count)\r\n \r\n current_earnings = stores['ScreenerResultsStore']['results']['rows']\r\n\r\n total_earnings = current_earnings + more_earnings\r\n\r\n return total_earnings\r\n\r\n\r\ndef get_earnings_in_date_range(start_date, end_date):\r\n\r\n '''Inputs: @start_date\r\n @end_date\r\n \r\n Returns the stock tickers with expected EPS data for all dates in the\r\n input range (inclusive of the start_date and end_date.'''\r\n \r\n earnings_data = []\r\n\r\n days_diff = pd.Timestamp(end_date) - pd.Timestamp(start_date)\r\n days_diff = days_diff.days\r\n\r\n \r\n current_date = pd.Timestamp(start_date)\r\n \r\n dates = [current_date + datetime.timedelta(diff) for diff in range(days_diff + 1)]\r\n dates = [d.strftime(\"%Y-%m-%d\") for d in dates]\r\n \r\n i = 0\r\n while i < len(dates):\r\n try:\r\n earnings_data += get_earnings_for_date(dates[i])\r\n except Exception:\r\n pass\r\n \r\n i += 1\r\n \r\n return earnings_data\r\n\r\n\r\ndef get_currencies(headers = {'User-agent': 'Mozilla/5.0'}):\r\n \r\n '''Returns the currencies table from Yahoo Finance'''\r\n \r\n site = \"https://finance.yahoo.com/currencies\"\r\n tables = pd.read_html(requests.get(site, headers=headers).text)\r\n \r\n result = tables[0]\r\n \r\n return result\r\n\r\n\r\ndef get_futures(headers = {'User-agent': 'Mozilla/5.0'}):\r\n \r\n '''Returns the futures table from Yahoo Finance'''\r\n \r\n site = \"https://finance.yahoo.com/commodities\"\r\n tables = pd.read_html(requests.get(site, headers=headers).text)\r\n \r\n result = tables[0]\r\n \r\n return result\r\n\r\n\r\ndef get_undervalued_large_caps(headers = {'User-agent': 'Mozilla/5.0'}):\r\n \r\n '''Returns the undervalued large caps table from Yahoo Finance'''\r\n \r\n site = \"https://finance.yahoo.com/screener/predefined/undervalued_large_caps?offset=0&count=100\"\r\n \r\n tables = pd.read_html(requests.get(site, headers=headers).text)\r\n \r\n result = tables[0]\r\n \r\n return result\r\n\r\n\r\ndef get_quote_data(ticker, headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\r\n):\r\n \r\n '''Inputs: @ticker\r\n \r\n Returns a dictionary containing over 70 elements corresponding to the \r\n input ticker, including company name, book value, moving average data,\r\n pre-market / post-market price (when applicable), and more.'''\r\n \r\n site = \"https://query1.finance.yahoo.com/v7/finance/quote?symbols=\" + ticker\r\n \r\n resp = requests.get(site, headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\r\n)\r\n \r\n if not resp.ok:\r\n raise AssertionError(\"\"\"Invalid response from server. Check if ticker is\r\n valid.\"\"\")\r\n \r\n \r\n json_result = resp.json()\r\n info = json_result[\"quoteResponse\"][\"result\"]\r\n \r\n return info[0]\r\n \r\n\r\ndef get_market_status():\r\n \r\n '''Returns the current state of the market - PRE, POST, OPEN, or CLOSED'''\r\n \r\n quote_data = get_quote_data(\"^dji\")\r\n\r\n return quote_data[\"marketState\"]\r\n\r\ndef get_premarket_price(ticker):\r\n\r\n '''Inputs: @ticker\r\n \r\n Returns the current pre-market price of the input ticker\r\n (returns value if pre-market price is available.'''\r\n \r\n quote_data = get_quote_data(ticker)\r\n \r\n if \"preMarketPrice\" in quote_data:\r\n return quote_data[\"preMarketPrice\"]\r\n \r\n raise AssertionError(\"Premarket price not currently available.\")\r\n\r\ndef get_postmarket_price(ticker):\r\n\r\n '''Inputs: @ticker\r\n \r\n Returns the current post-market price of the input ticker\r\n (returns value if pre-market price is available.'''\r\n \r\n quote_data = get_quote_data(ticker)\r\n \r\n if \"postMarketPrice\" in quote_data:\r\n return quote_data[\"postMarketPrice\"]\r\n \r\n raise AssertionError(\"Postmarket price not currently available.\")\r\n \r\n\r\n# Company Information Functions\r\ndef get_company_info(ticker):\r\n '''Scrape the company information for a ticker\r\n\r\n @param: ticker\r\n '''\r\n site = f\"https://finance.yahoo.com/quote/{ticker}/profile?p={ticker}\"\r\n json_info = _parse_json(site)\r\n json_info = json_info[\"assetProfile\"]\r\n info_frame = pd.DataFrame.from_dict(json_info,\r\n orient=\"index\",\r\n columns=[\"Value\"])\r\n info_frame = info_frame.drop(\"companyOfficers\", axis=\"index\")\r\n info_frame.index.name = \"Breakdown\"\r\n return info_frame\r\n\r\n\r\ndef get_company_officers(ticker):\r\n '''Scrape the company information and return a table of the officers\r\n\r\n @param: ticker\r\n '''\r\n site = f\"https://finance.yahoo.com/quote/{ticker}/profile?p={ticker}\"\r\n json_info = _parse_json(site)\r\n json_info = json_info[\"assetProfile\"][\"companyOfficers\"]\r\n info_frame = pd.DataFrame.from_dict(json_info)\r\n info_frame = info_frame.set_index(\"name\")\r\n return info_frame\r\n"
] |
[
[
"pandas.to_datetime",
"pandas.read_csv",
"pandas.DateOffset",
"pandas.DataFrame",
"pandas.read_html",
"pandas.DataFrame.from_dict",
"pandas.Timestamp",
"pandas.Timestamp.today"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jvpoulos/NeurIPS2019-traffic4cast
|
[
"707ab2d2b3fcad8df19ab6e5443f0280c00a02c5"
] |
[
"utils/pred.py"
] |
[
"import numpy as np\nimport os, csv, re, datetime\nimport sys, getopt\nimport h5py\nfrom h5shape import *\nfrom keras import models\nfrom keras.models import load_model\n\n#prediction times in test sets)\nutcPlus2 = [30, 69, 126, 186, 234]\nutcPlus3 = [57, 114, 174, 222, 258]\n\ndef load_test_data(file_path, indices):\n \"\"\"Load data for one test day, return as numpy array with normalized samples.\n \n Args.:\n file_path (str): file path of h5 file for one day\n indices (list): list with prediction times (as list indices in the interval [0, 288])\n \n Returns: numpy array of shape (5, 3, 3, 495, 436)\n \"\"\"\n #load h5 file\n fr = h5py.File(file_path, 'r')\n a_group_key = list(fr.keys())[0]\n data = list(fr[a_group_key])\n \n #identify test cases and split in samples of each length 3 time bins\n data = [data[y - 3: y] for y in indices]\n data = np.stack(data, axis=0)\n \n #transpose to (samples, timesteps, channels, rows, columns)\n data = np.transpose(data, (0, 1, 4, 2, 3))\n \n #rescale and return data\n data = data.astype(np.float32)\n np.random.shuffle(data)\n data /= 255.\n return data\n\ndef list_filenames(directory):\n filenames = os.listdir(directory)\n return filenames\n\ndef return_date(file_name):\n \"\"\"Auxilliary function which returns datetime object from Traffic4Cast filename.\n \n Args.:\n file_name (str): file name, e.g., '20180516_100m_bins.h5'\n \n Returns: date string, e.g., '2018-05-16'\n \"\"\"\n \n match = re.search(r'\\d{4}\\d{2}\\d{2}', file_name)\n date = datetime.datetime.strptime(match.group(), '%Y%m%d').date()\n return date\n\ndef write_data(data, filename):\n \"\"\"\n write data in gzipped h5 format.\n \"\"\"\n f = h5py.File(filename, 'w', libver='latest')\n dset = f.create_dataset('array', shape=(data.shape), data = data, compression='gzip', compression_opts=9)\n f.close()\n\ndef write_output_files(model_dir, data_dir, output_dir, city):\n \"\"\"\n write outdata into each submission folder structure at out_path, cloning\n filenames in corresponding folder structure at input_path.\n \"\"\"\n \n test_indices = utcPlus3\n if city == \"Berlin\":\n test_indices = utcPlus2\n\n model_path = sys.argv[-1]\n model = load_model(model_path)\n\n # set relevant list\n test_data_dir = os.path.join(data_dir, city, city+\"_test/\")\n file_names = list_filenames(test_data_dir)\n for f in file_names:\n # load data\n x = load_test_data(test_data_dir + f, test_indices)\n out = model.predict(x)\n out *= 255\n out = out.astype(int)\n neg_indices = out < 0\n out[neg_indices] = 0\n out = np.transpose(out, (0, 1, 3, 4, 2))\n \n # output result\n outfile = os.path.join(output_dir, city, city+'_test',f)\n write_data(out, outfile)\n print(\"just wrote file {}\".format(outfile))\n\n \n# run prediction\n\nif __name__ == '__main__':\n\n # gather command line arguments.\n data_dir = ''\n model_dir = ''\n output_dir = ''\n city = ''\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"hd:m:o:c:\", [\"data_dir\",\"model_dir\",\"output_dir\",\"city\"])\n except getopt.GetoptError:\n print('usage: pred.py -d <data dir> -m <model dir> -o <output dir> -c <city>')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print('usage: pred.py -d <data dir> -m <model dir> -o <output dir> -c <city>')\n elif opt in (\"-d\",\"--data_dir\"):\n data_dir = arg\n elif opt in (\"-m\",\"--model_dir\"):\n model_dir = arg\n elif opt in (\"-o\",\"--output\"):\n output_dir = arg\n elif opt in (\"-c\",\"--city\"):\n city = arg\n if city in (\"Berlin\",\"Istanbul\",\"Moscow\"):\n write_output_files(model_dir, data_dir, output_dir, city)\n else:\n print('invalid city provided')\n sys.exit(2)\n"
] |
[
[
"numpy.random.shuffle",
"numpy.stack",
"numpy.transpose"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
criddle858/PyLTEs
|
[
"ef16e595339542b8b0d774ed1699fde65723ac74"
] |
[
"pyltes/powerConfigurator.py"
] |
[
"__author__ = 'mslabicki'\r\n\r\nimport pygmo as pg\r\n#\r\nfrom pyltes.powerOptimizationProblemsDef import maximalThroughputProblemRR\r\nfrom pyltes.powerOptimizationProblemsDef import local_maximalThroughputProblemRR\r\nfrom pyltes.powerOptimizationProblemsDef import maximalMedianThrProblemRR\r\nfrom pyltes.powerOptimizationProblemsDef import local_maximalMedianThrProblemRR\r\nfrom pyltes.powerOptimizationProblemsDef import minInterQuartileRangeroblemRR\r\nfrom pyltes.powerOptimizationProblemsDef import local_minInterQuartileRangeroblemRR\r\n\r\nimport copy\r\nimport math\r\nimport numpy as np\r\n\r\nclass pygmoPowerConfigurator:\r\n def __init__(self,parent):\r\n self.parent = parent\r\n\r\n def findPowersRR(self, objectiveFunction=\"averageThr\", sgaGenerations = 100, numberOfThreads = 11, numOfIndividuals = 10, evolveTimes = 10, method=\"global\", x_arg=None, y_arg=None, expectedSignalLoss_arg=None):\r\n if method == \"local\":\r\n if x_arg == None:\r\n x = self.parent.constraintAreaMaxX/2\r\n else:\r\n x = x_arg\r\n if y_arg == None:\r\n y = self.parent.constraintAreaMaxY/2\r\n else:\r\n y = y_arg\r\n if expectedSignalLoss_arg == None:\r\n maxDistance = min(self.parent.constraintAreaMaxX/2, self.parent.constraintAreaMaxY/2)\r\n else:\r\n maxDistance = returnDistanceFromSNR(expectedSignalLoss_arg)\r\n localBsVector = []\r\n for bs in self.parent.bs:\r\n if math.sqrt((bs.x - x)**2 + (bs.y - y)**2) < maxDistance:\r\n row = []\r\n row.append(int(bs.ID))\r\n row.append(math.sqrt((bs.x - x)**2 + (bs.y - y)**2))\r\n localBsVector.append(row)\r\n localBsVector = np.asarray(localBsVector)\r\n if objectiveFunction == \"averageThr\":\r\n if method == \"local\":\r\n localListBS = []\r\n for i in range(len(localBsVector)):\r\n localListBS.append(localBsVector[i,0])\r\n prob = pg.problem(local_maximalThroughputProblemRR(dim=len(localBsVector), networkInstance=self.parent, lowerTxLimit=self.parent.minTxPower, upperTxLimit=self.parent.maxTxPower, localListBS=localListBS))\r\n\r\n if method == \"global\":\r\n prob = pg.problem(maximalThroughputProblemRR(dim=len(self.parent.bs), networkInstance=self.parent, lowerTxLimit=self.parent.minTxPower, upperTxLimit=self.parent.maxTxPower))\r\n\r\n if objectiveFunction == \"medianThr\":\r\n if method == \"local\":\r\n localListBS = []\r\n for i in range(len(localBsVector)):\r\n localListBS.append(localBsVector[i,0])\r\n prob = pg.problem(local_maximalMedianThrProblemRR(dim=len(localBsVector), networkInstance=self.parent, lowerTxLimit=self.parent.minTxPower, upperTxLimit=self.parent.maxTxPower, localListBS=localListBS))\r\n\r\n if method == \"global\":\r\n prob = pg.problem(maximalMedianThrProblemRR(dim=len(self.parent.bs), networkInstance=self.parent, lowerTxLimit=self.parent.minTxPower, upperTxLimit=self.parent.maxTxPower))\r\n\r\n if objectiveFunction == \"minIQRthr\":\r\n if method == \"local\":\r\n localListBS = []\r\n for i in range(len(localBsVector)):\r\n localListBS.append(localBsVector[i,0])\r\n prob = pg.problem(local_minInterQuartileRangeroblemRR(dim=len(localBsVector), networkInstance=self.parent, lowerTxLimit=self.parent.minTxPower, upperTxLimit=self.parent.maxTxPower, localListBS=localListBS))\r\n\r\n if method == \"global\":\r\n prob = pg.problem(minInterQuartileRangeroblemRR(dim=len(self.parent.bs), networkInstance=self.parent, lowerTxLimit=self.parent.minTxPower, upperTxLimit=self.parent.maxTxPower))\r\n\r\n\r\n prob.siec = copy.deepcopy(self.parent)\r\n # algo = algorithm.sga(gen=sgaGenerations)\r\n algo = pg.algorithm(pg.sga(gen=sgaGenerations))\r\n # archi = archipelago(algo, prob, numberOfThreads, numOfIndividuals, topology = topology.barabasi_albert())\r\n # archi.evolve(evolveTimes)\r\n # archi.join()\r\n population = pg.population(prob, numOfIndividuals)\r\n population = algo.evolve(population)\r\n\r\n theBestCostF = 0\r\n islandNumber = -1\r\n islandCounter = 0\r\n # for island in archi:\r\n # if theBestCostF > island.population.champion.f[0]:\r\n # theBestCostF = island.population.champion.f[0]\r\n # islandNumber = islandCounter\r\n # islandCounter = islandCounter + 1\r\n\r\n if method == \"global\":\r\n for i in range(len(self.parent.bs)):\r\n self.parent.bs[i].outsidePower = population.champion_x[i]\r\n if method == \"local\":\r\n for i in range(len(localListBS)):\r\n # self.parent.bs[int(prob.bsList[i])].outsidePower = archi[islandNumber].population.champion.x[i]\r\n self.parent.bs[int(localListBS[i])].outsidePower = population.champion_x[i]\r\n return len(localBsVector)\r\n\r\ndef returnDistanceFromSNR(expectedSignalLoss):\r\n lambda_val = 0.142758313333\r\n a = 4.0\r\n b = 0.0065\r\n c = 17.1\r\n d = 10.8\r\n s = 15.8\r\n\r\n ht = 40\r\n hr = 1.5\r\n f = 2.1\r\n gamma = a - b*ht + c/ht\r\n Xf = 6 * math.log10( f/2 )\r\n Xh = -d * math.log10( hr/2 )\r\n\r\n R0 = 100.0\r\n R0p = R0 * pow(10.0,-( (Xf+Xh) / (10*gamma) ))\r\n\r\n bandwidth=20\r\n k = 1.3806488 * math.pow(10, -23)\r\n T = 293.0\r\n BW = bandwidth * 1000 * 1000\r\n N = 10*math.log10(k*T) + 10*math.log10(BW)\r\n\r\n alpha = 20 * math.log10( (4*math.pi*R0p) / lambda_val )\r\n R = R0 * math.pow(10, (expectedSignalLoss - alpha-Xf-Xh-s - N)/(10*gamma))\r\n\r\n return R\r\n"
] |
[
[
"numpy.asarray"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
viztopia/animegan2-pytorch
|
[
"cef7f42fa429cfc902c3b419d343389e690943f5"
] |
[
"model.py"
] |
[
"import torch\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass ConvNormLReLU(nn.Sequential):\n def __init__(self, in_ch, out_ch, kernel_size=3, stride=1, padding=1, pad_mode=\"reflect\", groups=1, bias=False):\n \n pad_layer = {\n \"zero\": nn.ZeroPad2d,\n \"same\": nn.ReplicationPad2d,\n \"reflect\": nn.ReflectionPad2d,\n }\n if pad_mode not in pad_layer:\n raise NotImplementedError\n \n super(ConvNormLReLU, self).__init__(\n pad_layer[pad_mode](padding),\n nn.Conv2d(in_ch, out_ch, kernel_size=kernel_size, stride=stride, padding=0, groups=groups, bias=bias),\n #nn.GroupNorm(num_groups=1, num_channels=out_ch, affine=True),\n nn.InstanceNorm2d(num_features=out_ch, affine=True),\n nn.LeakyReLU(0.2, inplace=True)\n )\n\n\nclass InvertedResBlock(nn.Module):\n def __init__(self, in_ch, out_ch, expansion_ratio=2):\n super(InvertedResBlock, self).__init__()\n\n self.use_res_connect = in_ch == out_ch\n bottleneck = int(round(in_ch*expansion_ratio))\n layers = []\n if expansion_ratio != 1:\n layers.append(ConvNormLReLU(in_ch, bottleneck, kernel_size=1, padding=0))\n \n # dw\n layers.append(ConvNormLReLU(bottleneck, bottleneck, groups=bottleneck, bias=True))\n # pw\n layers.append(nn.Conv2d(bottleneck, out_ch, kernel_size=1, padding=0, bias=False))\n # layers.append(nn.GroupNorm(num_groups=1, num_channels=out_ch, affine=True))\n layers.append(nn.InstanceNorm2d(num_features=out_ch, affine=True))\n\n self.layers = nn.Sequential(*layers)\n \n def forward(self, input):\n out = self.layers(input)\n if self.use_res_connect:\n out = input + out\n return out\n\n \nclass Generator(nn.Module):\n def __init__(self, ):\n super().__init__()\n \n self.block_a = nn.Sequential(\n ConvNormLReLU(3, 32, kernel_size=7, padding=3),\n ConvNormLReLU(32, 64, stride=2, padding=(0,1,0,1)),\n ConvNormLReLU(64, 64)\n )\n \n self.block_b = nn.Sequential(\n ConvNormLReLU(64, 128, stride=2, padding=(0,1,0,1)), \n ConvNormLReLU(128, 128)\n )\n \n self.block_c = nn.Sequential(\n ConvNormLReLU(128, 128),\n InvertedResBlock(128, 256, 2),\n InvertedResBlock(256, 256, 2),\n InvertedResBlock(256, 256, 2),\n InvertedResBlock(256, 256, 2),\n ConvNormLReLU(256, 128),\n ) \n \n self.block_d = nn.Sequential(\n ConvNormLReLU(128, 128),\n ConvNormLReLU(128, 128)\n )\n\n self.block_e = nn.Sequential(\n ConvNormLReLU(128, 64),\n ConvNormLReLU(64, 64),\n ConvNormLReLU(64, 32, kernel_size=7, padding=3)\n )\n\n self.out_layer = nn.Sequential(\n nn.Conv2d(32, 3, kernel_size=1, stride=1, padding=0, bias=False),\n nn.Tanh()\n )\n \n def forward(self, input, align_corners=False):\n out = self.block_a(input)\n half_size = out.size()[-2:]\n out = self.block_b(out)\n out = self.block_c(out)\n \n if align_corners:\n out = F.interpolate(out, half_size, mode=\"bilinear\", align_corners=True)\n else:\n out = F.interpolate(out, scale_factor=2, mode='nearest')\n out = self.block_d(out)\n\n if align_corners:\n out = F.interpolate(out, input.size()[-2:], mode=\"bilinear\", align_corners=True)\n else:\n out = F.interpolate(out, scale_factor=2, mode='nearest')\n out = self.block_e(out)\n\n out = self.out_layer(out)\n return out\n \n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.nn.Tanh",
"torch.nn.InstanceNorm2d",
"torch.nn.LeakyReLU",
"torch.nn.functional.interpolate"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lsiemens/QBox
|
[
"ef43c9bbc5f8437fb4d44fbf0e58e29a8e0b1b39"
] |
[
"ProofOfConcept/PythonVSFortran/PQBoxTest.py"
] |
[
"import numpy\n\nres, iterations = 100, 10000\ndt = 0.1\nV = 0*numpy.empty((res, res))\nphi = (1.0 + 1.0j) + 0*V\na = (0.0 + 0.0j) + 0*V\ngrad = (0.0 + 0.0j) + 0*V\n\nphi[0, :] = (0.0 + 0.0j)\nphi[res - 1, :] = (0.0 + 0.0j)\nphi[:, 0] = (0.0 + 0.0j)\nphi[:, res - 1] = (0.0 + 0.0j)\n\nphi = phi/numpy.sqrt(numpy.sum(numpy.conj(phi)*phi))\n\nfor i in range(iterations):\n phi = phi - numpy.sum(numpy.conj(a)*phi)*a\n grad[1:-1, 1:-1] = phi[2:, 1:-1] + phi[:-2, 1:-1] + phi[1:-1, 2:] + phi[1:-1, :-2] - 4*phi[1:-1, 1:-1]\n phi = phi + dt*(grad - V*phi)\n phi = phi/numpy.sqrt(numpy.sum(numpy.conj(phi)*phi))\n"
] |
[
[
"numpy.conj",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
louis-li/PlantDiseaseDetection
|
[
"14db4089a0f4f8fed00500d4c574fd3bcfcd29ad"
] |
[
"grad_cam.py"
] |
[
"## Based on https://keras.io/examples/vision/grad_cam/\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# Display\nfrom IPython.display import Image\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\ndef get_img_array(img_path, size):\n # `img` is a PIL image of size 299x299\n img = keras.preprocessing.image.load_img(img_path, target_size=size)\n # `array` is a float32 Numpy array of shape (299, 299, 3)\n array = keras.preprocessing.image.img_to_array(img)\n # We add a dimension to transform our array into a \"batch\"\n # of size (1, 299, 299, 3)\n array = np.expand_dims(array, axis=0)\n return array\n\n\ndef make_gradcam_heatmap(\n img_array, model, last_conv_layer_name, classifier_layer_names\n):\n # First, we create a model that maps the input image to the activations\n # of the last conv layer\n last_conv_layer = model.get_layer(last_conv_layer_name)\n last_conv_layer_model = keras.Model(model.inputs, last_conv_layer.output)\n\n # Second, we create a model that maps the activations of the last conv\n # layer to the final class predictions\n classifier_input = keras.Input(shape=last_conv_layer.output.shape[1:])\n x = classifier_input\n for layer_name in classifier_layer_names:\n x = model.get_layer(layer_name)(x)\n classifier_model = keras.Model(classifier_input, x)\n\n # Then, we compute the gradient of the top predicted class for our input image\n # with respect to the activations of the last conv layer\n with tf.GradientTape() as tape:\n # Compute activations of the last conv layer and make the tape watch it\n last_conv_layer_output = last_conv_layer_model(img_array)\n tape.watch(last_conv_layer_output)\n # Compute class predictions\n preds = classifier_model(last_conv_layer_output)\n top_pred_index = tf.argmax(preds[0])\n top_class_channel = preds[:, top_pred_index]\n\n # This is the gradient of the top predicted class with regard to\n # the output feature map of the last conv layer\n grads = tape.gradient(top_class_channel, last_conv_layer_output)\n\n # This is a vector where each entry is the mean intensity of the gradient\n # over a specific feature map channel\n pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))\n\n # We multiply each channel in the feature map array\n # by \"how important this channel is\" with regard to the top predicted class\n last_conv_layer_output = last_conv_layer_output.numpy()[0]\n pooled_grads = pooled_grads.numpy()\n for i in range(pooled_grads.shape[-1]):\n last_conv_layer_output[:, :, i] *= pooled_grads[i]\n\n # The channel-wise mean of the resulting feature map\n # is our heatmap of class activation\n heatmap = np.mean(last_conv_layer_output, axis=-1)\n\n # For visualization purpose, we will also normalize the heatmap between 0 & 1\n heatmap = np.maximum(heatmap, 0) / np.max(heatmap)\n return heatmap\n\ndef showGradCam(model, last_conv_layer_name = \"top_conv\", classifier_layer_name = [\"global_average_pooling2d_3\", \"dense_5\"], img_path = r\"F:\\notebooks\\capstone\\data\\fgvc7\\images\\Test_1.jpg\", image_size = 224, save_path = r\"data/archive/grad_cam_test1.jpg\", classes = ['healthy', 'multiple_diseases', 'rust', 'scab']):\n\n img_array = get_img_array(img_path, (image_size,image_size))\n\n # Print what the top predicted class is\n preds = model.predict(img_array)\n print(\"Predicted:\", classes[np.argmax(preds)])\n\n # Generate class activation heatmap\n heatmap = make_gradcam_heatmap(img_array, model, last_conv_layer_name, classifier_layer_name)\n\n # We load the original image\n img = keras.preprocessing.image.load_img(img_path)\n img = keras.preprocessing.image.img_to_array(img)\n\n # We raescale heatmap to a range 0-255\n heatmap = np.uint8(255 * heatmap)\n\n # We use jet colormap to colorize heatmap\n jet = cm.get_cmap(\"jet\")\n\n # We use RGB values of the colormap\n jet_colors = jet(np.arange(256))[:, :3]\n jet_heatmap = jet_colors[heatmap]\n\n # We create an image with RGB colorized heatmap\n jet_heatmap = keras.preprocessing.image.array_to_img(jet_heatmap)\n jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0]))\n jet_heatmap = keras.preprocessing.image.img_to_array(jet_heatmap)\n\n # Superimpose the heatmap on original image\n superimposed_img = jet_heatmap * 0.7 + img * 0.5\n merged_img = np.hstack((img, superimposed_img))\n superimposed_img = keras.preprocessing.image.array_to_img(merged_img)\n \n\n # Save the superimposed image\n superimposed_img.save(save_path)\n\n # Display Grad CAM\n display(Image(save_path))"
] |
[
[
"numpy.hstack",
"numpy.expand_dims",
"numpy.maximum",
"tensorflow.keras.Input",
"tensorflow.keras.preprocessing.image.load_img",
"tensorflow.reduce_mean",
"numpy.uint8",
"numpy.arange",
"tensorflow.keras.Model",
"numpy.max",
"numpy.argmax",
"numpy.mean",
"matplotlib.cm.get_cmap",
"tensorflow.argmax",
"tensorflow.keras.preprocessing.image.array_to_img",
"tensorflow.keras.preprocessing.image.img_to_array",
"tensorflow.GradientTape"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
Matthew-Signorotti/mpi-sppy
|
[
"5c6b4b8cd26af517ff09706d11751f2fb05b1b5f"
] |
[
"mpisppy/utils/listener_util/demo_listener_util.py"
] |
[
"# Copyright 2020 by B. Knueven, D. Mildebrath, C. Muir, J-P Watson, and D.L. Woodruff\n# This software is distributed under the 3-clause BSD License.\n# Demonstrate some uses of listener_util.py for asynchronous computing.\n# This very silly and of limited value.\n# DLW March 2019\n# NOTE: If you have runtime error in this code, then you will need to kill\n# the listener threads.\n\nimport sys\nimport collections\nimport numpy as np\nimport mpisppy.MPI as mpi\nimport time\nimport datetime as dt\nimport threading\nimport logging\nimport mpisppy.utils.listener_util.listener_util as listener_util\n\nstartdt = dt.datetime.now()\n\nfullcomm = mpi.COMM_WORLD\nrank = fullcomm.Get_rank()\nn_proc = fullcomm.Get_size()\n\nlogging.basicConfig(level=logging.DEBUG,\n format='(%(threadName)-10s) %(message)s',\n )\n\ndef worker_bee(synchronizer, buzz=1e6, sting=100.0):\n \"\"\"\n Do some busy work. Note that the synchronizer does not need to be an argument\n to this function (it could be accessed some other way).\n\n Args:\n sychronizer (object): used to do asynchronous sums\n buzz (int): Number of deviates to generate\n sting (float): standard deviation\n\n Returns:\n nothing (these worker functions usually want to update an object\n but in this example we print).\n\n Note: To make this fun, we are randomly distribute the load.\n For even more fun, we occasionally try to \n reduce the listner sleep time but the listener might not see it since\n it might sleep through the whole thing. This is subtle.\n \n We are going to track the time that each rank last reported just to show\n one way to do it. To spell out the way we will do it: \n allocate n_proc of the vector to seconds_since_start and each rank \n will put its seconds_since_start into its spot; hence, the sum will be \n the report (since the others will have contributed zero).\n The number of times a rank has contributed to the sum could be tracked\n in an analogous way.\n \"\"\"\n\n local_sum_sofar = 0\n local_iters_sofar = 0\n global_iters_sofar = 0\n old_sleep = np.zeros(1, dtype='d')\n old_sleep[0] = synchronizer.sleep_secs[0]\n\n # We will send/receive sum (1), iters (1) and secs (n_proc)\n # and we are going to concatenat all \"vectors\" into one.\n local_concat = {\"FirstReduce\": {\"ROOT\": np.zeros(2 + n_proc, dtype='d')}}\n global_concat = {\"FirstReduce\": {\"ROOT\": \\\n np.zeros(len(local_concat[\"FirstReduce\"][\"ROOT\"]), \\\n dtype='d')}}\n\n # In this trivial example, we are going enable the side gig and\n # nothing will disable it. Normally, the listener side gig would\n # be expected to disable it.\n # Gratuitous call to enable the side_gig\n synchronizer.compute_global_data(local_concat,\n global_concat,\n rednames=[\"FirstReduce\"],\n enable_side_gig = True)\n\n while global_iters_sofar < buzz:\n # attempt at less sleep, maybe (but don't do it twice in a row)\n if np.random.uniform() > 0.1 and old_sleep[0] \\\n == synchronizer.sleep_secs[0]:\n old_sleep[0] = synchronizer.sleep_secs[0]\n synchronizer.sleep_secs[0] /= 10\n logging.debug (\"TRYING to reduce sleep to {} from rank={}\".\\\n format(synchronizer.sleep_secs[0], rank))\n elif old_sleep[0] != synchronizer.sleep_secs[0]:\n synchronizer.sleep_secs[0] = old_sleep[0]\n logging.debug (\"putting sleep back to {} from rank={}\".\\\n format(synchronizer.sleep_secs[0], rank))\n\n localiterstodo = int(np.random.uniform() * buzz / n_proc)\n if rank == 0:\n logging.debug(\"**rank 0: iterstodo=\"+str(localiterstodo))\n for i in range(localiterstodo):\n local_sum_sofar += np.random.normal(0, sting)\n \n local_iters_sofar += localiterstodo\n if rank == 0:\n logging.debug(\"rank 0: iterstodo {} iters sofar {} sum_so_far {}=\"\\\n .format(localiterstodo, local_iters_sofar, local_sum_sofar))\n local_concat[\"FirstReduce\"][\"ROOT\"][0] = local_iters_sofar\n local_concat[\"FirstReduce\"][\"ROOT\"][1] = local_sum_sofar\n local_concat[\"FirstReduce\"][\"ROOT\"][2+rank] \\\n = (dt.datetime.now() - startdt).total_seconds()\n\n # Only do \"FirstReduce\".\n synchronizer.compute_global_data(local_concat,\n global_concat,\n rednames=[\"FirstReduce\"])\n\n global_iters_sofar = global_concat[\"FirstReduce\"][\"ROOT\"][0]\n global_sum = global_concat[\"FirstReduce\"][\"ROOT\"][1]\n if rank == 0:\n logging.debug(\" rank 0: global_iters {} global_sum_so_far {}\"\\\n .format(global_iters_sofar, global_sum))\n\n # tell the listener threads to shut down\n synchronizer.quitting = 1\n\n if rank == 0:\n print (\"Rank 0 termination\")\n print (\"Based on {} iterations, the average was {}\".\\\n format(global_iters_sofar, global_sum / global_iters_sofar))\n print (\"In case you are curious:\\n rank \\t last report *in* (sec)\")\n for r in range(n_proc):\n print (r, \"\\t\", global_concat[\"FirstReduce\"][\"ROOT\"][2+r])\n \n\n#=================================\ndef side_gig(synchro, msg = None):\n \"\"\" Demonstrate a listener side gig. This will be called by the listener.\n This is a small, silly function. Usually, the side-gig will check\n to see if it should do something or just pass.\n dlw babble: we can *look* at synchronizer.global_data for\n our redname because we know the reduction was just done.\n We can then jump in and modify local_data for the next reduction.\n This is either \"hackish\" or \"c-like\" depending on your point of view.\n Args:\n snchro (object): the Synchronizer object where the listener lives\n msg (str): just to show keyword arg; normally, this would be \n something (e.g., an object) that is modified\n \"\"\"\n if synchro._rank == 0:\n print (\" (rank 0) ^*^* side_gig msg=\", str(msg))\n logging.debug(\"enter side gig on rank %d\" % rank)\n\n # Just to demonstrate how to do it, we will just return if nothing\n # changed in the first reduce.\n # NOTE: often the side will want to check and update enable_side_gig\n # on the synchro object. See aph.\n # So this code needs to know the name of previous reduce.\n # BTW: in this example, we are treating the function as an object,\n # but in most applications, this function will be in an object.\n prevredname = \"FirstReduce\"\n allthesame = True\n if len(side_gig.prev_red_prev_concat) == 0: # first time\n for cname, clen in synchro.Lens[prevredname].items():\n side_gig.prev_red_prev_concat[cname] = np.zeros(clen, dtype='d')\n allthesame = False # in case they are actually all zero\n\n for cname in synchro.Lens[prevredname]:\n if not np.array_equal(side_gig.prev_red_prev_concat[cname],\n synchro.global_data[prevredname][cname]):\n allthesame = False\n break\n if allthesame:\n logging.debug(\"Skipping intermediate side_gig on rank %d\" % rank)\n return\n\n logging.debug(\"Doing intermediate side_gig on rank %d\" % rank)\n # It is OK for us to directly at global_data on the synchro because\n # the side_gig is \"part of\" the listener, the listener has the lock,\n # and only the listener updates global_data on the syncrho.\n # Side gigs are a bit of a hack.\n\n # this particular side_gig is very silly\n lastsideresult = synchro.global_data[\"SecondReduce\"][\"ROOT\"]\n logging.debug(\"In case you are curious, before this listener call to\"\\\n +\"side_gig, the value of the secondreduce was {} on rank {}\"\\\n .format(lastsideresult, rank))\n \n # dst, src\n np.copyto(side_gig.prev_red_prev_concat[cname],\n synchro.global_data[prevredname][cname])\n \n # For the second reduce, we are going to sum the ranks, which is silly.\n \n # Normally, the concats would be created once in an __init__, btw.\n local_concat = {\"SecondReduce\": {\"ROOT\": np.zeros(1, dtype='d')}}\n global_concat = {\"SecondReduce\": {\"ROOT\": np.zeros(1, dtype='d')}}\n local_concat[\"SecondReduce\"][\"ROOT\"][0] = rank\n # We can (and should) do a dangerous put in the side_gig because\n # the listener will have the lock. If the worker gets to its compute_global\n # then it will have to wait for the lock.\n synchro._unsafe_put_local_data(\"SecondReduce\", local_concat)\n\n\n # global data for the second reduce will be updated when we return to the\n # listener and\n # it will be available for the next get (we don't need a compute).\n # But it is not available now because the reduction has not been done yet.\n\nside_gig.prev_red_prev_concat = {}#[cname]=synchro.global_data[prevredname][cname]\n \n\n####### Main #######\nusemsg = \"usage: python demo_listener_util.py iters sleep seed; e.g.,\\n\" + \\\n \"python demo_listener_util.py 1e5 0.5 1134\"\nif len(sys.argv) != 4:\n raise RuntimeError(usemsg)\ntry:\n iters = int(sys.argv[1])\nexcept:\n raise RuntimeError(sys.argv[1]+\" is not a valid iters\\n\"+usemsg) \ntry:\n sleep = float(sys.argv[2])\nexcept:\n raise RuntimeError(sys.argv[2]+\" is not a valid sleep\\n\"+usemsg)\ntry:\n seed = int(sys.argv[3])\nexcept:\n raise RuntimeError(sys.argv[3]+\" is not a valid seed\\n\"+usemsg) \n\nsting = 1 # standard devation\nnp.random.seed(seed)\n\n# Note: at this point the first reduce is the only reduce\nLens = collections.OrderedDict({\"FirstReduce\": {\"ROOT\": 2+n_proc}})\nif rank == 0:\n logging.debug(\"iters %d, sleep %f, seed %d\".format((iters, sleep, seed)))\n# \"ROOT\" is required to be the name of the global comm\nsynchronizer = listener_util.Synchronizer(comms = {\"ROOT\": fullcomm},\n Lens = Lens,\n work_fct = worker_bee,\n rank = rank,\n sleep_secs = sleep,\n asynch = True)\nargs = [synchronizer]\nkwargs = {\"buzz\": iters, \"sting\": sting}\nsynchronizer.run(args, kwargs)\n\n### now demo the use of a listener side gig between two reductions ###\nif rank == 0:\n print (\"testing side gig\")\nlogging.debug(\"testing side gig on rank %d\" % rank)\n\nkwargs = {\"msg\": \"Oh wow, the side gig is running\"}\nLens = collections.OrderedDict({\"FirstReduce\": {\"ROOT\": 2+n_proc},\n \"SecondReduce\": {\"ROOT\": 1}})\nlistener_gigs = {\"FirstReduce\": (side_gig, kwargs),\n \"SecondReduce\": None}\n\nsynchronizer = listener_util.Synchronizer(comms = {\"ROOT\": fullcomm},\n Lens = Lens,\n work_fct = worker_bee,\n rank = rank,\n sleep_secs = sleep,\n asynch = True,\n listener_gigs = listener_gigs)\nargs = [synchronizer]\nkwargs = {\"buzz\": iters, \"sting\": sting}\nsynchronizer.run(args, kwargs)\n"
] |
[
[
"numpy.array_equal",
"numpy.random.seed",
"numpy.random.normal",
"numpy.copyto",
"numpy.random.uniform",
"numpy.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jiahuanglin/pytorch-transformers
|
[
"a7a93143df4e60e31e062d7f2a4eb0d6283473a4"
] |
[
"pytorch_transformers/modeling_bert.py"
] |
[
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"PyTorch BERT model. \"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport json\nimport logging\nimport math\nimport os\nimport sys\nfrom io import open\n\nimport torch\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss, MSELoss\n\nfrom .modeling_utils import (WEIGHTS_NAME, CONFIG_NAME, PretrainedConfig, PreTrainedModel,\n prune_linear_layer, add_start_docstrings)\n\nlogger = logging.getLogger(__name__)\n\nBERT_PRETRAINED_MODEL_ARCHIVE_MAP = {\n 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-pytorch_model.bin\",\n 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-pytorch_model.bin\",\n 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-pytorch_model.bin\",\n 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-pytorch_model.bin\",\n 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-pytorch_model.bin\",\n 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-pytorch_model.bin\",\n 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-pytorch_model.bin\",\n 'bert-base-german-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-cased-pytorch_model.bin\",\n 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-pytorch_model.bin\",\n 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-pytorch_model.bin\",\n 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-pytorch_model.bin\",\n 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-pytorch_model.bin\",\n 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-pytorch_model.bin\",\n}\n\nBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {\n 'bert-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-config.json\",\n 'bert-large-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-config.json\",\n 'bert-base-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-config.json\",\n 'bert-large-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-config.json\",\n 'bert-base-multilingual-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-uncased-config.json\",\n 'bert-base-multilingual-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-cased-config.json\",\n 'bert-base-chinese': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-config.json\",\n 'bert-base-german-cased': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-german-cased-config.json\",\n 'bert-large-uncased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-config.json\",\n 'bert-large-cased-whole-word-masking': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-config.json\",\n 'bert-large-uncased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-whole-word-masking-finetuned-squad-config.json\",\n 'bert-large-cased-whole-word-masking-finetuned-squad': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-cased-whole-word-masking-finetuned-squad-config.json\",\n 'bert-base-cased-finetuned-mrpc': \"https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-finetuned-mrpc-config.json\",\n}\n\n\ndef load_tf_weights_in_bert(model, config, tf_checkpoint_path):\n \"\"\" Load tf checkpoints in a pytorch model.\n \"\"\"\n try:\n import re\n import numpy as np\n import tensorflow as tf\n except ImportError:\n logger.error(\"Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see \"\n \"https://www.tensorflow.org/install/ for installation instructions.\")\n raise\n tf_path = os.path.abspath(tf_checkpoint_path)\n logger.info(\"Converting TensorFlow checkpoint from {}\".format(tf_path))\n # Load weights from TF model\n init_vars = tf.train.list_variables(tf_path)\n names = []\n arrays = []\n for name, shape in init_vars:\n logger.info(\"Loading TF weight {} with shape {}\".format(name, shape))\n array = tf.train.load_variable(tf_path, name)\n names.append(name)\n arrays.append(array)\n\n for name, array in zip(names, arrays):\n name = name.split('/')\n # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v\n # which are not required for using pretrained model\n if any(n in [\"adam_v\", \"adam_m\", \"global_step\"] for n in name):\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\n continue\n pointer = model\n for m_name in name:\n if re.fullmatch(r'[A-Za-z]+_\\d+', m_name):\n l = re.split(r'_(\\d+)', m_name)\n else:\n l = [m_name]\n if l[0] == 'kernel' or l[0] == 'gamma':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'output_bias' or l[0] == 'beta':\n pointer = getattr(pointer, 'bias')\n elif l[0] == 'output_weights':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'squad':\n pointer = getattr(pointer, 'classifier')\n else:\n try:\n pointer = getattr(pointer, l[0])\n except AttributeError:\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\n continue\n if len(l) >= 2:\n num = int(l[1])\n pointer = pointer[num]\n if m_name[-11:] == '_embeddings':\n pointer = getattr(pointer, 'weight')\n elif m_name == 'kernel':\n array = np.transpose(array)\n try:\n assert pointer.shape == array.shape\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n logger.info(\"Initialize PyTorch weight {}\".format(name))\n pointer.data = torch.from_numpy(array)\n return model\n\[email protected]\ndef f_gelu(x):\n \"\"\"Fused gelu func\"\"\"\n return x * 0.5 * (1.0 + torch.erf(x / 1.41421))\n\n\ndef gelu(x):\n \"\"\"Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n Also see https://arxiv.org/abs/1606.08415\n \"\"\"\n return f_gelu(x)\n\n\ndef swish(x):\n return x * torch.sigmoid(x)\n\n\nACT2FN = {\"gelu\": gelu, \"relu\": torch.nn.functional.relu, \"swish\": swish}\n\n\nclass BertConfig(PretrainedConfig):\n r\"\"\"\n :class:`~pytorch_transformers.BertConfig` is the configuration class to store the configuration of a\n `BertModel`.\n\n\n Arguments:\n vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `BertModel`.\n hidden_size: Size of the encoder layers and the pooler layer.\n num_hidden_layers: Number of hidden layers in the Transformer encoder.\n num_attention_heads: Number of attention heads for each attention layer in\n the Transformer encoder.\n intermediate_size: The size of the \"intermediate\" (i.e., feed-forward)\n layer in the Transformer encoder.\n hidden_act: The non-linear activation function (function or string) in the\n encoder and pooler. If string, \"gelu\", \"relu\" and \"swish\" are supported.\n hidden_dropout_prob: The dropout probabilitiy for all fully connected\n layers in the embeddings, encoder, and pooler.\n attention_probs_dropout_prob: The dropout ratio for the attention\n probabilities.\n max_position_embeddings: The maximum sequence length that this model might\n ever be used with. Typically set this to something large just in case\n (e.g., 512 or 1024 or 2048).\n type_vocab_size: The vocabulary size of the `token_type_ids` passed into\n `BertModel`.\n initializer_range: The sttdev of the truncated_normal_initializer for\n initializing all weight matrices.\n layer_norm_eps: The epsilon used by LayerNorm.\n \"\"\"\n pretrained_config_archive_map = BERT_PRETRAINED_CONFIG_ARCHIVE_MAP\n\n def __init__(self,\n vocab_size_or_config_json_file=30522,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12,\n **kwargs):\n super(BertConfig, self).__init__(**kwargs)\n if isinstance(vocab_size_or_config_json_file, str) or (sys.version_info[0] == 2\n and isinstance(vocab_size_or_config_json_file, unicode)):\n with open(vocab_size_or_config_json_file, \"r\", encoding='utf-8') as reader:\n json_config = json.loads(reader.read())\n for key, value in json_config.items():\n self.__dict__[key] = value\n elif isinstance(vocab_size_or_config_json_file, int):\n self.vocab_size = vocab_size_or_config_json_file\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n else:\n raise ValueError(\"First argument must be either a vocabulary size (int)\"\n \"or the path to a pretrained model config file (str)\")\n\n\n\ntry:\n from apex.normalization.fused_layer_norm import FusedLayerNorm as BertLayerNorm\nexcept ImportError:\n logger.info(\"Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex .\")\n class BertLayerNorm(nn.Module):\n def __init__(self, hidden_size, eps=1e-12):\n \"\"\"Construct a layernorm module in the TF style (epsilon inside the square root).\n \"\"\"\n super(BertLayerNorm, self).__init__()\n self.weight = nn.Parameter(torch.ones(hidden_size))\n self.bias = nn.Parameter(torch.zeros(hidden_size))\n self.variance_epsilon = eps\n\n def forward(self, x):\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n return self.weight * x + self.bias\n\nclass BertEmbeddings(nn.Module):\n \"\"\"Construct the embeddings from word, position and token_type embeddings.\n \"\"\"\n def __init__(self, config):\n super(BertEmbeddings, self).__init__()\n self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0)\n self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)\n self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)\n\n # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load\n # any TensorFlow checkpoint file\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, input_ids, token_type_ids=None, position_ids=None):\n seq_length = input_ids.size(1)\n if position_ids is None:\n position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n words_embeddings = self.word_embeddings(input_ids)\n position_embeddings = self.position_embeddings(position_ids)\n token_type_embeddings = self.token_type_embeddings(token_type_ids)\n\n embeddings = words_embeddings + position_embeddings + token_type_embeddings\n embeddings = self.LayerNorm(embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\n\nclass BertSelfAttention(nn.Module):\n def __init__(self, config):\n super(BertSelfAttention, self).__init__()\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (config.hidden_size, config.num_attention_heads))\n self.output_attentions = config.output_attentions\n\n self.num_attention_heads = config.num_attention_heads\n self.attention_head_size = int(config.hidden_size / config.num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n self.query = nn.Linear(config.hidden_size, self.all_head_size)\n self.key = nn.Linear(config.hidden_size, self.all_head_size)\n self.value = nn.Linear(config.hidden_size, self.all_head_size)\n\n self.dropout = nn.Dropout(config.attention_probs_dropout_prob)\n\n def transpose_for_scores(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)\n x = x.view(*new_x_shape)\n return x.permute(0, 2, 1, 3)\n\n def forward(self, hidden_states, attention_mask, head_mask=None):\n mixed_query_layer = self.query(hidden_states)\n mixed_key_layer = self.key(hidden_states)\n mixed_value_layer = self.value(hidden_states)\n\n query_layer = self.transpose_for_scores(mixed_query_layer)\n key_layer = self.transpose_for_scores(mixed_key_layer)\n value_layer = self.transpose_for_scores(mixed_value_layer)\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))\n attention_scores = attention_scores / math.sqrt(self.attention_head_size)\n # Apply the attention mask is (precomputed for all layers in BertModel forward() function)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = nn.Softmax(dim=-1)(attention_scores)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = self.dropout(attention_probs)\n\n # Mask heads if we want to\n if head_mask is not None:\n attention_probs = attention_probs * head_mask\n\n context_layer = torch.matmul(attention_probs, value_layer)\n\n context_layer = context_layer.permute(0, 2, 1, 3).contiguous()\n new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)\n context_layer = context_layer.view(*new_context_layer_shape)\n\n outputs = (context_layer, attention_probs) if self.output_attentions else (context_layer,)\n return outputs\n\n\nclass BertSelfOutput(nn.Module):\n def __init__(self, config):\n super(BertSelfOutput, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertAttention(nn.Module):\n def __init__(self, config):\n super(BertAttention, self).__init__()\n self.self = BertSelfAttention(config)\n self.output = BertSelfOutput(config)\n\n def prune_heads(self, heads):\n if len(heads) == 0:\n return\n mask = torch.ones(self.self.num_attention_heads, self.self.attention_head_size)\n for head in heads:\n mask[head] = 0\n mask = mask.view(-1).contiguous().eq(1)\n index = torch.arange(len(mask))[mask].long()\n # Prune linear layers\n self.self.query = prune_linear_layer(self.self.query, index)\n self.self.key = prune_linear_layer(self.self.key, index)\n self.self.value = prune_linear_layer(self.self.value, index)\n self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)\n # Update hyper params\n self.self.num_attention_heads = self.self.num_attention_heads - len(heads)\n self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads\n\n def forward(self, input_tensor, attention_mask, head_mask=None):\n self_outputs = self.self(input_tensor, attention_mask, head_mask)\n attention_output = self.output(self_outputs[0], input_tensor)\n outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them\n return outputs\n\n\nclass BertIntermediate(nn.Module):\n def __init__(self, config):\n super(BertIntermediate, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.intermediate_size)\n if isinstance(config.hidden_act, str) or (sys.version_info[0] == 2 and isinstance(config.hidden_act, unicode)):\n self.intermediate_act_fn = ACT2FN[config.hidden_act]\n else:\n self.intermediate_act_fn = config.hidden_act\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n return hidden_states\n\n\nclass BertOutput(nn.Module):\n def __init__(self, config):\n super(BertOutput, self).__init__()\n self.dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertLayer(nn.Module):\n def __init__(self, config):\n super(BertLayer, self).__init__()\n self.attention = BertAttention(config)\n self.intermediate = BertIntermediate(config)\n self.output = BertOutput(config)\n\n def forward(self, hidden_states, attention_mask, head_mask=None):\n attention_outputs = self.attention(hidden_states, attention_mask, head_mask)\n attention_output = attention_outputs[0]\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.output(intermediate_output, attention_output)\n outputs = (layer_output,) + attention_outputs[1:] # add attentions if we output them\n return outputs\n\n\nclass BertEncoder(nn.Module):\n def __init__(self, config):\n super(BertEncoder, self).__init__()\n self.output_attentions = config.output_attentions\n self.output_hidden_states = config.output_hidden_states\n self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])\n\n def forward(self, hidden_states, attention_mask, head_mask=None):\n all_hidden_states = ()\n all_attentions = ()\n for i, layer_module in enumerate(self.layer):\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n layer_outputs = layer_module(hidden_states, attention_mask, head_mask[i])\n hidden_states = layer_outputs[0]\n\n if self.output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n\n # Add last layer\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n outputs = (hidden_states,)\n if self.output_hidden_states:\n outputs = outputs + (all_hidden_states,)\n if self.output_attentions:\n outputs = outputs + (all_attentions,)\n return outputs # outputs, (hidden states), (attentions)\n\n\nclass BertPooler(nn.Module):\n def __init__(self, config):\n super(BertPooler, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n self.activation = nn.Tanh()\n\n def forward(self, hidden_states):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token.\n first_token_tensor = hidden_states[:, 0]\n pooled_output = self.dense(first_token_tensor)\n pooled_output = self.activation(pooled_output)\n return pooled_output\n\n\nclass BertPredictionHeadTransform(nn.Module):\n def __init__(self, config):\n super(BertPredictionHeadTransform, self).__init__()\n self.dense = nn.Linear(config.hidden_size, config.hidden_size)\n if isinstance(config.hidden_act, str) or (sys.version_info[0] == 2 and isinstance(config.hidden_act, unicode)):\n self.transform_act_fn = ACT2FN[config.hidden_act]\n else:\n self.transform_act_fn = config.hidden_act\n self.LayerNorm = BertLayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.transform_act_fn(hidden_states)\n hidden_states = self.LayerNorm(hidden_states)\n return hidden_states\n\n\nclass BertLMPredictionHead(nn.Module):\n def __init__(self, config):\n super(BertLMPredictionHead, self).__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(config.hidden_size,\n config.vocab_size,\n bias=False)\n\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states) + self.bias\n return hidden_states\n\n\nclass BertOnlyMLMHead(nn.Module):\n def __init__(self, config):\n super(BertOnlyMLMHead, self).__init__()\n self.predictions = BertLMPredictionHead(config)\n\n def forward(self, sequence_output):\n prediction_scores = self.predictions(sequence_output)\n return prediction_scores\n\n\nclass BertOnlyNSPHead(nn.Module):\n def __init__(self, config):\n super(BertOnlyNSPHead, self).__init__()\n self.seq_relationship = nn.Linear(config.hidden_size, 2)\n\n def forward(self, pooled_output):\n seq_relationship_score = self.seq_relationship(pooled_output)\n return seq_relationship_score\n\n\nclass BertPreTrainingHeads(nn.Module):\n def __init__(self, config):\n super(BertPreTrainingHeads, self).__init__()\n self.predictions = BertLMPredictionHead(config)\n self.seq_relationship = nn.Linear(config.hidden_size, 2)\n\n def forward(self, sequence_output, pooled_output):\n prediction_scores = self.predictions(sequence_output)\n seq_relationship_score = self.seq_relationship(pooled_output)\n return prediction_scores, seq_relationship_score\n\n\nclass BertPreTrainedModel(PreTrainedModel):\n \"\"\" An abstract class to handle weights initialization and\n a simple interface for dowloading and loading pretrained models.\n \"\"\"\n config_class = BertConfig\n pretrained_model_archive_map = BERT_PRETRAINED_MODEL_ARCHIVE_MAP\n load_tf_weights = load_tf_weights_in_bert\n base_model_prefix = \"bert\"\n\n def __init__(self, *inputs, **kwargs):\n super(BertPreTrainedModel, self).__init__(*inputs, **kwargs)\n\n def init_weights(self, module):\n \"\"\" Initialize the weights.\n \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding)):\n # Slightly different from the TF version which uses truncated_normal for initialization\n # cf https://github.com/pytorch/pytorch/pull/5617\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n elif isinstance(module, BertLayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n\nBERT_START_DOCSTRING = r\"\"\" The BERT model was proposed in\n `BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding`_\n by Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova. It's a bidirectional transformer\n pre-trained using a combination of masked language modeling objective and next sentence prediction\n on a large corpus comprising the Toronto Book Corpus and Wikipedia.\n\n This model is a PyTorch `torch.nn.Module`_ sub-class. Use it as a regular PyTorch Module and\n refer to the PyTorch documentation for all matter related to general usage and behavior.\n\n .. _`BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding`:\n https://arxiv.org/abs/1810.04805\n\n .. _`torch.nn.Module`:\n https://pytorch.org/docs/stable/nn.html#module\n\n Parameters:\n config (:class:`~pytorch_transformers.BertConfig`): Model configuration class with all the parameters of the model.\n\"\"\"\n\nBERT_INPUTS_DOCSTRING = r\"\"\"\n Inputs:\n **input_ids**: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Indices of input sequence tokens in the vocabulary.\n To match pre-training, BERT input sequence should be formatted with [CLS] and [SEP] tokens as follows:\n\n (a) For sequence pairs:\n\n ``tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]``\n \n ``token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1``\n\n (b) For single sequences:\n\n ``tokens: [CLS] the dog is hairy . [SEP]``\n \n ``token_type_ids: 0 0 0 0 0 0 0``\n \n Indices can be obtained using :class:`pytorch_transformers.BertTokenizer`.\n See :func:`pytorch_transformers.PreTrainedTokenizer.encode` and\n :func:`pytorch_transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details.\n **position_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Indices of positions of each input sequence tokens in the position embeddings.\n Selected in the range ``[0, config.max_position_embeddings - 1[``.\n **token_type_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Segment token indices to indicate first and second portions of the inputs.\n Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``\n corresponds to a `sentence B` token\n (see `BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding`_ for more details).\n **attention_mask**: (`optional`) ``torch.Tensor`` of shape ``(batch_size, sequence_length)``:\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n **head_mask**: (`optional`) ``torch.Tensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``:\n Mask to nullify selected heads of the self-attention modules.\n Mask values selected in ``[0, 1]``:\n ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**.\n\"\"\"\n\n@add_start_docstrings(\"The bare Bert Model transformer outputing raw hidden-states without any specific head on top.\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertModel(BertPreTrainedModel):\n r\"\"\"\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)``\n Sequence of hidden-states at the output of the last layer of the model.\n **pooler_output**: ``torch.FloatTensor`` of shape ``(batch_size, hidden_size)``\n Last layer hidden-state of the first token of the sequence (classification token)\n further processed by a Linear layer and a Tanh activation function. The Linear\n layer weights are trained from the next sentence prediction (classification)\n objective during Bert pretraining. This output is usually *not* a good summary\n of the semantic content of the input, you're often better with averaging or pooling\n the sequence of hidden-states for the whole input sequence.\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n >>> config = BertConfig.from_pretrained('bert-base-uncased')\n >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n >>> model = BertModel(config)\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n >>> outputs = model(input_ids)\n >>> last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple\n\n \"\"\"\n def __init__(self, config):\n super(BertModel, self).__init__(config)\n\n self.embeddings = BertEmbeddings(config)\n self.encoder = BertEncoder(config)\n self.pooler = BertPooler(config)\n\n self.apply(self.init_weights)\n\n def _resize_token_embeddings(self, new_num_tokens):\n old_embeddings = self.embeddings.word_embeddings\n new_embeddings = self._get_resized_embeddings(old_embeddings, new_num_tokens)\n self.embeddings.word_embeddings = new_embeddings\n return self.embeddings.word_embeddings\n\n def _prune_heads(self, heads_to_prune):\n \"\"\" Prunes heads of the model.\n heads_to_prune: dict of {layer_num: list of heads to prune in this layer}\n See base class PreTrainedModel\n \"\"\"\n for layer, heads in heads_to_prune.items():\n self.encoder.layer[layer].attention.prune_heads(heads)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, position_ids=None, head_mask=None):\n if attention_mask is None:\n attention_mask = torch.ones_like(input_ids)\n if token_type_ids is None:\n token_type_ids = torch.zeros_like(input_ids)\n\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]\n # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]\n if head_mask is not None:\n if head_mask.dim() == 1:\n head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)\n head_mask = head_mask.expand(self.config.num_hidden_layers, -1, -1, -1, -1)\n elif head_mask.dim() == 2:\n head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1) # We can specify head_mask for each layer\n head_mask = head_mask.to(dtype=next(self.parameters()).dtype) # switch to fload if need + fp16 compatibility\n else:\n head_mask = [None] * self.config.num_hidden_layers\n\n embedding_output = self.embeddings(input_ids, position_ids=position_ids, token_type_ids=token_type_ids)\n encoder_outputs = self.encoder(embedding_output,\n extended_attention_mask,\n head_mask=head_mask)\n sequence_output = encoder_outputs[0]\n pooled_output = self.pooler(sequence_output)\n\n outputs = (sequence_output, pooled_output,) + encoder_outputs[1:] # add hidden_states and attentions if they are here\n return outputs # sequence_output, pooled_output, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with two heads on top as done during the pre-training:\n a `masked language modeling` head and a `next sentence prediction (classification)` head. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForPreTraining(BertPreTrainedModel):\n r\"\"\"\n **masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Labels for computing the masked language modeling loss.\n Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)\n Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels\n in ``[0, ..., config.vocab_size]``\n **next_sentence_label**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see ``input_ids`` docstring)\n Indices should be in ``[0, 1]``.\n ``0`` indicates sequence B is a continuation of sequence A,\n ``1`` indicates sequence B is a random sequence.\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when both ``masked_lm_labels`` and ``next_sentence_label`` are provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Total loss as the sum of the masked language modeling loss and the next sequence prediction (classification) loss.\n **prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n **seq_relationship_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, 2)``\n Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n >>> config = BertConfig.from_pretrained('bert-base-uncased')\n >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n >>> \n >>> model = BertForPreTraining(config)\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n >>> outputs = model(input_ids)\n >>> prediction_scores, seq_relationship_scores = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForPreTraining, self).__init__(config)\n\n self.bert = BertModel(config)\n self.cls = BertPreTrainingHeads(config)\n\n self.apply(self.init_weights)\n self.tie_weights()\n\n def tie_weights(self):\n \"\"\" Make sure we are sharing the input and output embeddings.\n Export to TorchScript can't handle parameter sharing so we are cloning them instead.\n \"\"\"\n self._tie_or_clone_weights(self.cls.predictions.decoder,\n self.bert.embeddings.word_embeddings)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None,\n next_sentence_label=None, position_ids=None, head_mask=None):\n outputs = self.bert(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,\n attention_mask=attention_mask, head_mask=head_mask)\n\n sequence_output, pooled_output = outputs[:2]\n prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)\n\n outputs = (prediction_scores, seq_relationship_score,) + outputs[2:] # add hidden states and attention if they are here\n\n if masked_lm_labels is not None and next_sentence_label is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n total_loss = masked_lm_loss + next_sentence_loss\n outputs = (total_loss,) + outputs\n\n return outputs # (loss), prediction_scores, seq_relationship_score, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with a `language modeling` head on top. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForMaskedLM(BertPreTrainedModel):\n r\"\"\"\n **masked_lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Labels for computing the masked language modeling loss.\n Indices should be in ``[-1, 0, ..., config.vocab_size]`` (see ``input_ids`` docstring)\n Tokens with indices set to ``-1`` are ignored (masked), the loss is only computed for the tokens with labels\n in ``[0, ..., config.vocab_size]``\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``masked_lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Masked language modeling loss.\n **prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n >>> config = BertConfig.from_pretrained('bert-base-uncased')\n >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n >>> \n >>> model = BertForMaskedLM(config)\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n >>> outputs = model(input_ids, masked_lm_labels=input_ids)\n >>> loss, prediction_scores = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForMaskedLM, self).__init__(config)\n\n self.bert = BertModel(config)\n self.cls = BertOnlyMLMHead(config)\n\n self.apply(self.init_weights)\n self.tie_weights()\n\n def tie_weights(self):\n \"\"\" Make sure we are sharing the input and output embeddings.\n Export to TorchScript can't handle parameter sharing so we are cloning them instead.\n \"\"\"\n self._tie_or_clone_weights(self.cls.predictions.decoder,\n self.bert.embeddings.word_embeddings)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None,\n position_ids=None, head_mask=None):\n outputs = self.bert(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,\n attention_mask=attention_mask, head_mask=head_mask)\n\n sequence_output = outputs[0]\n prediction_scores = self.cls(sequence_output)\n\n outputs = (prediction_scores,) + outputs[2:] # Add hidden states and attention is they are here\n if masked_lm_labels is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n outputs = (masked_lm_loss,) + outputs\n\n return outputs # (masked_lm_loss), prediction_scores, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with a `next sentence prediction (classification)` head on top. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForNextSentencePrediction(BertPreTrainedModel):\n r\"\"\"\n **next_sentence_label**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see ``input_ids`` docstring)\n Indices should be in ``[0, 1]``.\n ``0`` indicates sequence B is a continuation of sequence A,\n ``1`` indicates sequence B is a random sequence.\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``next_sentence_label`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Next sequence prediction (classification) loss.\n **seq_relationship_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, 2)``\n Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n >>> config = BertConfig.from_pretrained('bert-base-uncased')\n >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n >>> \n >>> model = BertForNextSentencePrediction(config)\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n >>> outputs = model(input_ids)\n >>> seq_relationship_scores = outputs[0]\n\n \"\"\"\n def __init__(self, config):\n super(BertForNextSentencePrediction, self).__init__(config)\n\n self.bert = BertModel(config)\n self.cls = BertOnlyNSPHead(config)\n\n self.apply(self.init_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, next_sentence_label=None,\n position_ids=None, head_mask=None):\n outputs = self.bert(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,\n attention_mask=attention_mask, head_mask=head_mask)\n pooled_output = outputs[1]\n\n seq_relationship_score = self.cls(pooled_output)\n\n outputs = (seq_relationship_score,) + outputs[2:] # add hidden states and attention if they are here\n if next_sentence_label is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n outputs = (next_sentence_loss,) + outputs\n\n return outputs # (next_sentence_loss), seq_relationship_score, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForSequenceClassification(BertPreTrainedModel):\n r\"\"\"\n **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for computing the sequence classification/regression loss.\n Indices should be in ``[0, ..., config.num_labels]``.\n If ``config.num_labels == 1`` a regression loss is computed (Mean-Square loss),\n If ``config.num_labels > 1`` a classification loss is computed (Cross-Entropy).\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Classification (or regression if config.num_labels==1) loss.\n **logits**: ``torch.FloatTensor`` of shape ``(batch_size, config.num_labels)``\n Classification (or regression if config.num_labels==1) scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n >>> config = BertConfig.from_pretrained('bert-base-uncased')\n >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n >>> \n >>> model = BertForSequenceClassification(config)\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n >>> labels = torch.tensor([1]).unsqueeze(0) # Batch size 1\n >>> outputs = model(input_ids, labels=labels)\n >>> loss, logits = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForSequenceClassification, self).__init__(config)\n self.num_labels = config.num_labels\n\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)\n\n self.apply(self.init_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None,\n position_ids=None, head_mask=None):\n outputs = self.bert(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,\n attention_mask=attention_mask, head_mask=head_mask)\n pooled_output = outputs[1]\n\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n\n outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here\n\n if labels is not None:\n if self.num_labels == 1:\n # We are doing regression\n loss_fct = MSELoss()\n loss = loss_fct(logits.view(-1), labels.view(-1))\n else:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (loss), logits, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with a multiple choice classification head on top (a linear layer on top of\n the pooled output and a softmax) e.g. for RocStories/SWAG tasks. \"\"\",\n BERT_START_DOCSTRING)\nclass BertForMultipleChoice(BertPreTrainedModel):\n r\"\"\"\n Inputs:\n **input_ids**: ``torch.LongTensor`` of shape ``(batch_size, num_choices, sequence_length)``:\n Indices of input sequence tokens in the vocabulary.\n The second dimension of the input (`num_choices`) indicates the number of choices to score.\n To match pre-training, BERT input sequence should be formatted with [CLS] and [SEP] tokens as follows:\n\n (a) For sequence pairs:\n\n ``tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]``\n \n ``token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1``\n\n (b) For single sequences:\n\n ``tokens: [CLS] the dog is hairy . [SEP]``\n \n ``token_type_ids: 0 0 0 0 0 0 0``\n \n Indices can be obtained using :class:`pytorch_transformers.BertTokenizer`.\n See :func:`pytorch_transformers.PreTrainedTokenizer.encode` and\n :func:`pytorch_transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details.\n **token_type_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, num_choices, sequence_length)``:\n Segment token indices to indicate first and second portions of the inputs.\n The second dimension of the input (`num_choices`) indicates the number of choices to score.\n Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``\n corresponds to a `sentence B` token\n (see `BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding`_ for more details).\n **attention_mask**: (`optional`) ``torch.Tensor`` of shape ``(batch_size, num_choices, sequence_length)``:\n Mask to avoid performing attention on padding token indices.\n The second dimension of the input (`num_choices`) indicates the number of choices to score.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n **head_mask**: (`optional`) ``torch.Tensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``:\n Mask to nullify selected heads of the self-attention modules.\n Mask values selected in ``[0, 1]``:\n ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**.\n **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for computing the multiple choice classification loss.\n Indices should be in ``[0, ..., num_choices]`` where `num_choices` is the size of the second dimension\n of the input tensors. (see `input_ids` above)\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Classification loss.\n **classification_scores**: ``torch.FloatTensor`` of shape ``(batch_size, num_choices)`` where `num_choices` is the size of the second dimension\n of the input tensors. (see `input_ids` above).\n Classification scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n >>> config = BertConfig.from_pretrained('bert-base-uncased')\n >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n >>> \n >>> model = BertForMultipleChoice(config)\n >>> choices = [\"Hello, my dog is cute\", \"Hello, my cat is amazing\"]\n >>> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices\n >>> labels = torch.tensor(1).unsqueeze(0) # Batch size 1\n >>> outputs = model(input_ids, labels=labels)\n >>> loss, classification_scores = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForMultipleChoice, self).__init__(config)\n\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, 1)\n\n self.apply(self.init_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None,\n position_ids=None, head_mask=None):\n num_choices = input_ids.shape[1]\n\n flat_input_ids = input_ids.view(-1, input_ids.size(-1))\n flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None\n flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None\n flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None\n outputs = self.bert(flat_input_ids, position_ids=flat_position_ids, token_type_ids=flat_token_type_ids,\n attention_mask=flat_attention_mask, head_mask=head_mask)\n pooled_output = outputs[1]\n\n pooled_output = self.dropout(pooled_output)\n logits = self.classifier(pooled_output)\n reshaped_logits = logits.view(-1, num_choices)\n\n outputs = (reshaped_logits,) + outputs[2:] # add hidden states and attention if they are here\n\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(reshaped_logits, labels)\n outputs = (loss,) + outputs\n\n return outputs # (loss), reshaped_logits, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with a token classification head on top (a linear layer on top of\n the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForTokenClassification(BertPreTrainedModel):\n r\"\"\"\n **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Labels for computing the token classification loss.\n Indices should be in ``[0, ..., config.num_labels]``.\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Classification loss.\n **scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.num_labels)``\n Classification scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n >>> config = BertConfig.from_pretrained('bert-base-uncased')\n >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n >>> \n >>> model = BertForTokenClassification(config)\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n >>> labels = torch.tensor([1] * input_ids.size(1)).unsqueeze(0) # Batch size 1\n >>> outputs = model(input_ids, labels=labels)\n >>> loss, scores = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForTokenClassification, self).__init__(config)\n self.num_labels = config.num_labels\n\n self.bert = BertModel(config)\n self.dropout = nn.Dropout(config.hidden_dropout_prob)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n\n self.apply(self.init_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None,\n position_ids=None, head_mask=None):\n outputs = self.bert(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,\n attention_mask=attention_mask, head_mask=head_mask)\n sequence_output = outputs[0]\n\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n outputs = (logits,) + outputs[2:] # add hidden states and attention if they are here\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n # Only keep active parts of the loss\n if attention_mask is not None:\n active_loss = attention_mask.view(-1) == 1\n active_logits = logits.view(-1, self.num_labels)[active_loss]\n active_labels = labels.view(-1)[active_loss]\n loss = loss_fct(active_logits, active_labels)\n else:\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (loss), scores, (hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of\n the hidden-states output to compute `span start logits` and `span end logits`). \"\"\",\n BERT_START_DOCSTRING, BERT_INPUTS_DOCSTRING)\nclass BertForQuestionAnswering(BertPreTrainedModel):\n r\"\"\"\n **start_positions**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`).\n Position outside of the sequence are not taken into account for computing the loss.\n **end_positions**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size,)``:\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (`sequence_length`).\n Position outside of the sequence are not taken into account for computing the loss.\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.\n **start_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``\n Span-start scores (before SoftMax).\n **end_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length,)``\n Span-end scores (before SoftMax).\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n >>> config = BertConfig.from_pretrained('bert-base-uncased')\n >>> tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n >>> \n >>> model = BertForQuestionAnswering(config)\n >>> input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n >>> start_positions = torch.tensor([1])\n >>> end_positions = torch.tensor([3])\n >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)\n >>> loss, start_scores, end_scores = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(BertForQuestionAnswering, self).__init__(config)\n self.num_labels = config.num_labels\n\n self.bert = BertModel(config)\n self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)\n\n self.apply(self.init_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, start_positions=None,\n end_positions=None, position_ids=None, head_mask=None):\n outputs = self.bert(input_ids, position_ids=position_ids, token_type_ids=token_type_ids,\n attention_mask=attention_mask, head_mask=head_mask)\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1)\n end_logits = end_logits.squeeze(-1)\n\n outputs = (start_logits, end_logits,) + outputs[2:]\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions.clamp_(0, ignored_index)\n end_positions.clamp_(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n outputs = (total_loss,) + outputs\n\n return outputs # (loss), start_logits, end_logits, (hidden_states), (attentions)\n"
] |
[
[
"torch.nn.Softmax",
"torch.zeros",
"torch.nn.Embedding",
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"torch.sqrt",
"torch.from_numpy",
"torch.arange",
"tensorflow.train.list_variables",
"torch.ones_like",
"torch.sigmoid",
"torch.zeros_like",
"tensorflow.train.load_variable",
"torch.nn.Linear",
"numpy.transpose",
"torch.nn.Tanh",
"torch.matmul",
"torch.erf",
"torch.nn.MSELoss"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
xingshulicc/citrus-pest-classification-by-advanced-deep-learning
|
[
"6f98ddcf680356db35ac111204da12a057ed8bd8"
] |
[
"xception_test_model.py"
] |
[
"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\"\"\"\nCreated on Mon Sep 25 09:51:13 2017\n\n@author: xingshuli\n\"\"\"\n\n'''\nThe default_size of input image is 299 and min_size = 71\nShould note that the input preprocessing function is also different from\nVGG16 and ResNet but same as Xception: the pixel value between -1 and 1\n'''\n\nimport os\nimport numpy as np\nimport keras\n\nfrom keras.layers import Input\nfrom keras.layers import Dense\n#from keras.layers import Dropout\n\nfrom keras.applications.xception import Xception\nfrom keras.preprocessing import image\nfrom keras.models import Model\nfrom keras.preprocessing.image import ImageDataGenerator\n\nfrom keras.callbacks import EarlyStopping \n\nimg_width, img_height = 200, 200 \ninput_tensor = Input(shape=(img_width, img_height, 3))\n\ntrain_data_dir = os.path.join(os.getcwd(), 'data/train')\nvalidation_data_dir = os.path.join(os.getcwd(), 'data/validation')\n\nnb_train_samples = 5000\nnb_validation_samples = 1000\n\nnum_class = 10\nepochs = 100\nbatch_size = 20\n\n#load pre_trained model\n\nbase_model = Xception(include_top = False, weights = 'imagenet', \n input_tensor = input_tensor, pooling = 'avg')\n\n#visualize layer name and layer indices \nfor i, layer in enumerate(base_model.layers):\n print(i, layer.name)\n\n#reconstruct fully-connected layers\nx = base_model.output\nx = Dense(2048, activation='relu')(x)\n#x = Dropout(0.25)(x)\npre_out = Dense(num_class, activation='softmax')(x)\n\n#reconstruct the model\ntrain_model = Model(base_model.input, outputs= pre_out, name='train_model')\n\n#we will freeze the first 3 layers and fine-tune the rest\nfor layer in base_model.layers[:4]:\n layer.trainable = False\nfor layer in base_model.layers[4:]:\n layer.trainable = True\n\n#fine-tune:the learning rate should be smaller \nsgd = keras.optimizers.SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True)\ntrain_model.compile(loss='categorical_crossentropy', \n optimizer=sgd, metrics=['accuracy'])\n\ntrain_model.summary()\n#imgae data augmentation\ntrain_datagen = ImageDataGenerator(rotation_range=30, \n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n rescale=1. / 255,\n fill_mode='nearest')\n\n\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\n\n\ntrain_generator = train_datagen.flow_from_directory(\n train_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode='categorical')\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode='categorical')\n \n\n#early-stopping\nearly_stopping = EarlyStopping(monitor='val_loss', patience=3)\n\n#train the model on the new data\nhist = train_model.fit_generator(\n train_generator,\n steps_per_epoch=nb_train_samples //batch_size,\n epochs=epochs,\n validation_data=validation_generator,\n validation_steps=nb_validation_samples //batch_size, \n callbacks=[early_stopping])\n\n#print acc and stored into acc.txt\nf = open('/home/xingshuli/Desktop/acc.txt','w')\nf.write(str(hist.history['acc']))\nf.close()\n#print val_acc and stored into val_acc.txt\nf = open('/home/xingshuli/Desktop/val_acc.txt','w')\nf.write(str(hist.history['val_acc']))\nf.close()\n#print val_loss and stored into val_loss.txt \nf = open('/home/xingshuli/Desktop/val_loss.txt', 'w')\nf.write(str(hist.history['val_loss']))\nf.close()\n\n#evaluate the model\nevaluation = train_model.evaluate_generator(validation_generator,\n steps=nb_validation_samples //batch_size)\n \nprint('Model Accuracy = %.4f' % (evaluation[1]))\n\n\n\n#predict a category of input image\nimg_path = '/home/xingshuli/Desktop/test_pictures/citrus_swallowtail.jpeg'\nimg = image.load_img(img_path, target_size=(200, 200))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\nx /=255\nprint('Input image shape:', x.shape)\npreds = train_model.predict(x)\nprint('citrus_swallowtail:%f, forktailed_bush_katydid:%f, ground_beetle:%f, \\\ngreen_stink_bug:%f, green_leafhopper:%f, syrhip_fly:%f, dragon_fly:%f, \\\nmantis:%f, fruit_moth:%f, citrus_longicorn_beetle:%f' \\\n %(preds[0][0], preds[0][1], preds[0][2], preds[0][3], preds[0][4], \n preds[0][5], preds[0][6], preds[0][7], preds[0][8], preds[0][9]))\n\n\n#the pre-processing for imagenet in Xception\n\n#def preprocess_input(x):\n# x /= 255.\n# x -= 0.5\n# x *= 2.\n# return x\n\n\n#if __name__ == '__main__':\n# model = Xception(include_top=True, weights='imagenet')\n#\n# img_path = 'elephant.jpg'\n# img = image.load_img(img_path, target_size=(299, 299))\n# x = image.img_to_array(img)\n# x = np.expand_dims(x, axis=0)\n# x = preprocess_input(x)\n# print('Input image shape:', x.shape)\n#\n# preds = model.predict(x)\n# print(np.argmax(preds))\n# print('Predicted:', decode_predictions(preds, 1))\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] |
[
[
"numpy.expand_dims"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
EmoryMLIP/DynamicBlocks
|
[
"52acc9fbc1a2640c6ac8922fa18105279ccaea97"
] |
[
"modules/TvNorm.py"
] |
[
"# TvNorm.py\n\nimport torch\nimport torch.nn as nn\n\nclass TvNorm(nn.Module):\n \"\"\"\n normalization using the total variation; idea is to normalize pixel-wise by the length of the feature vector, i.e.,\n MATLAB notation:\n z = diag( 1/ sqrt( sum(x.^2,3)+eps)) x\n\n Attributes:\n eps: small float so no division by 0\n weight: scaling weight for the affine transformation\n bias: bias for the affine transformation\n\n \"\"\"\n def __init__(self, nChan, eps=1e-4):\n \"\"\"\n :param nChan: number of channels for the data you expect to normalize\n :param eps: small float so no division by 0\n \"\"\"\n super().__init__()\n\n self.eps = eps\n\n # Tv Norm has no tuning of the scaling weights\n # self.weight = nn.Parameter(torch.ones(nChan))\n self.register_buffer('weight', torch.ones(nChan))\n\n self.bias = nn.Parameter(torch.zeros(nChan))\n\n\n def forward(self,x):\n \"\"\"\n :param x: inputs tensor, second dim is channels\n example dims: (num images in the batch , num channels, height , width)\n :return: normalized version with same dimensions as x\n \"\"\"\n z = torch.pow(x, 2)\n z = torch.div(x, torch.sqrt(torch.sum(z, dim=1, keepdim=True) + self.eps))\n # assumes that Tensor is formatted ( something , no. of channels, something, something, etc.)\n\n if self.weight is not None:\n w = self.weight.unsqueeze(0) # add first dimension\n w = w.unsqueeze(-1) # add last dimension\n w = w.unsqueeze(-1) # add last dimension\n z = z * w\n if self.bias is not None:\n b = self.bias.unsqueeze(0) # add first dimension\n b = b.unsqueeze(-1) # add last dimension\n b = b.unsqueeze(-1) # add last dimension\n z = z + b\n\n return z\n\n"
] |
[
[
"torch.sum",
"torch.ones",
"torch.pow",
"torch.zeros"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ttpro1995/CV_FinalProject
|
[
"89aa252f349561b6d4a6a4a9c8d0ae6e00429f92"
] |
[
"preprocessor.py"
] |
[
"# Thai Thien 1351040\n\nimport cv2\nimport copyright\nimport numpy as np\nfrom os import listdir\nfrom os.path import isfile, join, splitext\nimport os.path\n\nclass PreProcessor:\n def __init__(self, face_xml, eye_xml, mouth_xml, nose_xml):\n \"\"\"\n\n :param face_xml: pretrain cascade classifier for face detection\n :param eye_xml: pretrain cascade classifier for eye detection\n :param mouth_xml: pretrain cascade classifier for mouth detection\n :param nose_xml: pretrain cascade classifier for nose detection\n \"\"\"\n self.FAILED_MOUTH = 'FAILED to detect MOUTH'\n self.FAILED_EYE = 'FAILED to detect EYE'\n self.FAILED_NOSE = 'FAILED to detect NOSE'\n self.face_cascade = cv2.CascadeClassifier(face_xml)\n self.eye_cascade = cv2.CascadeClassifier(eye_xml)\n self.nose_cascade = cv2.CascadeClassifier(nose_xml)\n self.mouth_cascade = cv2.CascadeClassifier(mouth_xml)\n self.kernel = np.ones((5, 5), np.float32) / 25\n\n def process_file(self, filename, size_dim, landmark = False):\n \"\"\"\n Convert image to black scale\n detect face in image\n return a array of face size 96x96\n :param filename: raw data file name\n :return:\n ret: an array each element is tuple (roi_face, roi_eyes, roi_nose, roi_mouth)\n \"\"\"\n print ('process file ', filename)\n img = cv2.imread(filename)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Color -> grayscale\n gray = cv2.GaussianBlur(gray,(5,5),0) # blur gaussian\n ret = []\n faces = self.face_cascade.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in faces:\n roi_eyes = []\n cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n roi_gray = gray[y:y + h, x:x + w]\n roi_gray = cv2.resize(roi_gray, (size_dim, size_dim)) # resize image to 96x96\n roi_face = roi_gray\n\n if (landmark):\n # detect eye\n eyes = self.eye_cascade.detectMultiScale(roi_gray)\n if len(eyes) <2:\n return self.FAILED_EYE\n\n for (ex, ey,ew,eh) in eyes:\n roi_eye = roi_face[ey:ey + eh, ex:ex + ew]\n roi_eyes.append(roi_eye)\n\n # detect nose\n nose = self.nose_cascade.detectMultiScale(roi_gray)\n if len(nose) < 1:\n return self.FAILED_NOSE\n\n nx, ny, nw, nh = nose[0]\n roi_nose = roi_face[ny:ny + nh, nx:nx + nw]\n\n # detect mouth\n mouth = self.mouth_cascade.detectMultiScale(roi_gray)\n if len(mouth) < 1:\n return self.FAILED_MOUTH\n\n mx, my, mw, mh = mouth[0]\n roi_mouth = roi_face[my:my + mh, mx:mx + mw]\n\n sample = (roi_face, roi_eyes, roi_nose, roi_mouth)\n else:\n sample = (roi_face, None)\n\n ret.append(sample)\n return ret\n\n def display_ret(self,ret):\n \"\"\"\n Display the result of preprocess_file function\n :param ret: output of preprocess_file function\n :return: nothing\n \"\"\"\n face, eyes, nose, mouth = ret[0]\n cv2.imshow('face',face)\n cv2.imshow('left_eye', eyes[0])\n cv2.imshow('right_eye', eyes[1])\n cv2.imshow('nose', nose)\n cv2.imshow('mouth', mouth)\n\n cv2.waitKey()\n cv2.destroyAllWindows()\n\n def preprocess(self, in_dir, out_dir, size_dim):\n inputs = [f for f in listdir(in_dir) if isfile(join(in_dir, f))]\n for filename in inputs:\n outputs = self.process_file(in_dir+'/'+filename, size_dim)\n for output_img in outputs:\n output_img = output_img[0] # only the face\n cv2.imwrite(out_dir+'/'+filename, output_img)\n\n def preprocess_landmark(self, in_dir, out_dir):\n \"\"\"\n Preprocess file and get landmark of eye, nose, mouth\n :param in_dir:\n :param out_dir:\n :return:\n \"\"\"\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n inputs = [f for f in listdir(in_dir) if isfile(join(in_dir, f))]\n for filename in inputs:\n outputs = self.process_file(in_dir+'/'+filename, size_dim=96, landmark=True)\n if outputs == self.FAILED_MOUTH or outputs == self.FAILED_NOSE or outputs == self.FAILED_EYE:\n print ('in %s, error %s'%(filename, outputs))\n continue # whenever failed to detect all eyes, nose, mouth, skip picture\n\n name, extension = splitext(filename)\n subdir = out_dir+'/'+name # contain landmark\n if not os.path.exists(out_dir+'/'+name):\n os.makedirs(out_dir+'/'+name)\n for roi_face, roi_eyes, roi_nose, roi_mouth in outputs:\n cv2.imwrite(out_dir+'/'+filename, roi_face)\n cv2.imwrite(subdir + '/' + 'eye0.tiff', roi_eyes[0])\n cv2.imwrite(subdir + '/' + 'eye1.tiff', roi_eyes[1])\n cv2.imwrite(subdir + '/' + 'nose.tiff', roi_nose)\n cv2.imwrite(subdir + '/' + 'mouth.tiff', roi_mouth)\n\n"
] |
[
[
"numpy.ones"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ckm3/eleanor
|
[
"d460ec5b420781c7adc44ed260020d60d1cb91ed"
] |
[
"eleanor/update.py"
] |
[
"import os\nfrom urllib.request import urlopen\nfrom datetime import datetime\nimport math\nfrom astropy.coordinates import SkyCoord\nfrom astropy import units as u\nfrom astroquery.mast import Tesscut\nfrom astropy.io import fits\nimport numpy as np\nfrom lightkurve import TessLightCurveFile, search_targetpixelfile\nimport sys\nimport urllib.parse as urlparse\nimport requests\nfrom bs4 import BeautifulSoup\n\n\neleanorpath = os.path.join(os.path.expanduser('~'), '.eleanor')\nif not os.path.exists(eleanorpath):\n try:\n os.mkdir(eleanorpath)\n except OSError:\n eleanorpath = os.path.dirname(__file__)\n\ndef hmsm_to_days(hour=0,min=0,sec=0,micro=0):\n days = sec + (micro / 1.e6)\n days = min + (days / 60.)\n days = hour + (days / 60.)\n return days / 24.\ndef date_to_jd(year,month,day):\n if month == 1 or month == 2:\n yearp = year - 1\n monthp = month + 12\n else:\n yearp = year\n monthp = month\n\n # this checks where we are in relation to October 15, 1582, the beginning\n # of the Gregorian calendar.\n if ((year < 1582) or\n (year == 1582 and month < 10) or\n (year == 1582 and month == 10 and day < 15)):\n # before start of Gregorian calendar\n B = 0\n else:\n # after start of Gregorian calendar\n A = math.trunc(yearp / 100.)\n B = 2 - A + math.trunc(A / 4.)\n\n if yearp < 0:\n C = math.trunc((365.25 * yearp) - 0.75)\n else:\n C = math.trunc(365.25 * yearp)\n\n D = math.trunc(30.6001 * (monthp + 1))\n\n jd = B + C + D + day + 1720994.5 + 0.0008 # including leap second correction\n\n return jd\n\ndef listFD(url, ext=''):\n page = requests.get(url).text\n soup = BeautifulSoup(page, 'html.parser')\n return [url + node.get('href') for node in soup.find_all('a') if node.get('href').endswith(ext)]\n\n__all__ = ['Update', 'update_all']\n\ndef update_all():\n sector = 1\n good = 1\n while good:\n try:\n Update(sector=sector)\n except AttributeError:\n good = 0\n sector += 1\n\nclass Update(object):\n\n def __init__(self, sector=None):\n\n if sector is None:\n print('Please pass a sector into eleanor.Update()!')\n return\n\n self.sector = sector\n\n try:\n os.mkdir(eleanorpath + '/metadata/s{:04d}'.format(sector))\n success = 1\n except FileExistsError:\n print('Sector {:d} metadata directory exists already!'.format(sector))\n success = 0\n\n if success == 1:\n\n tic_north_cvz = 198237770\n tic_south_cvz = 38846515\n\n if self.sector < 13.5:\n self.tic = tic_south_cvz\n elif self.sector < 26.5:\n self.tic = tic_north_cvz\n else:\n self.tic = tic_south_cvz\n\n if self.tic == 198237770:\n coord = SkyCoord('16:35:50.667 +63:54:39.87', unit=(u.hourangle, u.deg))\n elif self.tic == 38846515:\n coord = SkyCoord('04:35:50.330 -64:01:37.33', unit=(u.hourangle, u.deg))\n\n sector_table = Tesscut.get_sectors(coord)\n\n\n manifest = Tesscut.download_cutouts(coord, 31, sector = self.sector)\n\n self.cutout = fits.open(manifest['Local Path'][0])\n\n print('This is the first light curve you have made for this sector. Getting eleanor metadata products for Sector {0:2d}...'.format(self.sector))\n print('This will only take a minute, and only needs to be done once. Any other light curves you make in this sector will be faster.')\n self.get_target()\n print('Target Acquired')\n self.get_cadences()\n print('Cadences Calculated')\n self.get_quality()\n print('Quality Flags Assured')\n self.get_cbvs()\n print('CBVs Made')\n print('Success! Sector {:2d} now available.'.format(self.sector))\n os.remove(manifest['Local Path'][0])\n self.try_next_sector()\n\n def get_cbvs(self):\n if self.sector <= 6:\n year = 2018\n elif self.sector <= 20:\n year = 2019\n else:\n year = 2020\n\n\n url = 'https://archive.stsci.edu/missions/tess/ffi/s{0:04d}/{1}/'.format(self.sector, year)\n\n directs = []\n for file in listFD(url):\n directs.append(file)\n directs = np.sort(directs)[1::]\n\n subdirects = []\n for file in listFD(directs[0]):\n subdirects.append(file)\n subdirects = np.sort(subdirects)[1:-4]\n for i in range(len(subdirects)):\n file = listFD(subdirects[i], ext='cbv.fits')[0]\n os.system('curl -O -L {}'.format(file))\n\n time = self.cutout[1].data['TIME'] - self.cutout[1].data['TIMECORR']\n\n files = os.listdir('.')\n files = [i for i in files if i.endswith('cbv.fits') and 's{0:04d}'.format(self.sector) in i]\n\n for c in range(len(files)):\n cbv = fits.open(files[c])\n camera = cbv[1].header['CAMERA']\n ccd = cbv[1].header['CCD']\n cbv_time = cbv[1].data['Time']\n\n new_fn = eleanorpath + '/metadata/s{0:04d}/cbv_components_s{0:04d}_{1:04d}_{2:04d}.txt'.format(self.sector, camera, ccd)\n\n convolved = np.zeros((len(time), 16))\n inds = np.array([], dtype=int)\n for i in range(len(time)):\n g = np.argmin( np.abs(time[i] -cbv_time) )\n for j in range(16):\n index = 'VECTOR_{0}'.format(j+1)\n cads = np.arange(g-7, g+8,1)\n convolved[i,j] = np.mean(cbv[1].data[index][cads])\n np.savetxt(new_fn, convolved)\n cbv.close()\n files = [i for i in files if i.endswith('cbv.fits') and 's{0:04d}'.format(self.sector) in i]\n for c in range(len(files)):\n os.remove(files[c])\n\n\n def try_next_sector(self):\n codepath = os.path.dirname(__file__)\n f1 = open(codepath + '/maxsector.py', 'r')\n oldmax = float(f1.readline().split('=')[-1])\n if self.sector > oldmax:\n f = open(codepath + '/maxsector.py', 'w')\n f.write('maxsector = {:2d}'.format(self.sector))\n f.close()\n\n\n def get_target(self):\n filelist = urlopen('https://archive.stsci.edu/missions/tess/download_scripts/sector/tesscurl_sector_{:d}_lc.sh'.\n format(self.sector))\n for line in filelist:\n if len(str(line)) > 30:\n import shutil\n os.system(str(line)[2:-3])\n fn = str(line)[2:-3].split()[5]\n shutil.move(fn, eleanorpath + '/metadata/s{0:04d}/target_s{0:04d}.fits'.format(self.sector, self.sector))\n break\n return\n\n def get_cadences(self):\n index_zeropoint = 12680\n index_t0 = 1491.625533688852\n\n times = np.array([], dtype=int)\n filelist = urlopen('https://archive.stsci.edu/missions/tess/download_scripts/sector/tesscurl_sector_{:d}_ffic.sh'.\n format(self.sector))\n for line in filelist:\n if len(str(line)) > 30:\n times = np.append(times, int(str(line).split('tess')[1][0:13]))\n\n times = np.sort(np.unique(times))\n\n outarr = np.zeros_like(times)\n for i in range(len(times)):\n date = datetime.strptime(str(times[i]), '%Y%j%H%M%S')\n days = date.day + hmsm_to_days(date.hour,date.minute,date.second,date.microsecond)\n tjd = date_to_jd(date.year,date.month,days) - 2457000\n cad = (tjd - index_t0)/(30./1440.)\n outarr[i] = (int(np.round(cad))+index_zeropoint)\n\n np.savetxt(eleanorpath + '/metadata/s{0:04d}/cadences_s{0:04d}.txt'.format(self.sector, self.sector), outarr, fmt='%i')\n return\n\n\n def get_quality(self):\n \"\"\" Uses the quality flags in a 2-minute target to create quality flags\n in the postcards.\n \"\"\"\n\n ffi_time = self.cutout[1].data['TIME'] - self.cutout[1].data['TIMECORR']\n\n\n shortCad_fn = eleanorpath + '/metadata/s{0:04d}/target_s{0:04d}.fits'.format(self.sector)\n\n # Binary string for values which apply to the FFIs\n ffi_apply = int('100010101111', 2)\n\n # Obtains information for 2-minute target\n twoMin = fits.open(shortCad_fn)\n twoMinTime = twoMin[1].data['TIME']-twoMin[1].data['TIMECORR']\n finite = np.isfinite(twoMinTime)\n twoMinQual = twoMin[1].data['QUALITY']\n\n twoMinTime = twoMinTime[finite]\n twoMinQual = twoMinQual[finite]\n\n convolve_ffi = []\n nodata = np.zeros_like(ffi_time)\n for i in range(len(ffi_time)):\n where = np.where(np.abs(ffi_time[i] - twoMinTime) == np.min(np.abs(ffi_time[i] - twoMinTime)))[0][0]\n\n sflux = np.sum(self.cutout[1].data['FLUX'][i])\n if sflux == 0:\n nodata[i] = 4096\n\n if (ffi_time[i] > 1420) and (ffi_time[i] < 1424):\n nodata[i] = 4096\n\n v = np.bitwise_or.reduce(twoMinQual[where-7:where+8])\n convolve_ffi.append(v)\n\n\n convolve_ffi = np.array(convolve_ffi)\n\n flags = np.bitwise_and(convolve_ffi, ffi_apply)\n\n np.savetxt(eleanorpath + '/metadata/s{0:04d}/quality_s{0:04d}.txt'.format(self.sector), flags+nodata, fmt='%i')\n\n return\n"
] |
[
[
"numpy.abs",
"numpy.isfinite",
"numpy.unique",
"numpy.arange",
"numpy.sort",
"numpy.bitwise_or.reduce",
"numpy.round",
"numpy.bitwise_and",
"numpy.zeros_like",
"numpy.mean",
"numpy.savetxt",
"numpy.array",
"numpy.sum"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
johnmartinsson/adversarial-representation-learning
|
[
"86cd1489b0bdfa76bab37e313c6ab53304179f1e",
"86cd1489b0bdfa76bab37e313c6ab53304179f1e",
"86cd1489b0bdfa76bab37e313c6ab53304179f1e"
] |
[
"vis/create_attributes_experiment_plot.py",
"vis/create_adversarial_plot.py",
"data/preprocess_annotations.py"
] |
[
"import os\nimport pickle\nimport json\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\ndef scatterplot(attribute_idx, table, epsilons, label, ax):\n ys = []\n xs = []\n for eps in epsilons:\n row = table[eps]\n y = row[attribute_idx]\n ys.append(y)\n xs.append(float(eps))\n ax.scatter(x=xs, y=ys, label=label)\n\n\ndef main():\n artifacts_dir = 'artifacts/attributes_experiment/'\n epsilons = ['0.001', '0.005', '0.01', '0.05']\n attributes = ['Smiling', 'Male', 'Wearing_Lipstick', 'Young']\n\n mean_table = {}\n std_table = {}\n for eps in epsilons:\n mean_table[eps] = []\n std_table[eps] = []\n for attr in attributes:\n gen_secret_accs = []\n for i in range(5):\n results_path = os.path.join(artifacts_dir,\n '{}_eps_{}'.format(attr, eps), str(i), 'results.json')\n with open(results_path, 'r') as f:\n res = json.load(f)\n gen_secret_accs.append(res['gen_secret_acc'] * 100)\n mean_table[eps].append(np.mean(gen_secret_accs))\n std_table[eps].append(np.std(gen_secret_accs))\n\n plt.rcParams[\"mathtext.fontset\"] = \"cm\"\n fig, ax = plt.subplots()\n for i, attr in enumerate(attributes):\n scatterplot(i, mean_table, epsilons, label=attr, ax=ax)\n\n plt.ylabel(\"Fool fixed classifier [%]\")\n plt.xlabel(\"$\\epsilon$\")\n plt.legend(loc=\"lower right\")\n plt.savefig(\"fool_fixed_classifier.pdf\")\n\nif __name__ == '__main__':\n main()\n",
"import os\nimport pickle\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\ndef scatterplot(attribute_idx, table, epsilons, marker, color, label, ax):\n ys = []\n xs = []\n for eps in epsilons:\n row = table[eps]\n y = row[attribute_idx]\n ys.append(y)\n xs.append(float(eps))\n ax.scatter(x=xs, y=ys, marker=marker, color=color, label=label)\n\ndef main():\n artifacts_dir = 'artifacts/attributes_experiment/'\n baseline_dir = 'artifacts/attributes_baseline_experiment/'\n epsilons = ['0.001', '0.005', '0.01', '0.05']\n attributes = ['Male', 'Wearing_Lipstick', 'Young']\n\n mean_table_ours = {}\n mean_table_bline = {}\n for eps in epsilons:\n mean_table_ours[eps] = []\n mean_table_bline[eps] = []\n for attr in attributes:\n ours_adv_secret_accs = []\n bline_adv_secret_accs = []\n for i in range(5):\n ours_path = os.path.join(artifacts_dir,\n '{}_eps_{}'.format(attr, eps), str(i), 'results.json')\n bline_path = os.path.join(baseline_dir,\n '{}_eps_{}'.format(attr, eps), str(i), 'results.json')\n with open(ours_path, 'r') as f:\n ours_res = json.load(f)\n with open(bline_path, 'r') as f:\n bline_res = json.load(f)\n\n ours_adv_secret_accs.append(ours_res['secret_adv_acc'] * 100)\n bline_adv_secret_accs.append(bline_res['secret_adv_acc'] * 100)\n\n mean_table_ours[eps].append(np.mean(ours_adv_secret_accs))\n mean_table_bline[eps].append(np.mean(bline_adv_secret_accs))\n\n colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']\n\n fig, ax = plt.subplots()\n for i, attr in enumerate(attributes):\n scatterplot(i, mean_table_ours, epsilons, marker='o', color=colors[i],\n label=\"{}\".format(attr), ax=ax)\n scatterplot(i, mean_table_bline, epsilons, marker='x', color=colors[i],\n label=\"\".format(attr), ax=ax)\n plt.legend(loc='lower left')\n plt.ylabel(\"Adv. smiling accuracy [%]\")\n plt.xlabel(r'$\\epsilon$')\n plt.show()\n\nif __name__ == '__main__':\n main()\n",
"import numpy as np\nimport pandas as pd\n\ndef load_annotation_file_as_dataframe(annotation_file):\n with open(annotation_file, 'r') as f:\n lines = f.readlines()\n columns = ['filename'] + lines[1].strip().split(' ')\n data = []\n for l in lines[2:]:\n data.append(list(filter(lambda x: len(x) > 0, l.strip().split(' '))))\n df = pd.DataFrame(np.array(data), columns=columns)\n\n return df\n\ndef load_partition_file_as_dataframe(partition_file):\n with open(partition_file, 'r') as f:\n lines = f.readlines()\n columns = ['filename', 'subset']\n data = []\n\n for l in lines:\n data.append(l.strip().split(' '))\n df = pd.DataFrame(np.array(data), columns=columns)\n\n return df\n\ndef main():\n annotation_frame = load_annotation_file_as_dataframe('annotations.txt')\n data_split_frame = load_partition_file_as_dataframe('data_split.txt')\n nb_training_samples = (data_split_frame['subset'] == '0').sum()\n nb_validation_samples = (data_split_frame['subset'] == '1').sum()\n nb_test_samples = (data_split_frame['subset'] == '2').sum()\n\n train_idx_begin = 0\n train_idx_end = nb_training_samples\n valid_idx_begin = train_idx_end\n valid_idx_end = valid_idx_begin + nb_validation_samples\n test_idx_begin = valid_idx_end\n test_idx_end = test_idx_begin + nb_test_samples\n\n training_annotations_frame = annotation_frame[train_idx_begin:train_idx_end]\n validation_annotations_frame = annotation_frame[valid_idx_begin:valid_idx_end]\n test_annotations_frame = annotation_frame[test_idx_begin:test_idx_end]\n\n training_annotations_frame.to_csv('training_annotations.csv')\n validation_annotations_frame.to_csv('validation_annotations.csv')\n test_annotations_frame.to_csv('test_annotations.csv')\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.std",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
],
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.subplots",
"numpy.mean",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
],
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
silence0201/Learn-Python
|
[
"662da7c0e74221cedb445ba17d5cb1cd3af41c86",
"662da7c0e74221cedb445ba17d5cb1cd3af41c86"
] |
[
"Others/Source/19/19.5/plot_guangzhou_weather_net.py",
"Others/Source/19/19.1/plot_subplot.py"
] |
[
"# coding: utf-8\r\n#########################################################################\r\n# 网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a> #\r\n# author yeeku.H.lee [email protected] #\r\n# #\r\n# version 1.0 #\r\n# #\r\n# Copyright (C), 2001-2018, yeeku.H.Lee #\r\n# #\r\n# This program is protected by copyright laws. #\r\n# #\r\n# Program Name: #\r\n# #\r\n# <br>Date: #\r\n#########################################################################\r\nimport re\r\nfrom datetime import datetime\r\nfrom datetime import timedelta\r\nfrom matplotlib import pyplot as plt\r\nfrom urllib.request import *\r\n\r\n# 定义一个函数读取lishi.tianqi.com的数据\r\ndef get_html(city, year, month): #①\r\n url = 'http://lishi.tianqi.com/' + city + '/' + str(year) + str(month) + '.html'\r\n # 创建请求\r\n request = Request(url)\r\n # 添加请求头\r\n request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64)' +\r\n 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36')\r\n response = urlopen(request)\r\n # 获取服务器响应\r\n return response.read().decode('gbk')\r\n \r\n# 定义3个list列表作为展示的数据\r\ndates, highs, lows = [], [], []\r\ncity = 'guangzhou'\r\nyear = '2017'\r\nmonths = ['01', '02', '03', '04', '05', '06', '07', \r\n '08', '09', '10', '11', '12']\r\nprev_day = datetime(2016, 12, 31)\r\n# 循环读取每个月的天气数据\r\nfor month in months:\r\n html = get_html(city, year, month)\r\n # 将html响应拼起来\r\n text = \"\".join(html.split())\r\n # 定义包含天气信息的div的正则表达式\r\n patten = re.compile('<divclass=\"tqtongji2\">(.*?)</div><divstyle=\"clear:both\">')\r\n table = re.findall(patten, text)\r\n patten1 = re.compile('<ul>(.*?)</ul>')\r\n uls = re.findall(patten1, table[0])\r\n for ul in uls:\r\n # 定义解析天气信息的正则表达式\r\n patten2 = re.compile('<li>(.*?)</li>')\r\n lis = re.findall(patten2, ul)\r\n # 解析得到日期数据\r\n d_str = re.findall('>(.*?)</a>', lis[0])[0]\r\n try:\r\n # 将日期字符串格式化为日期\r\n cur_day = datetime.strptime(d_str, '%Y-%m-%d')\r\n # 解析得到最高气温和最低气温\r\n high = int(lis[1])\r\n low = int(lis[2])\r\n except ValueError:\r\n print(cur_day, '数据出现错误')\r\n else:\r\n # 计算前、后两天数据的时间差\r\n diff = cur_day - prev_day\r\n # 如果前、后两天数据的时间差不是相差一天,说明数据有问题\r\n if diff != timedelta(days=1):\r\n print('%s之前少了%d天的数据' % (cur_day, diff.days - 1))\r\n dates.append(cur_day)\r\n highs.append(high)\r\n lows.append(low)\r\n prev_day = cur_day\r\n# 配置图形\r\nfig = plt.figure(dpi=128, figsize=(12, 9))\r\n# 绘制最高气温的折线\r\nplt.plot(dates, highs, c='red', label='最高气温', \r\n alpha=0.5, linewidth = 2.0)\r\n# 再绘制一条折线\r\nplt.plot(dates, lows, c='blue', label='最低气温',\r\n alpha=0.5, linewidth = 2.0)\r\n# 为两个数据的绘图区域填充颜色\r\nplt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)\r\n# 设置标题\r\nplt.title(\"广州%s年最高气温和最低气温\" % year)\r\n# 为两条坐标轴设置名称\r\nplt.xlabel(\"日期\")\r\n# 该方法绘制斜着的日期标签\r\nfig.autofmt_xdate()\r\nplt.ylabel(\"气温(℃)\")\r\n# 显示图例\r\nplt.legend()\r\nax = plt.gca()\r\n# 设置右边坐标轴线的颜色(设置为none表示不显示)\r\nax.spines['right'].set_color('none')\r\n# 设置顶部坐标轴线的颜色(设置为none表示不显示)\r\nax.spines['top'].set_color('none')\r\nplt.show()\r\n",
"# coding: utf-8\r\n#########################################################################\r\n# 网站: <a href=\"http://www.crazyit.org\">疯狂Java联盟</a> #\r\n# author yeeku.H.lee [email protected] #\r\n# #\r\n# version 1.0 #\r\n# #\r\n# Copyright (C), 2001-2018, yeeku.H.Lee #\r\n# #\r\n# This program is protected by copyright laws. #\r\n# #\r\n# Program Name: #\r\n# #\r\n# <br>Date: #\r\n#########################################################################\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nplt.figure()\r\n# 定义从-pi到pi之间的数据,平均取64个数据点\r\nx_data = np.linspace(-np.pi, np.pi, 64, endpoint=True) # ①\r\n# 将整个figure分成两行两列,第三个参数表示该图形放在第1个网格\r\nplt.subplot(2, 2, 1)\r\n# 绘制正弦曲线\r\nplt.plot(x_data, np.sin(x_data))\r\nplt.gca().spines['right'].set_color('none')\r\nplt.gca().spines['top'].set_color('none')\r\nplt.gca().spines['bottom'].set_position(('data', 0))\r\nplt.gca().spines['left'].set_position(('data', 0))\r\nplt.title('正弦曲线')\r\n\r\n# 将整个figure分成两行两列,并将该图形放在第2个网格\r\nplt.subplot(222)\r\n# 绘制余弦曲线\r\nplt.plot(x_data, np.cos(x_data))\r\nplt.gca().spines['right'].set_color('none')\r\nplt.gca().spines['top'].set_color('none')\r\nplt.gca().spines['bottom'].set_position(('data', 0))\r\nplt.gca().spines['left'].set_position(('data', 0))\r\nplt.title('余弦曲线')\r\n\r\n# 将整个figure分成两行两列,并该图形放在第3个网格\r\nplt.subplot(223)\r\n# 绘制正切曲线\r\nplt.plot(x_data, np.tan(x_data))\r\nplt.gca().spines['right'].set_color('none')\r\nplt.gca().spines['top'].set_color('none')\r\nplt.gca().spines['bottom'].set_position(('data', 0))\r\nplt.gca().spines['left'].set_position(('data', 0))\r\nplt.title('正切曲线')\r\n\r\nplt.show()"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.fill_between",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
],
[
"matplotlib.pyplot.gca",
"matplotlib.pyplot.title",
"numpy.linspace",
"numpy.cos",
"numpy.sin",
"numpy.tan",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DizzyYunxuan/FlappyBird
|
[
"4a078edff0d2276a717c437032cdbcebf33366f3",
"4a078edff0d2276a717c437032cdbcebf33366f3"
] |
[
"edge_detect_template_single_test.py",
"edge_detect_template.py"
] |
[
"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom scipy import ndimage\nimport time\nimport os\n\n\n\n\ndef get_decisionMap(img):\n img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n img = img_gray[34:434, 8:-8]\n [h, w] = img.shape\n\n\n # lap kernel\n k = np.array([[-1, -1, -1],\n [-1, 8, -1],\n [-1, -1, -1]])\n\n # remove holes in ob\n s_k = np.ones([3, 3]) / 9\n img_edge = cv2.filter2D(cv2.filter2D(img, -1, k), -1, s_k)\n img_seg = img_edge != 0.0\n img_seg = img_seg.astype(np.float64)\n ls_k = np.ones([1, 7]) / 7\n img_seg = cv2.copyMakeBorder(img_seg, 3, 3, 3, 3, borderType=cv2.BORDER_CONSTANT, value=1)\n img_seg = cv2.filter2D(img_seg, -1, ls_k, borderType=cv2.BORDER_REFLECT)[3:-3, 3:-3]\n img_seg = img_seg > 0\n img_seg = img_seg.astype(np.float64)\n\n # remove holes in bg\n img_seg = cv2.filter2D(img_seg, -1, ls_k, borderType=cv2.BORDER_REFLECT)\n img_seg = img_seg > 0.9\n img_seg = img_seg.astype(np.float64)\n ll_sk = np.ones([9, 9]) / 81\n img_seg = cv2.filter2D(img_seg, -1, ll_sk, borderType=cv2.BORDER_REFLECT)\n img_seg = img_seg > 0.999\n img_seg = img_seg.astype(np.float64)\n\n # remove scores\n img_seg[45:90, 125:160] = 1\n\n decision_map = np.zeros_like(img_edge)\n\n # get horizontal obs\n h_strip = img_seg[16, :]\n h_sePoints = h_strip[1:] - h_strip[:-1]\n h_start_Points = np.argwhere(h_sePoints > 0).flatten()\n h_end_Points = np.argwhere(h_sePoints < 0).flatten()\n\n if h_start_Points.shape[0] < 1 and h_end_Points.shape[0] < 1:\n num_ob = 0\n elif h_start_Points.shape[0] < 1:\n num_ob = 1\n h_start_Points = np.append(0, h_start_Points)\n elif h_end_Points.shape[0] < 1:\n num_ob = 1\n h_end_Points = np.append(h_end_Points, w)\n else:\n if h_start_Points[0] > h_end_Points[0]:\n h_start_Points = np.append(0, h_start_Points)\n if h_start_Points[-1] > h_end_Points[-1]:\n h_end_Points = np.append(h_end_Points, w)\n num_ob = len(h_start_Points)\n \n\n # get vertical space\n h_ob_lr_dict = {}\n v_space_ub_dict = {}\n for i in range(num_ob):\n h_ob_lr_dict[i] = [h_start_Points[i], h_end_Points[i]]\n left, right = h_ob_lr_dict[i]\n decision_map[:, left:right] = 1\n v_strip = img_seg[:, np.int32((left + right) / 2)]\n v_sePoints = v_strip[1:] - v_strip[:-1]\n v_bot_Points = np.argwhere(v_sePoints < 0)\n v_upper_Points = np.argwhere(v_sePoints > 0)\n sps_upper = np.min(v_bot_Points)\n sps_bot = np.max(v_upper_Points)\n v_space_ub_dict[i] = [sps_upper, sps_bot]\n decision_map[sps_upper:sps_bot, left:right] = 0\n\n\n\n bird_map = img_seg - decision_map\n bird_map = (bird_map > 0).astype(np.float32)\n bird_strip = bird_map[:, 50:100]\n b_k = np.ones([10, 10])\n bird_strip = cv2.filter2D(bird_strip, -1, b_k)\n bird_loc = np.argwhere(bird_strip > 99)\n\n\n\n # upper, bot, left, right\n if bird_loc.shape[0]:\n x_bird = bird_loc[0, 0]\n bird_x, bird_y = x_bird + 20, 70\n bird_bounding_box = np.array([x_bird, x_bird + 20, 55, 85])\n decision_map[bird_bounding_box[0]:bird_bounding_box[1], bird_bounding_box[2]:bird_bounding_box[3]] = 1\n else:\n raise(ValueError(\"No bird detected!\"))\n\n return decision_map, bird_x, bird_y, h_ob_lr_dict, v_space_ub_dict\n\n\n\nif __name__ == '__main__':\n import time\n\n img_path = r'D:\\anaconda\\flappy_ai\\FlapPyBird\\datasets\\test_png_4\\test_28.png'\n img_gray = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n s = time.time()\n decision_map = get_decisionMap(img_gray)\n e = time.time()\n print(\"Time: {}\".format(e-s))\n\n\n\n\n\n\n\n",
"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom scipy import ndimage\nimport time\nimport os\nfrom edge_detect_template_single_test import get_decisionMap\n\n\n\n# def get_decisionMap(img_gray):\n# img = img_gray[34:434, 8:-8]\n# [h, w] = img.shape\n\n\n# # lap kernel\n# k = np.array([[-1, -1, -1],\n# [-1, 8, -1],\n# [-1, -1, -1]])\n\n# # remove holes in ob\n# s_k = np.ones([3, 3]) / 9\n# img_edge = cv2.filter2D(cv2.filter2D(img, -1, k), -1, s_k)\n# img_seg = img_edge != 0.0\n# img_seg = img_seg.astype(np.float64)\n# ls_k = np.ones([7, 7]) / 49\n# img_seg = cv2.copyMakeBorder(img_seg, 3, 3, 3, 3, borderType=cv2.BORDER_CONSTANT, value=1)\n# img_seg = cv2.filter2D(img_seg, -1, ls_k, borderType=cv2.BORDER_REFLECT)[3:-3, 3:-3]\n# img_seg = img_seg > 0\n# img_seg = img_seg.astype(np.float64)\n\n# # remove holes in bg\n# img_seg = cv2.filter2D(img_seg, -1, ls_k, borderType=cv2.BORDER_REFLECT)\n# img_seg = img_seg > 0.9\n# img_seg = img_seg.astype(np.float64)\n# ll_sk = np.ones([9, 9]) / 81\n# img_seg = cv2.filter2D(img_seg, -1, ll_sk, borderType=cv2.BORDER_REFLECT)\n# img_seg = img_seg > 0.999\n# img_seg = img_seg.astype(np.float64)\n\n# # shrink for edges\n# img_seg = cv2.filter2D(img_seg, -1, s_k)\n# img_seg = img_seg > 0.0\n# img_seg = img_seg.astype(np.float64)\n\n\n# decision_map = np.zeros_like(img_edge)\n\n# # get horizontal obs\n# h_strip = img_seg[16, :]\n# h_sePoints = h_strip[1:] - h_strip[:-1]\n# h_start_Points = np.argwhere(h_sePoints > 0).flatten()\n# h_end_Points = np.argwhere(h_sePoints < 0).flatten()\n\n\n\n\n# if h_end_Points.shape[0] < 1 and h_start_Points.shape[0] < 1:\n# num_ob = 0\n# elif h_start_Points.shape[0] < 1:\n# num_ob = 0\n# else:\n# num_ob = 1\n# h_end_Points = np.append(h_end_Points, w)\n\n# # get vertical space\n# # num_ob = h_start_Points.shape[0]\n# h_ob_lr_dict = {}\n# for i in range(num_ob):\n# h_ob_lr_dict[i] = [h_start_Points[i], h_end_Points[i]]\n# left, right = h_ob_lr_dict[i]\n# decision_map[:, left:right] = 1\n# v_strip = img_seg[:, np.int32((left + right) / 2)]\n# v_sePoints = v_strip[1:] - v_strip[:-1]\n# v_bot_Points = np.argwhere(v_sePoints < 0)\n# v_upper_Points = np.argwhere(v_sePoints > 0)\n# sps_upper = np.min(v_bot_Points)\n# sps_bot = np.max(v_upper_Points)\n# decision_map[sps_upper:sps_bot, left:right] = 0\n\n\n\n# bird_map = img_seg - decision_map\n# bird_map = (bird_map > 0).astype(np.float32)\n# bird_strip = bird_map[:, 50:100]\n# b_k = np.ones([10, 10])\n# bird_strip = cv2.filter2D(bird_strip, -1, b_k)\n# bird_loc = np.argwhere(bird_strip > 99)\n\n\n\n# # upper, bot, left, right\n# x_bird = bird_loc[0, 0]\n# bird_bounding_box = np.array([x_bird - 5, x_bird + 25, 50, 85])\n# decision_map[bird_bounding_box[0]:bird_bounding_box[1], bird_bounding_box[2]:bird_bounding_box[3]] = 1\n\n# return decision_map\n\n\n\nif __name__ == '__main__':\n test_sequence_path = r'D:\\anaconda\\flappy_ai\\FlapPyBird\\datasets\\test_png_5'\n res_path = r'D:\\anaconda\\flappy_ai\\FlapPyBird\\datasets\\test_png_5_results'\n\n if not os.path.exists(res_path):\n os.mkdir(res_path)\n\n for i in os.listdir(test_sequence_path):\n img_path = os.path.join(test_sequence_path, i)\n img_gray = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n decision_map = get_decisionMap(img_gray)\n decision_map_uint8 = np.uint8(decision_map * 255)\n cv2.imwrite(os.path.join(res_path, i), decision_map_uint8)\n print(\"current frames: {}\".format(i))\n\n\n # plt.figure()\n # plt.imshow(decision_map, 'gray')\n # plt.figure()\n # plt.imshow(img_gray, 'gray')\n\n # print()\n\n\n\n\n\n\n"
] |
[
[
"numpy.min",
"numpy.int32",
"numpy.argwhere",
"numpy.ones",
"numpy.max",
"numpy.append",
"numpy.zeros_like",
"numpy.array"
],
[
"numpy.uint8"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ProGamerCode/FitML
|
[
"3b44160bbf6c0587b8df198d3ceef10a42e2bfca",
"3b44160bbf6c0587b8df198d3ceef10a42e2bfca"
] |
[
"QLearning/LunarLander_v2.py",
"ActorCritic/LunarLander_ActorCritic.py"
] |
[
"'''\nLunarLander-v2 solution by Michel Aka\nhttps://github.com/FitMachineLearning/FitML/\nhttps://www.youtube.com/channel/UCi7_WxajoowBl4_9P0DhzzA/featured\nUsing Modified Q Learning, Bellman, Reinforcement Learning, RL memory\n\n'''\nimport numpy as np\nimport keras\nimport gym\nimport os\nimport h5py\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.layers import Embedding\nfrom keras import optimizers\n\n\nnum_env_variables = 8\nnum_env_actions = 4\nnum_initial_observation = 15\nlearning_rate = 0.003\nweigths_filename = \"LL-QL-v2-weights.h5\"\n\nb_discount = 0.99\nmax_memory_len = 60000\nstarting_explore_prob = 0.05\ntraining_epochs = 3\nload_previous_weights = True\nobserve_and_train = True\nsave_weights = True\nnum_games_to_play = 1000\n\n\n#One hot encoding array\npossible_actions = np.arange(0,num_env_actions)\nactions_1_hot = np.zeros((num_env_actions,num_env_actions))\nactions_1_hot[np.arange(num_env_actions),possible_actions] = 1\n\n#Create testing enviroment\nenv = gym.make('LunarLander-v2')\nenv.reset()\n\n#initialize training matrix with random states and actions\ndataX = np.random.random(( 5,num_env_variables+num_env_actions ))\n#Only one output for the total score\ndataY = np.random.random((5,1))\n\n\n\n#nitialize the Neural Network with random weights\n\nmodel = Sequential()\n#model.add(Dense(num_env_variables+num_env_actions, activation='tanh', input_dim=dataX.shape[1]))\nmodel.add(Dense(512, activation='relu', input_dim=dataX.shape[1]))\nmodel.add(Dense(256, activation='relu' ))\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(dataY.shape[1]))\n\nopt = optimizers.adam(lr=learning_rate)\n\nmodel.compile(loss='mse', optimizer=opt, metrics=['accuracy'])\n\n#load previous model weights if they exist\nif load_previous_weights:\n dir_path = os.path.realpath(\".\")\n fn = dir_path + \"/\"+weigths_filename\n print(\"filepath \", fn)\n if os.path.isfile(fn):\n print(\"loading weights\")\n model.load_weights(weigths_filename)\n else:\n print(\"File \",weigths_filename,\" does not exis. Retraining... \")\n\n#Initialize training data array\ntotal_steps = 0\ndataX = np.zeros(shape=(1,num_env_variables+num_env_actions))\ndataY = np.zeros(shape=(1,1))\n\n#Initialize Memory Array data array\nmemoryX = np.zeros(shape=(1,num_env_variables+num_env_actions))\nmemoryY = np.zeros(shape=(1,1))\n\n\nprint(\"dataX shape\", dataX.shape)\nprint(\"dataY shape\", dataY.shape)\n\n\n#This function predicts the reward that will result from taking an \"action\" at a state \"qstate\"\ndef predictTotalRewards(qstate, action):\n qs_a = np.concatenate((qstate,actions_1_hot[action]), axis=0)\n predX = np.zeros(shape=(1,num_env_variables+num_env_actions))\n predX[0] = qs_a\n\n #print(\"trying to predict reward at qs_a\", predX[0])\n pred = model.predict(predX[0].reshape(1,predX.shape[1]))\n remembered_total_reward = pred[0][0]\n return remembered_total_reward\n\n\n\nif observe_and_train:\n\n #Play the game a determine number of times\n for game in range(num_games_to_play):\n gameX = np.zeros(shape=(1,num_env_variables+num_env_actions))\n gameY = np.zeros(shape=(1,1))\n #Get the initial Q state\n qs = env.reset()\n for step in range (40000):\n\n #Learn from observation and not playing\n if game < num_initial_observation:\n #take a radmon action\n a = env.action_space.sample()\n else:\n #Now playing and also learning from experience during play\n\n #Calculate probability to take deterministic action vs random action (epsilon)\n prob = np.random.rand(1)\n explore_prob = starting_explore_prob-(starting_explore_prob/num_games_to_play)*game\n\n #Chose between prediction and chance\n if prob < explore_prob:\n #take a random action\n a=env.action_space.sample()\n #print(\"taking random action\",a, \"at total_steps\" , total_steps)\n #print(\"prob \", prob, \"explore_prob\", explore_prob)\n\n else:\n ##chose an action by estimating the function-estimator remembered consequences of all possible actions\n ## Bellman states that the best policy (i.e. action) is the one that maximizez expected rewards for future states\n ## to caculate rewards we compute the reward a this state t + the discounted (b_discount) reward at all possible state t+1\n ## all states t+1 are estimated by our function estimator (our Neural Network)\n\n\n utility_possible_actions = np.zeros(shape=(num_env_actions))\n\n utility_possible_actions[0] = predictTotalRewards(qs,0)\n utility_possible_actions[1] = predictTotalRewards(qs,1)\n utility_possible_actions[2] = predictTotalRewards(qs,2)\n utility_possible_actions[3] = predictTotalRewards(qs,3)\n\n\n #chose argmax action of estimated anticipated rewards\n #print(\"utility_possible_actions \",utility_possible_actions)\n #print(\"argmax of utitity\", np.argmax(utility_possible_actions))\n a = np.argmax(utility_possible_actions)\n\n\n\n env.render()\n qs_a = np.concatenate((qs,actions_1_hot[a]), axis=0)\n\n #print(\"action\",a,\" qs_a\",qs_a)\n #Perform the optimal action and get the target state and reward\n s,r,done,info = env.step(a)\n\n\n #record information for training and memory\n if step ==0:\n gameX[0] = qs_a\n gameY[0] = np.array([r])\n memoryX[0] = qs_a\n memoryY[0] = np.array([r])\n\n gameX = np.vstack((gameX,qs_a))\n gameY = np.vstack((gameY,np.array([r])))\n\n\n if done :\n #GAME ENDED\n #Calculate Q values from end to start of game (From last step to first)\n for i in range(0,gameY.shape[0]):\n #print(\"Updating total_reward at game epoch \",(gameY.shape[0]-1) - i)\n if i==0:\n #print(\"reward at the last step \",gameY[(gameY.shape[0]-1)-i][0])\n gameY[(gameY.shape[0]-1)-i][0] = gameY[(gameY.shape[0]-1)-i][0]\n else:\n #print(\"local error before Bellman\", gameY[(gameY.shape[0]-1)-i][0],\"Next error \", gameY[(gameY.shape[0]-1)-i+1][0])\n gameY[(gameY.shape[0]-1)-i][0] = gameY[(gameY.shape[0]-1)-i][0]+b_discount*gameY[(gameY.shape[0]-1)-i+1][0]\n #print(\"reward at step\",i,\"away from the end is\",gameY[(gameY.shape[0]-1)-i][0])\n if i==gameY.shape[0]-1 and game%5==0:\n print(\"Training Game #\",game, \" steps = \", step ,\"last reward\", r,\" finished with headscore \", gameY[(gameY.shape[0]-1)-i][0])\n\n if memoryX.shape[0] ==1:\n memoryX = gameX\n memoryY = gameY\n else:\n #Add experience to memory\n memoryX = np.concatenate((memoryX,gameX),axis=0)\n memoryY = np.concatenate((memoryY,gameY),axis=0)\n\n #if memory is full remove first element\n if np.alen(memoryX) >= max_memory_len:\n #print(\"memory full. mem len \", np.alen(memoryX))\n for l in range(np.alen(gameX)):\n memoryX = np.delete(memoryX, 0, axis=0)\n memoryY = np.delete(memoryY, 0, axis=0)\n\n #Update the states\n qs=s\n\n #Retrain every X game after num_initial_observation\n if done and game >= num_initial_observation:\n if game%10 == 0:\n print(\"Training game# \", game,\"momory size\", memoryX.shape[0])\n model.fit(memoryX,memoryY, batch_size=256,nb_epoch=training_epochs,verbose=0)\n\n if done:\n if r >= 0 and r <99:\n print(\"Game \",game,\" ended with positive reward \")\n if r > 50:\n print(\"Game \", game,\" WON *** \" )\n #Game ended - Break\n break\n\n\n\n\n\nif save_weights:\n #Save model\n print(\"Saving weights\")\n model.save_weights(weigths_filename)\n",
"'''\nLunarLander solution by Michel Aka\nhttps://github.com/FitMachineLearning/FitML/\n\nCheck out its performance here.\nhttps://www.youtube.com/watch?v=z9R5hDT6vUQ\n\nUsing Actor Critic\nNote that I prefe the terms Action Predictor Network and Q/Reward Predictor network better\n'''\nimport numpy as np\nimport keras\nimport gym\nimport os\nimport h5py\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.layers import Embedding\nfrom keras.layers import LSTM\nfrom keras import optimizers\n\n\nnum_env_variables = 8\nnum_env_actions = 4\nnum_initial_observation = 10\nlearning_rate = 0.001\nweigths_filename = \"LL-AC-v2-weights.h5\"\napWeights_filename = \"LL_ap-AC-v2-weights.h5\"\n\n#range within wich the SmartCrossEntropy action parameters will deviate from\n#remembered optimal policy\nsce_range = 0.2\nb_discount = 0.999\nmax_memory_len = 6000\nstarting_explore_prob = 0.1\ntraining_epochs = 2\nload_previous_weights = True\nobserve_and_train = True\nsave_weights = True\nnum_games_to_play = 3000\n\n\n#One hot encoding array\npossible_actions = np.arange(0,num_env_actions)\nactions_1_hot = np.zeros((num_env_actions,num_env_actions))\nactions_1_hot[np.arange(num_env_actions),possible_actions] = 1\n\n#Create testing enviroment\nenv = gym.make('LunarLander-v2')\nenv.reset()\n\n#initialize training matrix with random states and actions\ndataX = np.random.random(( 5,num_env_variables+num_env_actions ))\n#Only one output for the total score / reward\ndataY = np.random.random((5,1))\n\n#initialize training matrix with random states and actions\napdataX = np.random.random(( 5,num_env_variables ))\napdataY = np.random.random((5,1))\n\n#nitialize the Reward predictor model\nmodel = Sequential()\n#model.add(Dense(num_env_variables+num_env_actions, activation='tanh', input_dim=dataX.shape[1]))\nmodel.add(Dense(1024, activation='relu', input_dim=dataX.shape[1]))\nmodel.add(Dense(dataY.shape[1]))\n\nopt = optimizers.adam(lr=learning_rate)\n\nmodel.compile(loss='mse', optimizer=opt, metrics=['accuracy'])\n\n\n#initialize the action predictor model\naction_predictor_model = Sequential()\n#model.add(Dense(num_env_variables+num_env_actions, activation='tanh', input_dim=dataX.shape[1]))\naction_predictor_model.add(Dense(1024, activation='relu', input_dim=apdataX.shape[1]))\naction_predictor_model.add(Dense(apdataY.shape[1]))\n\nopt2 = optimizers.adam(lr=learning_rate)\n\naction_predictor_model.compile(loss='mse', optimizer=opt2, metrics=['accuracy'])\n\n\n#load previous model weights if they exist\nif load_previous_weights:\n dir_path = os.path.realpath(\".\")\n fn = dir_path + \"/\"+weigths_filename\n print(\"filepath \", fn)\n if os.path.isfile(fn):\n print(\"loading weights\")\n model.load_weights(weigths_filename)\n else:\n print(\"File \",weigths_filename,\" does not exis. Retraining... \")\n\n#load previous action predictor model weights if they exist\nif load_previous_weights:\n dir_path = os.path.realpath(\".\")\n fn = dir_path + \"/\"+ apWeights_filename\n print(\"filepath \", fn)\n if os.path.isfile(fn):\n print(\"loading weights\")\n action_predictor_model.load_weights(apWeights_filename)\n else:\n print(\"File \",apWeights_filename,\" does not exis. Retraining... \")\n\n\n\n\n\n#Record first 500 in a sequence and add them to the training sequence\ntotal_steps = 0\ndataX = np.zeros(shape=(1,num_env_variables+num_env_actions))\ndataY = np.zeros(shape=(1,1))\n\nmemoryX = np.zeros(shape=(1,num_env_variables+num_env_actions))\nmemoryY = np.zeros(shape=(1,1))\n\napmemoryX = np.zeros(shape=(1,num_env_variables))\napmemoryY = np.zeros(shape=(1,1))\n\nprint(\"dataX shape\", dataX.shape)\nprint(\"dataY shape\", dataY.shape)\n\n\n\ndef predictTotalRewards(qstate, action):\n qs_a = np.concatenate((qstate,actions_1_hot[action]), axis=0)\n predX = np.zeros(shape=(1,num_env_variables+num_env_actions))\n predX[0] = qs_a\n\n #print(\"trying to predict reward at qs_a\", predX[0])\n pred = model.predict(predX[0].reshape(1,predX.shape[1]))\n remembered_total_reward = pred[0][0]\n return remembered_total_reward\n\n\ndef GetRememberedOptimalPolicy(qstate):\n predX = np.zeros(shape=(1,num_env_variables))\n predX[0] = qstate\n\n #print(\"trying to predict reward at qs_a\", predX[0])\n pred = action_predictor_model.predict(predX[0].reshape(1,predX.shape[1]))\n r_remembered_optimal_policy = pred[0]\n return r_remembered_optimal_policy\n\ndef SmartCrossEntropy(current_optimal_policy):\n sce = np.zeros(shape=(num_env_actions))\n #print(\"current_optimal_policy\", current_optimal_policy)\n for i in range(num_env_actions):\n sce[i] = current_optimal_policy[i] + sce_range * (np.random.rand(1)*2 - 1)\n if sce[i] > 1:\n sce[i] = 1.0\n if sce[i] < -1:\n sce[i] = -1\n #print(\"current_optimal_policy\", current_optimal_policy)\n #print(\"sce\", sce)\n return sce\n\n\nif observe_and_train:\n\n #Play the game 500 times\n for game in range(num_games_to_play):\n gameX = np.zeros(shape=(1,num_env_variables+num_env_actions))\n gameY = np.zeros(shape=(1,1))\n #Get the Q state\n qs = env.reset()\n #print(\"qs \", qs)\n if game < num_initial_observation:\n print(\"Observing game \", game)\n else:\n print(\"Learning & playing game \", game)\n for step in range (8000):\n\n if game < num_initial_observation:\n #take a radmon action\n a = env.action_space.sample()\n else:\n prob = np.random.rand(1)\n explore_prob = starting_explore_prob-(starting_explore_prob/num_games_to_play)*game\n\n #Chose between prediction and chance\n if prob < explore_prob:\n #take a random action\n a=env.action_space.sample()\n\n #print(\"taking random action\",a, \"at total_steps\" , total_steps)\n #print(\"prob \", prob, \"explore_prob\", explore_prob)\n\n else:\n ##chose an action by estimating function-estimator remembered consequences of all possible actions\n ## Bellman states that the best policy (i.e. action) is the one that maximizez expected rewards for future states\n ## to caculate rewards we compute the reward a this state t + the discounted (b_discount) reward at all possible state t+1\n ## all states t+1 are estimated by our function estimator (our Neural Network)\n\n #Get Remembered optiomal policy\n remembered_optimal_policy = GetRememberedOptimalPolicy(qs)\n remembered_optimal_policy = remembered_optimal_policy[0]\n remembered_optimal_policy = int(round(remembered_optimal_policy))\n #print(\"remembered_optimal_policy\", remembered_optimal_policy)\n\n if remembered_optimal_policy>3:\n remembered_optimal_policy = 3\n if remembered_optimal_policy < 0:\n remembered_optimal_policy = 0\n '''\n #Generate a set of num_env_action*10\n possible_actions = np.zeros(shape=(num_env_actions*4,num_env_actions))\n utility_possible_actions = np.zeros(shape=(num_env_actions*4))\n for i in range(num_env_actions*4):\n possible_actions[i] = SmartCrossEntropy(remembered_optimal_policy)\n utility_possible_actions[i] = predictTotalRewards(qs,possible_actions[i])\n #print(\"utility_possible_actions\", utility_possible_actions)\n #chose argmax action of estimated anticipated rewards\n #print(\"utility_possible_actions \",utility_possible_actions)\n #print(\"argmax of utitity\", np.argmax(utility_possible_actions))\n best_sce_i = np.argmax(utility_possible_actions)\n '''\n\n randaction = env.action_space.sample()\n\n #Compare R for SmartCrossEntropy action with remembered_optimal_policy and select the best\n #if predictTotalRewards(qs,remembered_optimal_policy) > utility_possible_actions[best_sce_i]:\n if predictTotalRewards(qs,remembered_optimal_policy) > predictTotalRewards(qs,randaction):\n a = remembered_optimal_policy\n #print(\" | selecting remembered_optimal_policy \",a)\n else:\n a = randaction\n #print(\" - selecting generated optimal policy \",a)\n\n\n if a > 3:\n a = 3\n if a < 0:\n a = 0\n\n\n env.render()\n\n #print(\"a after argmax\", a)\n qs_a = np.concatenate((qs,actions_1_hot[a]), axis=0)\n\n #get the target state and reward\n s,r,done,info = env.step(a)\n #record only the first x number of states\n\n\n if step ==0:\n gameX[0] = qs_a\n gameY[0] = np.array([r])\n memoryX[0] = qs_a\n memoryY[0] = np.array([r])\n apmemoryX[0] = qs\n apmemoryY[0] = np.array([a])\n\n gameX = np.vstack((gameX,qs_a))\n gameY = np.vstack((gameY,np.array([r])))\n apmemoryX = np.vstack((apmemoryX,qs))\n apmemoryY = np.vstack((apmemoryY,np.array([a])))\n\n\n\n if done :\n #GAME ENDED\n\n #Calculate Q values from end to start of game\n for i in range(0,gameY.shape[0]):\n #print(\"Updating total_reward at game epoch \",(gameY.shape[0]-1) - i)\n if i==0:\n #print(\"reward at the last step \",gameY[(gameY.shape[0]-1)-i][0])\n gameY[(gameY.shape[0]-1)-i][0] = gameY[(gameY.shape[0]-1)-i][0]\n else:\n #print(\"local error before Bellman\", gameY[(gameY.shape[0]-1)-i][0],\"Next error \", gameY[(gameY.shape[0]-1)-i+1][0])\n gameY[(gameY.shape[0]-1)-i][0] = gameY[(gameY.shape[0]-1)-i][0]+b_discount*gameY[(gameY.shape[0]-1)-i+1][0]\n #print(\"reward at step\",i,\"away from the end is\",gameY[(gameY.shape[0]-1)-i][0])\n if i==gameY.shape[0]-1:\n print(\"Training Game #\",game, \" steps = \", step ,\"last reward\", r,\" finished with headscore \", gameY[(gameY.shape[0]-1)-i][0])\n\n if memoryX.shape[0] ==1:\n memoryX = gameX\n memoryY = gameY\n else:\n #Add experience to memory\n memoryX = np.concatenate((memoryX,gameX),axis=0)\n memoryY = np.concatenate((memoryY,gameY),axis=0)\n\n #if memory is full remove first element\n if np.alen(memoryX) >= max_memory_len:\n #print(\"memory full. mem len \", np.alen(memoryX))\n for l in range(np.alen(gameX)):\n memoryX = np.delete(memoryX, 0, axis=0)\n memoryY = np.delete(memoryY, 0, axis=0)\n apmemoryX = np.delete(apmemoryX, 0 , axis=0)\n apmemoryY = np.delete(apmemoryY, 0 , axis=0)\n\n\n #Update the states\n qs=s\n\n\n #Retrain every X failures after num_initial_observation\n if done and game >= num_initial_observation:\n if game%3 == 0:\n print(\"Training game# \", game,\"momory size\", memoryX.shape[0])\n\n #training Reward predictor model\n model.fit(memoryX,memoryY, batch_size=256,epochs=training_epochs,verbose=2)\n\n #training action predictor model\n action_predictor_model.fit(apmemoryX,apmemoryY, batch_size=256, epochs=training_epochs,verbose=2)\n\n if done and game >= num_initial_observation:\n if save_weights and game%30 == 0:\n #Save model\n print(\"Saving weights\")\n model.save_weights(weigths_filename)\n action_predictor_model.save_weights(apWeights_filename)\n\n if done:\n #Game won conditions\n if r >= 0 and r <99:\n print(\"Game \",game,\" ended with positive reward \")\n if r > 50:\n print(\"Game \", game,\" WON *** \" )\n #Game ended - Break\n break\n\n\n\n\n\nif save_weights:\n #Save model\n print(\"Saving weights\")\n model.save_weights(weigths_filename)\n action_predictor_model.save_weights(apWeights_filename)\n"
] |
[
[
"numpy.random.random",
"numpy.alen",
"numpy.arange",
"numpy.concatenate",
"numpy.delete",
"numpy.argmax",
"numpy.random.rand",
"numpy.array",
"numpy.zeros",
"numpy.vstack"
],
[
"numpy.random.random",
"numpy.alen",
"numpy.arange",
"numpy.concatenate",
"numpy.delete",
"numpy.random.rand",
"numpy.array",
"numpy.zeros",
"numpy.vstack"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
tmensink/deepncm
|
[
"fe7cdd43eb7276f4374c9c51715bf6cf417f994b"
] |
[
"resnet_deepncm_run_loop.py"
] |
[
"# Copyright 2018 Thomas Mensink, University of Amsterdam, [email protected]\n#\n# Beloning to the DeepNCM repository\n# DeepNCM is proposed in\n# Samantha Guerriero, Barbara Caputo, and Thomas Mensink\n# DeepNCM: Deep Nearest Class Mean Classifiers\n# ICLR Workshop 2018\n# https://openreview.net/forum?id=rkPLZ4JPM\n#\n# This file (resnet_deepncm_run_loop) is based on resnet_run_loop from the\n# TensorFlow Models Official ResNet library (release 1.8.0/1.7.0)\n# https://github.com/tensorflow/models/tree/master/official/resnet\n#\n# It contains code to support the ResNet DeepNCM models\n# Modifications are made to\n# - resnet_model_fn call, to incorporate the NCM update ops\n# - ResnetArgParser, to include different command line arguments\n# - Main, to allow multiple models at the same GPU\n\"\"\"Contains utility and supporting functions for ResNet.\n\n This module contains ResNet code which does not directly build layers. This\nincludes dataset management, hyperparameter and optimizer code, and argument\nparsing. Code for defining the ResNet layers can be found in resnet_ncm.py.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\n\nimport tensorflow as tf # pylint: disable=g-bad-import-order\n\nimport numpy as np\n\n#import resnet_ncm as rncm\nimport resnet_ncmequal as rncm\n\nALLOW_MULTIPLE_MODELS = True\n\nimport sys\nsys.path.append(\"./tf/models/\")\nfrom official.utils.arg_parsers import parsers\nfrom official.utils.export import export\nfrom official.utils.logging import hooks_helper\nfrom official.utils.logging import logger\nfrom official.resnet import resnet_run_loop as rrl\n################################################################################\n# Functions for input processing.\n################################################################################\ndef process_record_dataset(dataset, is_training, batch_size, shuffle_buffer,\n parse_record_fn, num_epochs=1, num_parallel_calls=1,\n examples_per_epoch=0, multi_gpu=False):\n return rrl.process_record_dataset(dataset, is_training, batch_size, shuffle_buffer,\n parse_record_fn, num_epochs=num_epochs, num_parallel_calls=num_parallel_calls,\n examples_per_epoch=examples_per_epoch, multi_gpu=multi_gpu)\n\ndef get_synth_input_fn(height, width, num_channels, num_classes):\n return rrl.get_synth_input_fn(height, width, num_channles, num_classes)\n\n################################################################################\n# Functions for running training/eval/validation loops for the model.\n################################################################################\ndef learning_rate_with_decay(\n batch_size, batch_denom, num_images, boundary_epochs, decay_rates,initial_learning_scale=0.1):\n \"\"\"Get a learning rate that decays step-wise as training progresses.\n\n Args:\n batch_size: the number of examples processed in each training batch.\n batch_denom: this value will be used to scale the base learning rate.\n `0.1 * batch size` is divided by this number, such that when\n batch_denom == batch_size, the initial learning rate will be 0.1.\n num_images: total number of images that will be used for training.\n boundary_epochs: list of ints representing the epochs at which we\n decay the learning rate.\n decay_rates: list of floats representing the decay rates to be used\n for scaling the learning rate. It should have one more element\n than `boundary_epochs`, and all elements should have the same type.\n\n Returns:\n Returns a function that takes a single argument - the number of batches\n trained so far (global_step)- and returns the learning rate to be used\n for training the next batch.\n \"\"\"\n initial_learning_rate = initial_learning_scale * batch_size / batch_denom\n batches_per_epoch = num_images / batch_size\n\n # Multiply the learning rate by 0.1 at 100, 150, and 200 epochs.\n boundaries = [int(batches_per_epoch * epoch) for epoch in boundary_epochs]\n vals = [initial_learning_rate * decay for decay in decay_rates]\n\n def learning_rate_fn(global_step):\n global_step = tf.cast(global_step, tf.int32)\n return tf.train.piecewise_constant(global_step, boundaries, vals)\n\n return learning_rate_fn\n\n\ndef resnet_model_fn(features, labels, mode, model_class,\n resnet_size, weight_decay, learning_rate_fn, momentum,\n data_format, version, loss_filter_fn=None, multi_gpu=False, ncm=rncm.NCM_DEFAULT):\n \"\"\"Shared functionality for different resnet model_fns.\n\n Initializes the ResnetModel representing the model layers\n and uses that model to build the necessary EstimatorSpecs for\n the `mode` in question. For training, this means building losses,\n the optimizer, and the train op that get passed into the EstimatorSpec.\n For evaluation and prediction, the EstimatorSpec is returned without\n a train op, but with the necessary parameters for the given mode.\n\n Args:\n features: tensor representing input images\n labels: tensor representing class labels for all input images\n mode: current estimator mode; should be one of\n `tf.estimator.ModeKeys.TRAIN`, `EVALUATE`, `PREDICT`\n model_class: a class representing a TensorFlow model that has a __call__\n function. We assume here that this is a subclass of ResnetModel.\n resnet_size: A single integer for the size of the ResNet model.\n weight_decay: weight decay loss rate used to regularize learned variables.\n learning_rate_fn: function that returns the current learning rate given\n the current global_step\n momentum: momentum term used for optimization\n data_format: Input format ('channels_last', 'channels_first', or None).\n If set to None, the format is dependent on whether a GPU is available.\n version: Integer representing which version of the ResNet network to use.\n See README for details. Valid values: [1, 2]\n loss_filter_fn: function that takes a string variable name and returns\n True if the var should be included in loss calculation, and False\n otherwise. If None, batch_normalization variables will be excluded\n from the loss.\n multi_gpu: If True, wrap the optimizer in a TowerOptimizer suitable for\n data-parallel distribution across multiple GPUs.\n\n Returns:\n EstimatorSpec parameterized according to the input params and the\n current mode.\n \"\"\"\n # Generate a summary node for the images\n tf.summary.image('images', features, max_outputs=6)\n\n model = model_class(resnet_size, data_format=data_format, num_classes=labels.shape[1].value, version=version,ncm=ncm)\n logits, deep_x, deepmean = model(features, mode == tf.estimator.ModeKeys.TRAIN)\n\n predictions = {\n 'classes': tf.argmax(logits, axis=1),\n 'probabilities': tf.nn.softmax(logits, name='softmax_tensor'),\n }\n\n\n dm = tf.identity(deepmean,\"DM\")\n if not (model.ncmmethod == \"softmax\"):\n rdist,mmsk = model.get_relative_mean_distance(deep_x=deep_x,labels=labels)\n mcmd = tf.metrics.mean(rdist,weights=mmsk)\n rmd = tf.identity(mcmd[1],name=\"rmd\")\n rmd = tf.summary.scalar('rmd', rmd)\n predictions['rmd'] = tf.identity(rmd,name=\"rmd\")\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n # Return the predictions and the specification for serving a SavedModel\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=predictions,\n export_outputs={\n 'predict': tf.estimator.export.PredictOutput(predictions)\n }\n )\n\n # Calculate loss, which includes softmax cross entropy and L2 regularization.\n cross_entropy = tf.losses.softmax_cross_entropy(logits=logits, onehot_labels=labels)\n\n # Create a tensor named cross_entropy for logging purposes.\n tf.identity(cross_entropy, name='cross_entropy')\n tf.summary.scalar('cross_entropy', cross_entropy)\n\n # If no loss_filter_fn is passed, assume we want the default behavior,\n # which is that batch_normalization variables are excluded from loss.\n def exclude_batch_norm(name):\n return 'batch_normalization' not in name\n loss_filter_fn = loss_filter_fn or exclude_batch_norm\n\n # Add weight decay to the loss.\n l2_loss = weight_decay * tf.add_n(\n [tf.nn.l2_loss(v) for v in tf.trainable_variables()\n if loss_filter_fn(v.name)])\n tf.summary.scalar('l2_loss', l2_loss)\n loss = cross_entropy + l2_loss\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n ncm_ops = model.get_ncm_ops(deep_x=deep_x,labels=labels)\n\n # Create a tensor named learning_rate for logging purposes\n global_step = tf.train.get_or_create_global_step()\n learning_rate = learning_rate_fn(global_step)\n tf.identity(learning_rate, name='learning_rate')\n tf.summary.scalar('learning_rate', learning_rate)\n\n # Create loss_op using Gradient clipping\n optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate,momentum=momentum)\n gavs = optimizer.compute_gradients(loss)\n gavsc= [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gavs]\n loss_op = optimizer.apply_gradients(gavsc,global_step=global_step)\n\n # Update ops from Graph\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\n train_op = tf.group(loss_op, update_ops, ncm_ops)\n else:\n train_op = None\n\n accuracy = tf.metrics.accuracy(tf.argmax(labels, axis=1), predictions['classes'])\n\n dm,bm,bmc = model.get_mean_and_batch_mean(deep_x=deep_x,labels=labels)\n\n metrics = {'accuracy': accuracy}\n if not (model.ncmmethod == \"softmax\"):\n metrics['mcmdistance'] = mcmd\n # The following is only required for the Relative Mean Distance Experiment\n #metrics['batchmeans'] = tf.metrics.mean_tensor(tf.transpose(bm),weights=bmc)\n #metrics['deepmean'] = tf.metrics.mean_tensor(dm)\n\n # Create a tensor named train_accuracy for logging purposes\n tf.identity(accuracy[1], name='train_accuracy')\n tf.summary.scalar('train_accuracy', accuracy[1])\n\n return tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=predictions,\n loss=loss,\n train_op=train_op,\n eval_metric_ops=metrics)\n\n\ndef resnet_main(flags, model_function, input_function, shape=None):\n \"\"\"Shared main loop for ResNet Models.\n\n Args:\n flags: FLAGS object that contains the params for running. See\n ResnetArgParser for created flags.\n model_function: the function that instantiates the Model and builds the\n ops for train/eval. This will be passed directly into the estimator.\n input_function: the function that processes the dataset and returns a\n dataset that the estimator can train on. This will be wrapped with\n all the relevant flags for running and passed to estimator.\n shape: list of ints representing the shape of the images used for training.\n This is only used if flags.export_dir is passed.\n \"\"\"\n\n # Using the Winograd non-fused algorithms provides a small performance boost.\n os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'\n\n # Create session config based on values of inter_op_parallelism_threads and\n # intra_op_parallelism_threads. Note that we default to having\n # allow_soft_placement = True, which is required for multi-GPU and not\n # harmful for other modes.\n session_config = tf.ConfigProto(\n inter_op_parallelism_threads=flags.inter_op_parallelism_threads,\n intra_op_parallelism_threads=flags.intra_op_parallelism_threads,\n allow_soft_placement=True)\n\n if ALLOW_MULTIPLE_MODELS:\n session_config.gpu_options.allow_growth = True\n\n # Set up a RunConfig to save checkpoint and set session config.\n run_config = tf.estimator.RunConfig().replace(\n save_checkpoints_secs = 5*60, # Save checkpoints every X minutes.\n keep_checkpoint_max = 1000, # Retain the 1000 most recent checkpoints.\n #tf_random_seed = 5739, # Set random seed for \"reproducible\" results\n save_summary_steps = 10000, # Number of steps between summaries\n session_config=session_config)\n\n classifier = tf.estimator.Estimator(\n model_fn=model_function, model_dir=flags.model_dir, config=run_config,\n params={\n 'resnet_size': flags.resnet_size,\n 'data_format': flags.data_format,\n 'batch_size': flags.batch_size,\n 'multi_gpu': flags.multi_gpu,\n 'version': flags.version,\n 'ncmmethod': flags.ncmmethod,\n 'ncmparam' : flags.ncmparam,\n 'initial_learning_scale' : flags.initial_learning_scale\n })\n\n if flags.benchmark_log_dir is not None:\n benchmark_logger = logger.BenchmarkLogger(flags.benchmark_log_dir)\n benchmark_logger.log_run_info(\"resnet\")\n else:\n benchmark_logger = None\n\n for _ in range(flags.train_epochs // flags.epochs_between_evals):\n train_hooks = hooks_helper.get_train_hooks(\n flags.hooks,\n batch_size=flags.batch_size,\n benchmark_log_dir=flags.benchmark_log_dir)\n #tensors_to_log = {\"iter\": \"m_iter\",\"deep-cnt\": \"m_cnt\", \"deep-sum\": \"m_sum\"}\n #logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=1)\n\n\n print('Starting a training cycle.')\n\n def input_fn_train():\n return input_function(True, flags.data_dir, flags.batch_size,\n flags.epochs_between_evals,\n flags.num_parallel_calls, flags.multi_gpu)\n\n classifier.train(input_fn=input_fn_train, hooks=train_hooks,max_steps=flags.max_train_steps)\n\n print('Starting to evaluate.')\n # Evaluate the model and print results\n def input_fn_eval():\n return input_function(False, flags.data_dir, flags.batch_size,\n 1, flags.num_parallel_calls, flags.multi_gpu)\n\n # flags.max_train_steps is generally associated with testing and profiling.\n # As a result it is frequently called with synthetic data, which will\n # iterate forever. Passing steps=flags.max_train_steps allows the eval\n # (which is generally unimportant in those circumstances) to terminate.\n # Note that eval will run for max_train_steps each loop, regardless of the\n # global_step count.\n eval_results = classifier.evaluate(input_fn=input_fn_eval,\n steps=flags.max_train_steps)\n print(eval_results)\n\n if benchmark_logger:\n benchmark_logger.log_estimator_evaluation_result(eval_results)\n\n if flags.export_dir is not None:\n # Exports a saved model for the given classifier.\n input_receiver_fn = export.build_tensor_serving_input_receiver_fn(\n shape, batch_size=flags.batch_size)\n classifier.export_savedmodel(flags.export_dir, input_receiver_fn)\n\n\nclass ResnetArgParser(argparse.ArgumentParser):\n \"\"\"Arguments for configuring and running a Resnet Model.\"\"\"\n\n def __init__(self, resnet_size_choices=None):\n super(ResnetArgParser, self).__init__(parents=[\n parsers.BaseParser(),\n parsers.PerformanceParser(),\n parsers.ImageModelParser(),\n parsers.ExportParser(),\n parsers.BenchmarkParser(),\n ])\n\n self.add_argument('--dataset','-d',default=\"cifar10\",\n help='Which dataset to use (currently cifar10/cifar100)'\n )\n\n self.add_argument(\n '--version', '-v', type=int, choices=[1, 2],\n default=rncm.RESNET_DEFAULT_VERSION,\n help='Version of ResNet. (1 or 2) See README.md for details.'\n )\n\n self.add_argument(\n '--resnet_size', '-rs', type=int, default=50,\n choices=resnet_size_choices,\n help='[default: %(default)s] The size of the ResNet model to use.',\n metavar='<RS>' if resnet_size_choices is None else None\n )\n\n self.add_argument(\n '--continu',type=int,default=0,\n help='Continue with an existing model, or start from scratch'\n )\n\n self.add_argument(\n '--scratch',type=int,default=0,\n help='Start from scratch even if model exist'\n )\n\n self.add_argument(\n '--ncmmethod', default=rncm.NCM_DEFAULT_METHOD,\n help='[default: %(default)s] Which NCM method to use',\n )\n\n self.add_argument(\n '--ncmparam', default=rncm.NCM_DEFAULT_PARAMETER, type=float,\n help='[default: %(default)s] additional NCM parameter to use',\n )\n\n self.add_argument(\n '--initial_learning_scale', '-l', default=0.1, type=float,\n help='Intial Learning Scale (default: %(default)s)',\n )\n"
] |
[
[
"tensorflow.cast",
"tensorflow.nn.l2_loss",
"tensorflow.estimator.RunConfig",
"tensorflow.group",
"tensorflow.summary.scalar",
"tensorflow.get_collection",
"tensorflow.summary.image",
"tensorflow.estimator.export.PredictOutput",
"tensorflow.train.get_or_create_global_step",
"tensorflow.losses.softmax_cross_entropy",
"tensorflow.ConfigProto",
"tensorflow.train.piecewise_constant",
"tensorflow.train.MomentumOptimizer",
"tensorflow.trainable_variables",
"tensorflow.argmax",
"tensorflow.metrics.mean",
"tensorflow.estimator.Estimator",
"tensorflow.identity",
"tensorflow.clip_by_value",
"tensorflow.nn.softmax",
"tensorflow.estimator.EstimatorSpec"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
kumasento/gradient-scaling
|
[
"0ca435433b9953e33656173c4d60ebd61c5c5e87"
] |
[
"chainerlp/notebook_utils.py"
] |
[
"\"\"\" Utility functions for Jupyter notebooks \"\"\"\nimport os\nimport json\nimport subprocess\nimport time\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport chainer\nimport chainer.links as L\nfrom chainerlp.links import models\nfrom chainerlp.training.load_only_updator import LoadOnlyUpdator\n\n\ndef get_train_dir(\n dtype=None, dataset=None, model=None, rootdir=None, seed=None, **kwargs\n):\n \"\"\" Get the training directory. \"\"\"\n train_dir = \"{rootdir}/{dataset}/{model}_{dtype}\".format(\n dataset=dataset, model=model, dtype=dtype, rootdir=rootdir\n )\n if seed is not None:\n train_dir += \"_{}\".format(seed)\n for key, val in kwargs.items():\n if val is None:\n continue\n if isinstance(val, float) and np.isnan(val):\n continue\n train_dir += \"_{}_{}\".format(key, val)\n\n return train_dir\n\n\n######################################\n# Cluster related #\n######################################\nUSER = os.environ.get(\"USER\", None)\nSERVER = os.environ.get(\"SERVER\", None)\nCLI = os.environ.get(\"CLUSTER_CLI\", None)\nDEFAULT_SPEC_FILE = \"{}spec.yml\".format(CLI)\nPROJDIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\")\nCLI_RUN_ARGS = [\n # '--auto-persist',\n]\n\n\ndef download_from_cluster(\n dtype,\n dataset,\n model,\n job_id,\n rootdir,\n files=None,\n ignore_job_done=False,\n seed=None,\n persist=True,\n verbose=False,\n **kwargs\n):\n \"\"\" Download result from the cluster to local directory \"\"\"\n if isinstance(job_id, int):\n job_id = str(job_id)\n\n info = get_job_info(job_id)\n if not is_job_done(info) and not ignore_job_done:\n return None\n if persist:\n execute_job_command(job_id, \"persist-results\")\n if files is None:\n files = [\"log\"]\n\n train_dir = get_train_dir(dtype, dataset, model, rootdir, seed=seed, **kwargs)\n args = [*files, \"--dest\", train_dir]\n if verbose:\n print(\"Downloading to directory: {} ...\".format(train_dir))\n\n return execute_job_command(job_id, \"get-results\", args=args)\n\n\ndef run_on_cluster(args, cli_args=None):\n \"\"\" Launch a run task on cluster \"\"\"\n if cli_args is None:\n cli_args = []\n args = [\n CLI,\n \"--user\",\n USER,\n \"--server\",\n SERVER,\n \"run\",\n *cli_args,\n \"--\",\n *args,\n ]\n return subprocess.run(args=args, capture_output=True, cwd=PROJDIR)\n\n\ndef train_on_cluster(\n train_script,\n train_args,\n cli_args=None,\n label=\"train_on_cluster\",\n spec_file=DEFAULT_SPEC_FILE,\n verbose=False,\n):\n \"\"\" Launch training task on the cluster without MPI environment \"\"\"\n if cli_args is None:\n cli_args = []\n cli_args.extend(\n [\n \"-A\",\n \"nvidia.k8s.pfn.io/cuda-version=10.0\",\n \"--auto-persist\",\n \"--spec\",\n spec_file,\n \"--label\",\n label,\n ]\n )\n args = [\n \"python3\",\n train_script,\n *train_args,\n ]\n return run_on_cluster(args, cli_args=cli_args)\n\n\ndef train_cifar_on_cluster(\n arch,\n dataset,\n dtype,\n n_epoch,\n schedule,\n manual_seed=0,\n learnrate=0.1,\n weight_decay=1e-4,\n lr_decay=0.1,\n warmup_lr_ratio=0.1,\n n_warmup_epoch=None,\n snapshot_freq=10,\n use_fixup=False,\n custom_label=None,\n):\n \"\"\" Train model on CIFAR-10 on the cluster environment.\n Single GPU is required.\n \"\"\"\n train_script = \"examples/cifar/train_cifar.py\"\n spec_file = os.path.join(PROJDIR, \"examples\", \"cifar\", DEFAULT_SPEC_FILE)\n label = \"{arch}-{dataset}-{dtype}-{seed}\".format(\n arch=arch, dataset=dataset, dtype=dtype, seed=manual_seed\n )\n if custom_label is not None:\n label = custom_label + \"-\" + label # add a prefix\n\n schedule_ = [str(s) for s in schedule]\n warmup_lr = learnrate * warmup_lr_ratio\n\n train_args = [\n \"--dataset\",\n dataset,\n \"--arch\",\n arch,\n \"--dtype\",\n dtype,\n \"-b\",\n \"128\",\n \"-e\",\n str(n_epoch),\n \"-s\",\n *schedule_,\n \"--learnrate\",\n str(learnrate),\n \"--manual-seed\",\n str(manual_seed),\n \"--device\",\n \"0\",\n \"--weight-decay\",\n str(weight_decay),\n \"--lr-decay\",\n str(lr_decay),\n \"--out\",\n \"/home/user/results\",\n \"--snapshot-freq\",\n str(snapshot_freq),\n ]\n\n if use_fixup:\n train_args.append(\"--use-fixup\")\n if n_warmup_epoch is not None:\n train_args.extend(\n [\"--warmup-lr\", str(warmup_lr), \"--warmup-epoch\", str(n_warmup_epoch),]\n )\n\n cli_args = []\n\n # HACK: need to launch on larger GPUs\n if dtype == \"float32\" and arch == \"resnet1202\":\n cli_args.extend(\n [\"-A\", \"nvidia.k8s.pfn.io/gpu_model=Tesla-P100-PCIE-16GB\",]\n )\n\n return train_on_cluster(train_script, train_args, label=label, spec_file=spec_file)\n\n\ndef train_imagenet_on_cluster(\n arch,\n dataset=\"imagenet\",\n dtype=\"float32\",\n manual_seed=0,\n first_bn_mixed16=None,\n dataset_dir=\"/home/user/data/imagenet\",\n mpi=\"4x4\",\n snapshot_freq=1,\n verbose=False,\n):\n \"\"\" Launch ImageNet training task on cluster \"\"\"\n train_script = \"examples/imagenet/train_imagenet_multi.py\"\n spec_file = os.path.join(PROJDIR, \"examples\", \"imagenet\", DEFAULT_SPEC_FILE)\n label = \"{arch}-{dataset}-{dtype}\".format(arch=arch, dataset=dataset, dtype=dtype)\n\n train_args = [\n \"--dataset-dir\",\n dataset_dir,\n \"-a\",\n arch,\n \"--dtype\",\n dtype,\n \"--manual-seed\",\n str(manual_seed),\n \"--out\",\n \"/home/user/results\",\n \"--snapshot-freq\",\n str(snapshot_freq),\n ]\n if first_bn_mixed16:\n train_args.append(\"--first-bn-mixed16\")\n\n cli_args = [\"--mpi\", mpi]\n\n return train_on_cluster(\n train_script,\n train_args,\n label=label,\n cli_args=cli_args,\n spec_file=spec_file,\n verbose=verbose,\n )\n\n\ndef execute_job_command(job_id, command, args=None):\n \"\"\" Collect job information by job_id \"\"\"\n if isinstance(job_id, int):\n job_id = str(job_id)\n if args is None:\n args = []\n args = [\n CLI,\n \"--user\",\n USER,\n \"--server\",\n SERVER,\n \"job\",\n job_id,\n command,\n *args,\n ]\n return subprocess.run(args=args, capture_output=True)\n\n\ndef get_job_info(job_id):\n \"\"\" Collect job information \"\"\"\n while True:\n p = execute_job_command(job_id, \"info\")\n # NOTE: this task may fail\n if p.returncode == 0:\n break\n else:\n print(\"[WARN] Retrying get job info of {} ...\".format(job_id))\n\n return p.stdout.decode(\"utf-8\")\n\n\ndef get_job_attr(job_info, attr_name):\n \"\"\" Get the content from a job attribute \"\"\"\n lines = [s.strip() for s in job_info.split(\"\\n\")]\n\n # Find the line that starts with the attribute\n cmd_line = next((l for l in lines if l.startswith(attr_name)), None)\n if cmd_line is None:\n return None\n\n cmd = cmd_line.split(\" \")[1:] # first entry is 'cmmand:'\n return cmd\n\n\ndef get_job_id(p):\n \"\"\" Collect job_id from a job launching process p \"\"\"\n s = p.stderr.decode(\"utf-8\")\n try:\n job_id = s.split(\"\\n\")[-3].split(\" \")[-1] # TODO: improve\n return int(job_id) # may raise value error\n except ValueError:\n return None\n\n\ndef is_job_failed(job_info):\n return \"failed\" in job_info\n\n\ndef is_job_done(job_info):\n return \"completed successfully\" in job_info\n\n\ndef is_job_running(job_info):\n return \"running\" in job_info\n\n\ndef get_job_status(job_info):\n if is_job_failed(job_info):\n return \"FAILED\"\n if is_job_done(job_info):\n return \"DONE\"\n if is_job_running(job_info):\n return \"RUNNING\"\n\n return \"UNKNOWN\"\n\n\ndef relaunch_failed_job(job_id, spec_file):\n \"\"\" Relaunch the selected failed job.\n spec_file should be provided or we cannot know which spec you're using\n \"\"\"\n job_info = get_job_info(job_id)\n if not is_job_failed(job_info):\n return None\n\n args = get_job_attr(job_info, \"command\")\n label = get_job_attr(job_info, \"label\")\n attrs = get_job_attr(job_info, \"attributes\")\n\n cli_args = [*CLI_RUN_ARGS, \"--spec\", spec_file]\n if label is not None:\n cli_args.extend([\"--label\", *label])\n if attrs is not None:\n cli_args.extend([\"-A\", *attrs])\n\n return run_on_cluster(args, cli_args=cli_args)\n\n\ndef relaunch_failed_jobs(tasks, spec_file, verbose=False):\n \"\"\" Relaunch jobs that are failed from the given list \"\"\"\n job_cnts = 0 # number of newly launched jobs\n\n for i, task in enumerate(tasks):\n job_id = str(task[-1]) # the last entry\n\n # Try to launch until succeed\n while True:\n p = relaunch_failed_job(job_id, spec_file)\n if p is None: # NOTE: when the job is not failed\n break\n\n if verbose:\n print(\"==> Re-launching failed task: {} ...\".format(task))\n new_id = get_job_id(p)\n if new_id is not None:\n break\n\n # If a new process is launched\n if p is not None:\n tasks[i][-1] = new_id\n job_cnts += 1\n\n return job_cnts\n\n\ndef check_task_status(tasks, verbose=False):\n \"\"\" Go through all the tasks and see how their running status are \"\"\"\n print(time.ctime()) # Print a timestamp (NECESSARY)\n\n stats = {}\n\n for task in tasks:\n job_id = str(task[-1]) # needs to be str\n info = get_job_info(job_id)\n status = get_job_status(info)\n if verbose:\n print(\"Status of task {}:\\t{}\".format(task, status))\n\n # update the statistics\n if status not in stats:\n stats[status] = 0\n stats[status] += 1\n\n return stats\n\n\ndef cleanup_jobs(jobs, verbose=False):\n \"\"\" Cleanup the jobs remaining on the cluster \"\"\"\n for job_id in jobs:\n if verbose:\n print(\"==> Cleaning-up job {} ...\".format(job_id))\n job_info = get_job_info(job_id)\n status = get_job_status(job_info)\n if status == \"RUNNING\": # kill if the job is running\n if verbose:\n print(\"==> Killing ...\")\n execute_job_command(job_id, \"kill\")\n\n # unpersist results\n execute_job_command(job_id, \"unpersist-results\")\n\n\n######################################\n# File IO #\n######################################\n\n\ndef load_train_log(\n dtype=None,\n dataset=None,\n model=None,\n rootdir=None,\n seed=None,\n train_dir=None,\n **kwargs\n):\n \"\"\" Load the log file by Pandas \"\"\"\n if train_dir is None:\n assert dtype in [\"float32\", \"float16\", \"mixed16\"]\n train_dir = get_train_dir(\n dtype=dtype,\n dataset=dataset,\n model=model,\n rootdir=rootdir,\n seed=seed,\n **kwargs\n )\n if not os.path.isdir(train_dir):\n print(\"[WARN] train_dir to load data cannot be found: {}\".format(train_dir))\n return None\n\n fp = \"{}/log\".format(train_dir)\n with open(fp, \"r\") as f:\n df = pd.DataFrame(json.loads(f.read()))\n return df\n\n\ndef plot_train_log(\n dataset=None,\n model=None,\n seed=None,\n rootdir=None,\n savedir=None,\n dtypes=None,\n x_axis=\"epoch\",\n fig=None,\n ax1=None,\n ax2=None,\n label_suffix=None,\n **kwargs\n):\n \"\"\" Plot the training log of a single model. \"\"\"\n assert isinstance(rootdir, str)\n\n if dtypes is None:\n dtypes = [\"float32\", \"float16\"]\n if fig is None:\n fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(9, 4))\n\n ax1.set_ylabel(\"Validation accuracy (%)\")\n ax1.set_xlabel(x_axis)\n ax2.set_ylabel(\"Train loss\")\n ax2.set_xlabel(x_axis)\n\n for dtype in dtypes:\n train_log = load_train_log(dtype, dataset, model, rootdir, seed=seed, **kwargs)\n\n if train_log is None:\n continue\n if label_suffix is None:\n label_suffix = \" ({})\".format(seed) if seed is not None else \"\"\n\n dtype_in_label = dtype[0] + dtype[-2:]\n val_acc = train_log[~train_log[\"validation/main/accuracy\"].isnull()]\n ax1.plot(\n val_acc[x_axis],\n val_acc[\"validation/main/accuracy\"] * 100,\n label=\"{} {}{}\".format(model, dtype_in_label, label_suffix),\n )\n ax2.plot(\n train_log[x_axis],\n train_log[\"main/loss\"],\n label=\"{} {}{}\".format(model, dtype_in_label, label_suffix),\n )\n\n ax1.legend()\n ax2.legend()\n fig.suptitle(\"{} on {}\".format(model, dataset))\n if savedir is not None:\n os.makedirs(savedir, exist_ok=True)\n fig.savefig(os.path.join(savedir, \"{}_{}_train_log.pdf\".format(model, dataset)))\n\n\ndef plot_train_logs(\n dataset, models, rootdir=None, savedir=None, x_axis=\"epoch\", dtypes=None, seeds=None\n):\n \"\"\" Plot training logs of multiple models\n \n There will be two subplots, on the left is the validation accuracy, \n on the right is training loss.\n \"\"\"\n if seeds is None:\n seeds = [None]\n fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(9, 4))\n\n for model in models:\n for seed in seeds:\n plot_train_log(\n dataset,\n model,\n seed=seed,\n rootdir=rootdir,\n savedir=None,\n x_axis=x_axis,\n dtypes=dtypes,\n fig=fig,\n ax1=ax1,\n ax2=ax2,\n )\n\n ax1.legend()\n ax2.legend()\n fig.suptitle(\"Results on {}\".format(dataset))\n if savedir is not None:\n fig.savefig(\n os.path.join(\n savedir, \"{}_{}_train_log.pdf\".format(\"_\".join(models), dataset)\n )\n )\n\n\ndef load_snapshot_and_create_model(\n arch,\n snapshot_name=None,\n snapshot_dir=None,\n dataset=\"imagenet\",\n dtype=\"float32\",\n n_class=1000,\n rootdir=None,\n job_id=None,\n seed=None,\n device=-1,\n **kwargs\n):\n \"\"\" Load the snapshot of a Trainer into a model. \"\"\"\n # create model\n chainer.config.dtype = get_chainer_dtype(dtype)\n model = L.Classifier(models.__dict__[arch](n_class=n_class))\n\n if device != -1:\n chainer.cuda.get_device(device).use()\n model.to_gpu()\n if snapshot_name is None: # will return the initialized model\n return model\n\n if snapshot_dir is not None:\n train_dir = snapshot_dir\n else:\n assert isinstance(rootdir, str)\n assert os.path.isdir(rootdir)\n\n train_dir = get_train_dir(dtype, dataset, arch, rootdir, seed=seed, **kwargs)\n\n fp = os.path.join(train_dir, snapshot_name)\n if not os.path.isdir(train_dir) or not os.path.isfile(fp):\n print(\"==> Snapshot not found: {}. Downloading ...\".format(fp))\n download_from_cluster(\n dtype,\n dataset,\n arch,\n job_id,\n rootdir,\n files=[snapshot_name],\n ignore_job_done=True,\n seed=seed,\n **kwargs\n )\n\n # create the trainer\n optim = chainer.optimizers.CorrectedMomentumSGD()\n optim.setup(model)\n\n updator = LoadOnlyUpdator(None, optim, device=0)\n trainer = chainer.training.Trainer(updator)\n chainer.serializers.load_npz(fp, trainer)\n\n return model\n\n\ndef get_chainer_dtype(dtype):\n if dtype == \"float32\":\n return np.float32\n if dtype == \"float16\":\n return np.float16\n if dtype == \"mixed16\":\n return chainer.mixed16\n\n\ndef get_snapshot_parameters(\n arch,\n dtype,\n snapshot_name=None,\n dataset=\"imagenet\",\n rootdir=None,\n n_class=1000,\n job_id=None,\n device=0,\n seed=None,\n fig=None,\n ax=None,\n savedir=None,\n includes=None,\n **kwargs\n):\n \"\"\" We will iterate the model and print out all the BN parameters \"\"\"\n net = load_snapshot_and_create_model(\n arch,\n snapshot_name,\n dataset=dataset,\n dtype=dtype,\n rootdir=rootdir,\n n_class=n_class,\n job_id=job_id,\n seed=seed,\n device=device,\n **kwargs\n )\n\n if includes is None:\n includes = []\n\n results = []\n for name, link in net.predictor.namedlinks():\n params = list(link.namedparams())\n results.append((name, params))\n\n return results\n"
] |
[
[
"numpy.isnan",
"matplotlib.pyplot.subplots"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
eodcgmbh/datacube-core
|
[
"0792e519ccfd33e0a0acf368aa6f33ca2c1ea50f"
] |
[
"tests/test_utils_other.py"
] |
[
"# This file is part of the Open Data Cube, see https://opendatacube.org for more information\n#\n# Copyright (c) 2015-2020 ODC Contributors\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"\nTest utility functions from :module:`datacube.utils`\n\n\n\"\"\"\nimport os\nimport pathlib\nimport string\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\nimport rasterio\nimport xarray as xr\nfrom dateutil.parser import parse\nfrom hypothesis import given\nfrom hypothesis.strategies import integers, text\nfrom pandas import to_datetime\n\nfrom datacube.helpers import write_geotiff\nfrom datacube.utils import gen_password, write_user_secret_file, slurp\nfrom datacube.model.utils import xr_apply\nfrom datacube.utils.dates import date_sequence\nfrom datacube.utils.math import (\n num2numpy,\n is_almost_int,\n maybe_zero,\n maybe_int,\n snap_scale,\n valid_mask,\n invalid_mask,\n clamp,\n unsqueeze_data_array,\n unsqueeze_dataset,\n spatial_dims,\n data_resolution_and_offset,\n affine_from_axis,\n)\nfrom datacube.utils.py import sorted_items\nfrom datacube.utils.uris import (uri_to_local_path, mk_part_uri, get_part_from_uri, as_url, is_url,\n pick_uri, uri_resolve, is_vsipath,\n normalise_path, default_base_dir)\nfrom datacube.utils.io import check_write_path\nfrom datacube.testutils import mk_sample_product, remove_crs\n\n\ndef test_stats_dates():\n # Winter for 1990\n winter_1990 = list(date_sequence(start=to_datetime('1990-06-01'), end=to_datetime('1990-09-01'), step_size='3m',\n stats_duration='3m'))\n assert winter_1990 == [(parse('1990-06-01'), parse('1990-09-01'))]\n\n # Every winter from 1990 - 1992\n three_years_of_winter = list(date_sequence(start=to_datetime('1990-06-01'), end=to_datetime('1992-09-01'),\n step_size='1y',\n stats_duration='3m'))\n assert three_years_of_winter == [(parse('1990-06-01'), parse('1990-09-01')),\n (parse('1991-06-01'), parse('1991-09-01')),\n (parse('1992-06-01'), parse('1992-09-01'))]\n\n # Full years from 1990 - 1994\n five_full_years = list(date_sequence(start=to_datetime('1990-01-01'), end=to_datetime('1995'), step_size='1y',\n stats_duration='1y'))\n assert five_full_years == [(parse('1990-01-01'), parse('1991-01-01')),\n (parse('1991-01-01'), parse('1992-01-01')),\n (parse('1992-01-01'), parse('1993-01-01')),\n (parse('1993-01-01'), parse('1994-01-01')),\n (parse('1994-01-01'), parse('1995-01-01'))]\n\n # Every season (three months), starting in March, from 1990 until end 1992-02\n two_years_of_seasons = list(date_sequence(start=to_datetime('1990-03-01'), end=to_datetime('1992-03'),\n step_size='3m',\n stats_duration='3m'))\n assert len(two_years_of_seasons) == 8\n assert two_years_of_seasons == [(parse('1990-03-01'), parse('1990-06-01')),\n (parse('1990-06-01'), parse('1990-09-01')),\n (parse('1990-09-01'), parse('1990-12-01')),\n (parse('1990-12-01'), parse('1991-03-01')),\n (parse('1991-03-01'), parse('1991-06-01')),\n (parse('1991-06-01'), parse('1991-09-01')),\n (parse('1991-09-01'), parse('1991-12-01')),\n (parse('1991-12-01'), parse('1992-03-01'))] # Leap year!\n\n # Every month from 1990-01 to 1990-06\n monthly = list(date_sequence(start=to_datetime('1990-01-01'), end=to_datetime('1990-07-01'), step_size='1m',\n stats_duration='1m'))\n assert len(monthly) == 6\n\n # Complex\n # I want the average over 5 years\n\n\ndef test_uri_to_local_path():\n if os.name == 'nt':\n assert 'C:\\\\tmp\\\\test.tmp' == str(uri_to_local_path('file:///C:/tmp/test.tmp'))\n assert '\\\\\\\\remote\\\\path\\\\file.txt' == str(uri_to_local_path('file://remote/path/file.txt'))\n\n else:\n assert '/tmp/something.txt' == str(uri_to_local_path('file:///tmp/something.txt'))\n\n with pytest.raises(ValueError):\n uri_to_local_path('file://remote/path/file.txt')\n\n assert uri_to_local_path(None) is None\n\n with pytest.raises(ValueError):\n uri_to_local_path('ftp://example.com/tmp/something.txt')\n\n\[email protected](\"base\", [\n \"s3://foo\",\n \"gs://foo\",\n \"wasb://foo\",\n \"wasbs://foo\",\n \"/vsizip//vsicurl/https://host.tld/some/path\",\n])\ndef test_uri_resolve(base):\n abs_path = '/abs/path/to/something'\n some_uri = 'http://example.com/file.txt'\n\n assert uri_resolve(base, abs_path) == \"file://\" + abs_path\n assert uri_resolve(base, some_uri) is some_uri\n assert uri_resolve(base, None) is base\n assert uri_resolve(base, '') is base\n assert uri_resolve(base, 'relative/path') == base + '/relative/path'\n assert uri_resolve(base + '/', 'relative/path') == base + '/relative/path'\n assert uri_resolve(base + '/some/dir/', 'relative/path') == base + '/some/dir/relative/path'\n\n if not is_vsipath(base):\n assert uri_resolve(base + '/some/dir/file.txt', 'relative/path') == base + '/some/dir/relative/path'\n\n\ndef test_pick_uri():\n f, s, h = ('file://a', 's3://b', 'http://c')\n\n assert pick_uri([f, s, h]) is f\n assert pick_uri([s, h, f]) is f\n assert pick_uri([s, h]) is s\n assert pick_uri([h, s]) is h\n assert pick_uri([f, s, h], 'http:') is h\n assert pick_uri([f, s, h], 's3:') is s\n assert pick_uri([f, s, h], 'file:') is f\n\n with pytest.raises(ValueError):\n pick_uri([])\n\n with pytest.raises(ValueError):\n pick_uri([f, s, h], 'ftp:')\n\n with pytest.raises(ValueError):\n pick_uri([s, h], 'file:')\n\n\n@given(integers(), integers(), integers())\ndef test_clamp(x, lower_bound, upper_bound):\n if lower_bound > upper_bound:\n lower_bound, upper_bound = upper_bound, lower_bound\n new_x = clamp(x, lower_bound, upper_bound)\n\n # If x was already between the bounds, it shouldn't have changed\n if lower_bound <= x <= upper_bound:\n assert new_x == x\n assert lower_bound <= new_x <= upper_bound\n\n\n@given(integers(min_value=10, max_value=30))\ndef test_gen_pass(n_bytes):\n password1 = gen_password(n_bytes)\n password2 = gen_password(n_bytes)\n assert len(password1) >= n_bytes\n assert len(password2) >= n_bytes\n assert password1 != password2\n\n\n@given(text(alphabet=string.digits + string.ascii_letters + ' ,:.![]?', max_size=20))\ndef test_write_user_secret_file(txt):\n fname = u\".tst-datacube-uefvwr4cfkkl0ijk.txt\"\n\n write_user_secret_file(txt, fname)\n txt_back = slurp(fname)\n os.remove(fname)\n assert txt == txt_back\n assert slurp(fname) is None\n\n\ndef test_write_geotiff(tmpdir, odc_style_xr_dataset):\n \"\"\"Ensure the geotiff helper writer works, and supports datasets smaller than 256x256.\"\"\"\n filename = tmpdir + '/test.tif'\n\n assert len(odc_style_xr_dataset.latitude) < 256\n\n with pytest.warns(DeprecationWarning):\n write_geotiff(filename, odc_style_xr_dataset)\n\n assert filename.exists()\n\n with rasterio.open(str(filename)) as src:\n written_data = src.read(1)\n\n assert (written_data == odc_style_xr_dataset['B10']).all()\n\n\ndef test_write_geotiff_str_crs(tmpdir, odc_style_xr_dataset):\n \"\"\"Ensure the geotiff helper writer works, and supports crs as a string.\"\"\"\n filename = tmpdir + '/test.tif'\n\n original_crs = odc_style_xr_dataset.crs\n\n odc_style_xr_dataset.attrs['crs'] = str(original_crs)\n\n with pytest.warns(DeprecationWarning):\n write_geotiff(filename, odc_style_xr_dataset)\n\n assert filename.exists()\n\n with rasterio.open(str(filename)) as src:\n written_data = src.read(1)\n\n assert (written_data == odc_style_xr_dataset['B10']).all()\n\n odc_style_xr_dataset = remove_crs(odc_style_xr_dataset)\n with pytest.raises(ValueError):\n with pytest.warns(DeprecationWarning):\n write_geotiff(filename, odc_style_xr_dataset)\n\n\ndef test_testutils_mk_sample():\n pp = mk_sample_product('tt', measurements=[('aa', 'int16', -999),\n ('bb', 'float32', np.nan)])\n assert set(pp.measurements) == {'aa', 'bb'}\n\n pp = mk_sample_product('tt', measurements=['aa', 'bb'])\n assert set(pp.measurements) == {'aa', 'bb'}\n\n pp = mk_sample_product('tt', measurements=[dict(name=n) for n in ['aa', 'bb']])\n assert set(pp.measurements) == {'aa', 'bb'}\n\n with pytest.raises(ValueError):\n mk_sample_product('tt', measurements=[None])\n\n\ndef test_testutils_write_files():\n from datacube.testutils import write_files, assert_file_structure\n\n files = {'a.txt': 'string',\n 'aa.txt': ('line1\\n', 'line2\\n')}\n\n pp = write_files(files)\n assert pp.exists()\n assert_file_structure(pp, files)\n\n # test that we detect missing files\n (pp / 'a.txt').unlink()\n\n with pytest.raises(AssertionError):\n assert_file_structure(pp, files)\n\n with pytest.raises(AssertionError):\n assert_file_structure(pp, {'aa.txt': 3})\n\n with pytest.raises(ValueError):\n write_files({'tt': 3})\n\n\ndef test_part_uri():\n base = 'file:///foo.txt'\n\n for i in range(10):\n assert get_part_from_uri(mk_part_uri(base, i)) == i\n\n assert get_part_from_uri('file:///f.txt') is None\n assert get_part_from_uri('file:///f.txt#something_else') is None\n assert get_part_from_uri('file:///f.txt#part=aa') == 'aa'\n assert get_part_from_uri('file:///f.txt#part=111') == 111\n\n\ndef test_xr_apply():\n src = xr.DataArray(np.asarray([1, 2, 3], dtype='uint8'), dims=['time'])\n dst = xr_apply(src, lambda _, v: v, dtype='float32')\n\n assert dst.dtype.name == 'float32'\n assert dst.shape == src.shape\n assert dst.values.tolist() == [1, 2, 3]\n\n dst = xr_apply(src, lambda _, v: v)\n assert dst.dtype.name == 'uint8'\n assert dst.shape == src.shape\n assert dst.values.tolist() == [1, 2, 3]\n\n dst = xr_apply(src, lambda idx, _, v: idx[0] + v, with_numeric_index=True)\n assert dst.dtype.name == 'uint8'\n assert dst.shape == src.shape\n assert dst.values.tolist() == [0 + 1, 1 + 2, 2 + 3]\n\n\ndef test_sorted_items():\n aa = dict(c=1, b={}, a=[])\n\n assert ''.join(k for k, _ in sorted_items(aa)) == 'abc'\n assert ''.join(k for k, _ in sorted_items(aa, key=lambda x: x)) == 'abc'\n assert ''.join(k for k, _ in sorted_items(aa, reverse=True)) == 'cba'\n\n remap = dict(c=0, a=1, b=2)\n assert ''.join(k for k, _ in sorted_items(aa, key=lambda x: remap[x])) == 'cab'\n\n assert sorted_items(None) == []\n\n\ndef test_default_base_dir(monkeypatch):\n def set_pwd(p):\n if p is None:\n monkeypatch.delenv('PWD')\n else:\n monkeypatch.setenv('PWD', str(p))\n\n cwd = Path('.').resolve()\n\n # Default base dir (once resolved) will never be different from cwd\n assert default_base_dir().resolve() == cwd\n\n # should work when PWD is not set\n set_pwd(None)\n assert 'PWD' not in os.environ\n assert default_base_dir() == cwd\n\n # should work when PWD is not absolute path\n set_pwd('this/is/not/a/valid/path')\n assert default_base_dir() == cwd\n\n # should be cwd when PWD points to some other dir\n set_pwd(cwd / 'deeper')\n assert default_base_dir() == cwd\n\n set_pwd(cwd.parent)\n assert default_base_dir() == cwd\n\n # PWD == cwd\n set_pwd(cwd)\n assert default_base_dir() == cwd\n\n # TODO:\n # - create symlink to current directory in temp\n # - set PWD to that link\n # - make sure that returned path is the same as symlink and different from cwd\n\n\ndef test_time_info():\n from datacube.model.utils import time_info\n from datetime import datetime\n\n date = '2019-03-03T00:00:00'\n ee = time_info(datetime(2019, 3, 3))\n assert ee['extent']['from_dt'] == date\n assert ee['extent']['to_dt'] == date\n assert ee['extent']['center_dt'] == date\n assert len(ee['extent']) == 3\n\n ee = time_info(datetime(2019, 3, 3), key_time=datetime(2019, 4, 4))\n assert ee['extent']['from_dt'] == date\n assert ee['extent']['to_dt'] == date\n assert ee['extent']['center_dt'] == date\n assert ee['extent']['key_time'] == '2019-04-04T00:00:00'\n assert len(ee['extent']) == 4\n\n\ndef test_normalise_path():\n cwd = Path('.').resolve()\n assert normalise_path('.').resolve() == cwd\n\n p = Path('/a/b/c/d.txt')\n assert normalise_path(p) == Path(p)\n assert normalise_path(str(p)) == Path(p)\n\n base = Path('/a/b/')\n p = Path('c/d.txt')\n assert normalise_path(p, base) == (base / p)\n assert normalise_path(str(p), str(base)) == (base / p)\n assert normalise_path(p) == (cwd / p)\n\n with pytest.raises(ValueError):\n normalise_path(p, 'not/absolute/path')\n\n\ndef test_testutils_testimage():\n from datacube.testutils import mk_test_image, split_test_image\n\n for dtype in ('uint16', 'uint32', 'int32', 'float32'):\n aa = mk_test_image(128, 64, dtype=dtype, nodata=None)\n assert aa.shape == (64, 128)\n assert aa.dtype == dtype\n\n xx, yy = split_test_image(aa)\n assert (xx[:, 33] == 33).all()\n assert (xx[:, 127] == 127).all()\n assert (yy[23, :] == 23).all()\n assert (yy[63, :] == 63).all()\n\n\ndef test_testutils_gtif(tmpdir):\n from datacube.testutils import mk_test_image\n from datacube.testutils.io import write_gtiff, rio_slurp\n\n w, h, dtype, nodata, ndw = 96, 64, 'int16', -999, 7\n\n aa = mk_test_image(w, h, dtype, nodata, nodata_width=ndw)\n bb = mk_test_image(w, h, dtype, nodata=None)\n\n assert aa.shape == (h, w)\n assert aa.dtype.name == dtype\n assert aa[10, 30] == (30 << 8) | 10\n assert aa[10, 11] == nodata\n assert bb[10, 11] == (11 << 8) | 10\n\n aa5 = np.stack((aa,) * 5)\n\n fname = pathlib.Path(str(tmpdir / \"aa.tiff\"))\n fname5 = pathlib.Path(str(tmpdir / \"aa5.tiff\"))\n\n aa_meta = write_gtiff(fname, aa, nodata=nodata,\n blocksize=128,\n resolution=(100, -100),\n offset=(12300, 11100),\n overwrite=True)\n\n aa5_meta = write_gtiff(str(fname5), aa5, nodata=nodata,\n resolution=(100, -100),\n offset=(12300, 11100),\n overwrite=True)\n\n assert fname.exists()\n assert fname5.exists()\n\n assert aa_meta.gbox.shape == (h, w)\n assert aa_meta.path is fname\n\n aa_, aa_meta_ = rio_slurp(fname)\n aa5_, aa5_meta_ = rio_slurp(fname5)\n\n assert aa_meta_.path is fname\n\n (sx, _, tx,\n _, sy, ty, *_) = aa5_meta_.transform\n\n assert (tx, ty) == (12300, 11100)\n assert (sx, sy) == (100, -100)\n\n np.testing.assert_array_equal(aa, aa_)\n np.testing.assert_array_equal(aa5, aa5_)\n\n assert aa_meta_.transform == aa_meta.transform\n assert aa5_meta_.transform == aa5_meta.transform\n\n # check that overwrite is off by default\n with pytest.raises(IOError):\n write_gtiff(fname, aa, nodata=nodata,\n blocksize=128)\n\n # check that overwrite re-writes file\n write_gtiff(fname, bb[:32, :32],\n gbox=aa_meta.gbox[:32, :32],\n overwrite=True)\n\n bb_, mm = rio_slurp(fname, (32, 32))\n np.testing.assert_array_equal(bb[:32, :32], bb_)\n\n assert mm.gbox == aa_meta.gbox[:32, :32]\n\n with pytest.raises(ValueError):\n write_gtiff(fname, np.zeros((3, 4, 5, 6)))\n\n\ndef test_testutils_geobox():\n from datacube.testutils.io import dc_crs_from_rio, rio_geobox\n from rasterio.crs import CRS\n from affine import Affine\n\n assert rio_geobox({}) is None\n\n transform = Affine(10, 0, 4676,\n 0, -10, 171878)\n\n shape = (100, 640)\n h, w = shape\n crs = CRS.from_epsg(3578)\n\n meta = dict(width=w, height=h, transform=transform, crs=crs)\n gbox = rio_geobox(meta)\n\n assert gbox.shape == shape\n assert gbox.crs.epsg == 3578\n assert gbox.transform == transform\n\n wkt = '''PROJCS[\"unnamed\",\n GEOGCS[\"NAD83\",\n DATUM[\"North_American_Datum_1983\",\n SPHEROID[\"GRS 1980\",6378137,298.257222101, AUTHORITY[\"EPSG\",\"7019\"]],\n TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6269\"]],\n PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],\n UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],\n ],\n PROJECTION[\"Albers_Conic_Equal_Area\"],\n PARAMETER[\"standard_parallel_1\",61.66666666666666],\n PARAMETER[\"standard_parallel_2\",68],\n PARAMETER[\"latitude_of_center\",59],\n PARAMETER[\"longitude_of_center\",-132.5],\n PARAMETER[\"false_easting\",500000],\n PARAMETER[\"false_northing\",500000],\n UNIT[\"Meter\",1]]\n '''\n\n crs_ = dc_crs_from_rio(CRS.from_wkt(wkt))\n assert crs_.epsg is None\n\n\[email protected](\"test_input,expected\", [\n (\"/foo/bar/file.txt\", False),\n (\"file:///foo/bar/file.txt\", True),\n (\"test.bar\", False),\n (\"s3://mybucket/objname.tiff\", True),\n (\"gs://mybucket/objname.tiff\", True),\n (\"wasb://mybucket/objname.tiff\", True),\n (\"wasbs://mybucket/objname.tiff\", True),\n (\"ftp://host.name/filename.txt\", True),\n (\"https://host.name.com/path/file.txt\", True),\n (\"http://host.name.com/path/file.txt\", True),\n (\"sftp://user:[email protected]/path/file.txt\", True),\n (\"file+gzip://host.name.com/path/file.txt\", True),\n (\"bongo:host.name.com/path/file.txt\", False),\n])\ndef test_is_url(test_input, expected):\n assert is_url(test_input) == expected\n if expected:\n assert as_url(test_input) is test_input\n\n\ndef test_is_almost_int():\n assert is_almost_int(1, 1e-10)\n assert is_almost_int(1.001, .1)\n assert is_almost_int(2 - 0.001, .1)\n assert is_almost_int(-1.001, .1)\n\n\ndef test_maybe_zero():\n assert maybe_zero(0.0001, 0.1) == 0\n assert maybe_zero(-0.0001, 0.1) == 0\n assert maybe_zero(1.5, 0.1) == 1.5\n\n\ndef test_maybe_int():\n assert maybe_int(1, 1e-10) == 1\n assert maybe_int(1.6, .1) == 1.6\n assert maybe_int(-1.6, .1) == -1.6\n assert maybe_int(1.001, .1) == 1\n assert maybe_int(2 - 0.001, .1) == 2\n assert maybe_int(-1.001, .1) == -1\n assert maybe_int(1.1, .1) == 1.1\n for x in [3/7, 7/3, -13.7878]:\n assert maybe_int(x, 1e-10) is x\n\n\ndef test_snap_scale():\n assert snap_scale(0.9999999) == 1\n assert snap_scale(-0.9999999) == -1\n for x in [0.0, 0.999, 0.621612621868, 3/7, 7/3]:\n assert snap_scale(x) is x\n x = -x\n assert snap_scale(x) is x\n assert snap_scale(0.33333331) == 1/3\n assert snap_scale(-0.33333331) == -1/3\n\n\ndef test_valid_mask():\n xx = np.zeros((4, 8), dtype='float32')\n mm = valid_mask(xx, 0)\n assert mm.dtype == 'bool'\n assert mm.shape == xx.shape\n assert not mm.all()\n assert not mm.any()\n nn = invalid_mask(xx, 0)\n assert nn.dtype == 'bool'\n assert nn.shape == xx.shape\n assert nn.all()\n assert nn.any()\n\n mm = valid_mask(xx, 13)\n assert mm.dtype == 'bool'\n assert mm.shape == xx.shape\n assert mm.all()\n nn = invalid_mask(xx, 13)\n assert nn.dtype == 'bool'\n assert nn.shape == xx.shape\n assert not nn.any()\n\n mm = valid_mask(xx, None)\n assert mm.dtype == 'bool'\n assert mm.shape == xx.shape\n assert mm.all()\n nn = invalid_mask(xx, None)\n assert nn.dtype == 'bool'\n assert nn.shape == xx.shape\n assert not nn.any()\n\n mm = valid_mask(xx, np.nan)\n assert mm.dtype == 'bool'\n assert mm.shape == xx.shape\n assert mm.all()\n nn = invalid_mask(xx, np.nan)\n assert nn.dtype == 'bool'\n assert nn.shape == xx.shape\n assert not nn.any()\n\n xx[0, 0] = np.nan\n mm = valid_mask(xx, np.nan)\n assert not mm[0, 0]\n assert mm.sum() == (4 * 8 - 1)\n nn = invalid_mask(xx, np.nan)\n assert nn[0, 0]\n assert nn.sum() == 1\n\n\ndef test_num2numpy():\n assert num2numpy(None, 'int8') is None\n assert num2numpy(-1, 'int8').dtype == np.dtype('int8')\n assert num2numpy(-1, 'int8').dtype == np.int8(-1)\n\n assert num2numpy(-1, 'uint8') is None\n assert num2numpy(256, 'uint8') is None\n assert num2numpy(-1, 'uint16') is None\n assert num2numpy(-1, 'uint32') is None\n assert num2numpy(-1, 'uint8', ignore_range=True) == np.uint8(255)\n\n assert num2numpy(0, 'uint8') == 0\n assert num2numpy(255, 'uint8') == 255\n assert num2numpy(-128, 'int8') == -128\n assert num2numpy(127, 'int8') == 127\n assert num2numpy(128, 'int8') is None\n\n assert num2numpy(3.3, np.dtype('float32')).dtype == np.dtype('float32')\n assert num2numpy(3.3, np.float32).dtype == np.dtype('float32')\n assert num2numpy(3.3, np.float64).dtype == np.dtype('float64')\n\n\ndef test_utils_datares():\n assert data_resolution_and_offset(np.array([1.5, 2.5, 3.5])) == (1.0, 1.0)\n assert data_resolution_and_offset(np.array([5, 3, 1])) == (-2.0, 6.0)\n assert data_resolution_and_offset(np.array([5, 3])) == (-2.0, 6.0)\n assert data_resolution_and_offset(np.array([1.5]), 1) == (1.0, 1.0)\n\n with pytest.raises(ValueError):\n data_resolution_and_offset(np.array([]))\n\n with pytest.raises(ValueError):\n data_resolution_and_offset(np.array([]), 10)\n\n with pytest.raises(ValueError):\n data_resolution_and_offset(np.array([1]))\n\n\ndef test_utils_affine_from_axis():\n assert affine_from_axis(np.asarray([1.5, 2.5, 3.5]),\n np.asarray([10.5, 11.5])) * (0, 0) == (1.0, 10.0)\n\n assert affine_from_axis(np.asarray([1.5, 2.5, 3.5]),\n np.asarray([10.5, 11.5])) * (2, 1) == (3, 11)\n\n (sx, z1, tx,\n z2, sy, ty, *_) = affine_from_axis(np.asarray([1, 2, 3]),\n np.asarray([10, 20]))\n assert z1 == 0 and z2 == 0\n assert sx == 1 and sy == 10\n assert tx == 0.5 and ty == 5\n\n (sx, _, tx,\n _, sy, ty, *_) = affine_from_axis(np.asarray([1]),\n np.asarray([10, 20]), 1)\n assert sx == 1 and sy == 10\n assert tx == 0.5 and ty == 5\n\n (sx, _, tx,\n _, sy, ty, *_) = affine_from_axis(np.asarray([1]),\n np.asarray([10, 20]), (1, 1))\n assert sx == 1 and sy == 10\n assert tx == 0.5 and ty == 5\n\n (sx, _, tx,\n _, sy, ty, *_) = affine_from_axis(np.asarray([1]),\n np.asarray([10]), (2, 10))\n assert sx == 2 and sy == 10\n assert tx == 0 and ty == 5\n\n\ndef test_utils_math():\n xx = xr.DataArray(np.zeros((3, 4)),\n name='xx',\n dims=('y', 'x'),\n coords={'x': np.arange(4),\n 'y': np.arange(3)})\n xx_t = unsqueeze_data_array(xx, 'time', 0)\n assert xx_t.dims == ('time', 'y', 'x')\n assert 'time' in xx_t.coords\n assert xx_t.data.shape == (1, 3, 4)\n\n ds = unsqueeze_dataset(xx.to_dataset(), 'time')\n assert ds.xx.dims == ('time', 'y', 'x')\n assert 'time' in ds.xx.coords\n assert ds.xx.data.shape == (1, 3, 4)\n\n\ndef test_spatial_dims():\n def tt(d1, d2):\n coords = {}\n coords[d1] = np.arange(3)\n coords[d2] = np.arange(4)\n return xr.DataArray(np.zeros((3, 4)),\n name='xx',\n dims=(d1, d2),\n coords=coords)\n\n assert spatial_dims(tt('y', 'x')) == ('y', 'x')\n assert spatial_dims(tt('x', 'y')) == ('y', 'x')\n assert spatial_dims(tt('latitude', 'longitude')) == ('latitude', 'longitude')\n assert spatial_dims(tt('lat', 'lon')) == ('lat', 'lon')\n assert spatial_dims(tt('a', 'b')) is None\n assert spatial_dims(tt('a', 'b'), relaxed=True) == ('a', 'b')\n\n\ndef test_check_write_path(tmpdir):\n tmpdir = Path(str(tmpdir))\n some_path = tmpdir/\"_should_not_exist-5125177.txt\"\n assert not some_path.exists()\n assert check_write_path(some_path, overwrite=False) is some_path\n assert check_write_path(str(some_path), overwrite=False) == some_path\n assert isinstance(check_write_path(str(some_path), overwrite=False), Path)\n\n p = tmpdir/\"ttt.tmp\"\n with open(str(p), 'wt') as f:\n f.write(\"text\")\n\n assert p.exists()\n with pytest.raises(IOError):\n check_write_path(p, overwrite=False)\n\n assert check_write_path(p, overwrite=True) == p\n assert not p.exists()\n"
] |
[
[
"pandas.to_datetime",
"numpy.asarray",
"numpy.uint8",
"numpy.arange",
"numpy.int8",
"numpy.dtype",
"numpy.stack",
"numpy.testing.assert_array_equal",
"numpy.array",
"numpy.zeros"
]
] |
[
{
"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": []
}
] |
kwryankrattiger/xmsinterp
|
[
"c3d7ffda8851acd328068e144db1a6120bd77c26"
] |
[
"_package/tests/unit_tests/interp_idw_pyt.py"
] |
[
"\"\"\"Test InterpIdw_py.cpp.\"\"\"\nimport unittest\n\nimport numpy as np\n\nfrom xms.core.misc import Observer\n\nfrom xms.interp.interpolate import InterpIdw\n\n\nclass MockObserver(Observer):\n \"\"\"Mock Observer class for testing.\"\"\"\n def __init__(self, obs_id=\"X\"):\n \"\"\"Constructor.\n\n Args:\n obs_id (str): Id of the observer\n \"\"\"\n self.status = {\n 'operation': None,\n 'operation_end': False,\n 'operation_begin': False,\n 'percent_complete': None,\n 'message': '',\n 'remaining_seconds': None,\n 'elapsed_seconds': None,\n 'obs_id': obs_id\n }\n super(MockObserver, self).__init__()\n\n def __str__(self):\n \"\"\"Returns a string representation of the mock observer.\"\"\"\n return str(self.status)\n\n def on_progress_status(self, percent_complete):\n \"\"\"Update progress status.\n\n Args:\n percent_complete (float): The percent of the operation completed\n \"\"\"\n self.status['percent_complete'] = percent_complete\n\n def on_begin_operation_string(self, operation):\n \"\"\"Called when an operation begins.\n\n Args:\n operation (str): Name of the operation\n \"\"\"\n self.status['operation_begin'] = True\n self.status['operation'] = operation\n\n def on_end_operation(self):\n \"\"\"Called when an operation ends.\"\"\"\n self.status['operation_end'] = True\n\n def on_update_message(self, message):\n \"\"\"Update the progress message.\n\n Args:\n message (str): The new progress message\n \"\"\"\n self.status['message'] = message\n\n def time_remaining_in_seconds(self, remaining_seconds):\n \"\"\"Update the remaining time in seconds.\n\n Args:\n remaining_seconds (float): The remaining time in seconds\n \"\"\"\n self.status['remaining_seconds'] = remaining_seconds\n\n def time_elapsed_in_seconds(self, elapsed_seconds):\n \"\"\"Update the elapsed time in seconds.\n\n Args:\n elapsed_seconds (float): The elapsed time in seconds\n \"\"\"\n self.status['elapsed_seconds'] = elapsed_seconds\n\n\nclass TestInterpIdw(unittest.TestCase):\n \"\"\"Test IDW Interpolation Class.\"\"\"\n\n def setUp(self):\n \"\"\"Set up for each test case.\"\"\"\n pts = ((1, 2, 3), (1, 2, 3), (1, 2, 3))\n self.interp_idw_obj = InterpIdw(pts)\n\n def test_set_pts(self):\n \"\"\"Set base points.\"\"\"\n interp = self.interp_idw_obj\n # Test that the a proper call does not throw\n interp.set_points(((1, 2, 3), (1, 2, 3), (3, 3, 3)), False)\n\n def test_set_pts_2d(self):\n \"\"\"Set base points.\"\"\"\n interp = self.interp_idw_obj\n # Test that the a proper call does not throw\n interp.set_points(((1, 2, 3), (1, 2, 3), (3, 3, 3)), True)\n\n def test_interp_to_pt(self):\n \"\"\"Interpolate to a specific point.\"\"\"\n interp = self.interp_idw_obj\n val = interp.interpolate_to_point((1, 2, 3))\n self.assertEqual(3.0, val)\n\n def test_interp_to_pts(self):\n \"\"\"Interpolate to multiple points.\"\"\"\n pts = ((0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3))\n interp = InterpIdw(pts)\n ret = interp.interpolate_to_points(np.array([(2.0, 1.0, 0.0), (5.0, 10.0, 2.5)]))\n np.testing.assert_array_almost_equal((0.02681550197303295, 2.5), ret)\n\n def test_interp_to_pts_numpy(self):\n \"\"\"Interpolate to multiple points.\"\"\"\n pts = np.array([(0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3)])\n interp = InterpIdw(pts)\n ret = interp.interpolate_to_points(np.array(((2.0, 1.0, 0.0), (5.0, 10.0, 2.5))))\n self.assertIsInstance(ret, np.ndarray)\n np.testing.assert_array_equal(np.array([0.02681550197303295, 2.5]), ret)\n\n def test_set_pt_activity(self):\n \"\"\"Setting point activity.\"\"\"\n pts = ((0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3))\n tris = (0, 1, 3, 1, 2, 3)\n interp = InterpIdw(pts, tris)\n act1 = (True, False, False, True)\n interp.point_activity = act1\n\n act2 = (0, 1, 0, 1)\n interp.point_activity = act2\n\n def test_triangle_activity(self):\n \"\"\"Setting tri activity.\"\"\"\n pts = ((0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3))\n tris = (0, 1, 3, 1, 2, 3)\n interp = InterpIdw(pts, tris)\n act1 = (True, False)\n interp.triangle_activity = act1\n\n act2 = (1, 1)\n interp.triangle_activity = act2\n\n def test_get_pts(self):\n \"\"\"Getting interp object points.\"\"\"\n pts = np.array([(0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3)])\n tris = np.array([0, 1, 3, 1, 2, 3])\n interp = InterpIdw(pts, tris)\n\n ret = interp.points\n np.testing.assert_array_equal(pts, ret)\n\n def test_get_tris(self):\n \"\"\"Getting interp object points.\"\"\"\n pts = np.array([(0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3)])\n tris = np.array([0, 1, 3, 1, 2, 3])\n interp = InterpIdw(pts, tris)\n\n ret = interp.triangles\n np.testing.assert_array_equal(tris, ret)\n\n def test_set_trunc(self):\n \"\"\"Test set_trunc.\"\"\"\n t_min = 7.11\n t_max = 11.7\n\n pts = np.array([(0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3)])\n tris = np.array([0, 1, 3, 1, 2, 3])\n interp = InterpIdw(pts, tris)\n\n interp.set_truncation(t_max, t_min)\n self.assertEquals(t_min, interp.truncate_min)\n self.assertEquals(t_max, interp.truncate_max)\n\n def test_set_observer(self):\n \"\"\"Test set_observer.\"\"\"\n observer1 = MockObserver(\"Obs1\")\n observer2 = MockObserver(\"Obs2\")\n\n pts = ((0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3))\n tris = (0, 1, 3, 1, 2, 3)\n interp = InterpIdw(pts, tris)\n\n # Non-Observer Type\n with self.assertRaises(TypeError) as context:\n interp.set_observer(\"xyz\")\n err = context.exception\n self.assertIn(\"SetObserver(): incompatible function arguments.\", str(err))\n\n interp.set_observer(observer1)\n interp.interpolate_to_points(np.random.rand(100000, 3) + 5)\n self.assertGreater(observer1.status['percent_complete'], 0.0)\n self.assertGreater(observer1.status['elapsed_seconds'], 0.0)\n\n interp.set_observer(observer2)\n interp.interpolate_to_points(np.random.rand(100000, 3) + 5)\n self.assertGreater(observer2.status['percent_complete'], 0.0)\n self.assertGreater(observer2.status['elapsed_seconds'], 0.0)\n\n def test_set_power(self):\n \"\"\"Set power on InterpIdw objects.\"\"\"\n interp = self.interp_idw_obj\n\n # None Type\n with self.assertRaises(TypeError) as context:\n interp.power = None\n err = context.exception\n self.assertIn(\"SetPower(): incompatible function arguments.\", str(err))\n\n # Non-number Type\n with self.assertRaises(TypeError) as context:\n interp.power = \"xyz\"\n err = context.exception\n self.assertIn(\"SetPower(): incompatible function arguments.\", str(err))\n\n # Good arguments\n power = 10\n interp.power = power\n self.assertEquals(power, interp.power)\n\n def test_set_search_opts(self):\n \"\"\"Ensure the tutorial will work.\"\"\"\n interp = self.interp_idw_obj\n typeerror = \"SetSearchOpts(): incompatible function arguments.\"\n\n # No Arguments\n with self.assertRaises(TypeError) as context:\n interp.set_search_options()\n err = context.exception\n\n # One Arguments\n with self.assertRaises(TypeError) as context:\n interp.set_search_options(123)\n err = context.exception\n\n # None Arguments\n with self.assertRaises(TypeError) as context:\n interp.set_search_options(None, None)\n err = context.exception\n self.assertIn(typeerror, str(err))\n\n # Bad Argument\n with self.assertRaises(TypeError) as context:\n interp.set_search_options(\"123\", False)\n err = context.exception\n self.assertIn(typeerror, str(err))\n\n # Good Arguments\n interp.set_search_options(10, True)\n\n interp.set_search_options(15, False)\n\n def test_set_weight_calc_method(self):\n \"\"\"Setting weight calc method with enum.\"\"\"\n interp = self.interp_idw_obj\n\n # None Argument\n with self.assertRaises(ValueError) as context:\n interp.weight_calculation_method = None\n err = context.exception\n none_value_error = '\"weights\" must be one of {}, not None'.format(', '.join(InterpIdw.weights))\n self.assertIn(none_value_error, str(err))\n\n # Bad Arguments\n with self.assertRaises(ValueError) as context:\n interp.weight_calculation_method = \"bad_string\"\n err = context.exception\n err_str = '\"weights\" must be one of {}, not bad_string'.format(', '.join(InterpIdw.weights))\n self.assertIn(err_str, str(err))\n\n with self.assertRaises(ValueError) as context:\n interp.weight_calculation_method = 123\n err = context.exception\n err_str = '\"weights\" must be one of {}, not 123'.format(', '.join(InterpIdw.weights))\n self.assertIn(err_str, str(err))\n\n # Valid Arguments\n\n interp.weight_calculation_method = \"modified\"\n\n interp.weight_calculation_method = \"classic\"\n\n def test_set_nodal_function(self):\n \"\"\"Setting nodal function.\"\"\"\n observer = MockObserver()\n typeerror = \"SetNodalFunction(): incompatible function arguments.\"\n\n pts = np.array([(0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3)])\n tris = np.array([0, 1, 3, 1, 2, 3])\n interp = InterpIdw(pts, tris)\n\n # No Argument\n interp.set_nodal_function()\n\n # None Args for each argument\n with self.assertRaises(ValueError) as context:\n interp.set_nodal_function(None, 1, True, observer)\n err = context.exception\n func_type_error = '\"nodal_function_type\" must be one of {}, not None'.format(\n \", \".join(InterpIdw.nodal_function_types))\n self.assertIn(func_type_error, str(err))\n with self.assertRaises(TypeError) as context:\n interp.set_nodal_function(\"constant\", None, True, observer)\n err = context.exception\n self.assertIn(typeerror, str(err))\n\n # Bad Args\n with self.assertRaises(ValueError) as context:\n interp.set_nodal_function(1, 1, True, observer)\n err = context.exception\n func_type_error = '\"nodal_function_type\" must be one of {}, not 1'.format(\n \", \".join(InterpIdw.nodal_function_types))\n self.assertIn(func_type_error, str(err))\n with self.assertRaises(ValueError) as context:\n interp.set_nodal_function(\"abc\", 1, True, observer)\n err = context.exception\n err_str = '\"nodal_function_type\" must be one of {}, not abc'.format(\n \", \".join(InterpIdw.nodal_function_types))\n self.assertIn(err_str, str(err))\n with self.assertRaises(TypeError) as context:\n interp.set_nodal_function(\"constant\", \"1234\", True, observer)\n err = context.exception\n self.assertIn(typeerror, str(err))\n with self.assertRaises(TypeError) as context:\n interp.set_nodal_function(\"constant\", 1.4, True, observer)\n err = context.exception\n self.assertIn(typeerror, str(err))\n with self.assertRaises(ValueError) as context:\n interp.set_nodal_function(\"constant\", 1, True, 1)\n err_str = \"observer must be of type xmscore.misc.Observer\"\n err = context.exception\n self.assertIn(err_str, str(err))\n with self.assertRaises(ValueError) as context:\n interp.set_nodal_function(\"constant\", 1, True, \"abcd\")\n err = context.exception\n self.assertIn(err_str, str(err))\n\n # Good Args\n base = str(interp)\n interp.set_nodal_function(\"constant\", 7, True, observer)\n self.assertEqual(base, str(interp))\n\n interp.set_nodal_function(\"gradient_plane\", 9, True, observer)\n # TODO: Removed to_string checks. Need another way to test this\n\n interp.set_nodal_function(\"quadratic\", 11, True, observer)\n # TODO: Removed to_string checks. Need another way to test this\n\n def test_interpolate_weights(self):\n \"\"\"Test interpolate_weights.\"\"\"\n pts = ((0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3))\n tris = (0, 1, 3, 1, 2, 3)\n interp = InterpIdw(pts, tris)\n\n idxs, wts = interp.interpolate_weights((5, 5, 2))\n np.testing.assert_array_equal(np.array([0, 1, 2, 3], np.int32), idxs)\n np.testing.assert_array_equal(np.array([0.25, 0.25, 0.25, 0.25]), wts)\n\n idxs, wts = interp.interpolate_weights((10, 10, 0))\n np.testing.assert_array_equal(np.array([2], np.int32), idxs)\n np.testing.assert_array_equal(np.array([1.]), wts)\n\n idxs, wts = interp.interpolate_weights((-10, -10, -10))\n np.testing.assert_array_equal(np.array([0, 1, 2, 3], np.int32), idxs)\n np.testing.assert_array_almost_equal(np.array([0.876919, 0.06154,\n 0.0, 0.06154]), wts, decimal=5)\n\n def test_set_multi_threading(self):\n \"\"\"Setting multi threading.\"\"\"\n interp = self.interp_idw_obj\n interp.set_multithreading(False)\n interp.set_multithreading(True)\n\n def test_tutorial(self):\n \"\"\"Ensure the tutorial will work.\"\"\"\n pts = ((0, 0, 0), (10, 0, 1), (10, 10, 2), (0, 10, 3))\n tris = ()\n tris2 = (0, 1, 3, 1, 2, 3)\n\n interp = InterpIdw(pts, tris)\n val = interp.interpolate_to_point((5, 5, 0))\n self.assertEqual(1.5, val)\n\n interp = InterpIdw(pts, tris2)\n val2 = interp.interpolate_to_point((5, 5, 0))\n self.assertEqual(1.5, val2)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.testing.assert_array_equal",
"numpy.array",
"numpy.random.rand",
"numpy.testing.assert_array_almost_equal"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rafaelmm82/learning
|
[
"c8cd7408404dbbcc0af3ae0a18c6c311d4003269"
] |
[
"mlfrancais/Partie 1 - Data Preprocessing/01 - Data Preprocessing.py"
] |
[
"'''\ncours en france de machine learning\nGithub: @rafaelmm82\n'''\n\n# Importer les librairies\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# La gestion des données\n# ----------------------\n\n# Importer le dataset\nfilename = 'mlfrancais/Partie 1 - Data Preprocessing/Data.csv'\ndataset = pd.read_csv(filename, header=0)\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, -1].values\n\n\n# Gérer les données manquantes\nfrom sklearn.impute import SimpleImputer\nimputer = SimpleImputer(missing_values=np.nan, strategy='mean')\nimputer.fit(X[:, 1:])\nX[:, 1:] = imputer.transform(X[:, 1:])\n\n# on peut fait de comparaison du description de donnéés e le resultat avec le imputer\n# dataset.describe()\n# print(imputer.transform(X[:, 1:]))\n\n\n# Gérer les variable catéoriques\nfrom sklearn.preprocessing import LabelEncoder, LabelBinarizer\n\nbinarizer = LabelBinarizer()\nnew_columns = binarizer.fit_transform(X[:, 0])\nX = np.column_stack((new_columns, X[:,1:]))\n\nlabel_enc = LabelEncoder()\ny = label_enc.fit_transform(y)\n\n\n# Diviser le dataset entre le Training set et le Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\n\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\n\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\n"
] |
[
[
"pandas.read_csv",
"sklearn.impute.SimpleImputer",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.LabelBinarizer",
"numpy.column_stack",
"sklearn.preprocessing.StandardScaler",
"sklearn.preprocessing.LabelEncoder"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
jvishnuvardhan/probability
|
[
"a408f8fbde831a40df3fb10023deaf997d104b24",
"a408f8fbde831a40df3fb10023deaf997d104b24"
] |
[
"tensorflow_probability/python/internal/backend/numpy/numpy_array.py",
"tensorflow_probability/python/distributions/gamma.py"
] |
[
"# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Numpy implementations of TensorFlow general top-level functions.\"\"\"\n\nimport functools\n# Dependency imports\nimport numpy as np\nimport numpy as onp # pylint: disable=reimported\n\nfrom tensorflow_probability.python.internal.backend.numpy import _utils as utils\nfrom tensorflow_probability.python.internal.backend.numpy import ops\nfrom tensorflow_probability.python.internal.backend.numpy.linalg_impl import einsum\nfrom tensorflow_probability.python.internal.backend.numpy.linalg_impl import norm\nfrom tensorflow_probability.python.internal.backend.numpy.linalg_impl import tensordot\n\n\n__all__ = [\n 'concat',\n 'einsum',\n 'expand_dims',\n 'fill',\n 'gather',\n 'gather_nd',\n 'linspace',\n 'meshgrid',\n 'norm',\n 'one_hot',\n 'ones',\n 'ones_like',\n 'pad',\n 'range',\n 'rank',\n 'reshape',\n 'reverse',\n 'repeat',\n 'roll',\n 'sequence_mask',\n 'searchsorted',\n 'shape',\n 'size',\n 'slice',\n 'split',\n 'squeeze',\n 'stack',\n 'tensordot',\n 'tile',\n 'transpose',\n 'unstack',\n 'where',\n 'zeros',\n 'zeros_like',\n # 'boolean_mask',\n # 'foldl',\n # 'foldr',\n]\n\n\nJAX_MODE = False\n\n\nif JAX_MODE:\n import jax # pylint: disable=g-import-not-at-top\n\n\ndef _astuple(x):\n try:\n return tuple(x)\n except TypeError:\n return x\n\n\ndef _gather( # pylint: disable=unused-argument\n params,\n indices,\n validate_indices=None,\n axis=None,\n batch_dims=0,\n name=None):\n \"\"\"gather.\"\"\"\n indices = ops.convert_to_tensor(indices, dtype_hint=np.int32)\n if validate_indices is not None:\n raise NotImplementedError(\n 'Argument `validate_indices != None` is currently unimplemented.')\n if batch_dims < 0:\n raise NotImplementedError('Negative `batch_dims` is currently unsupported.')\n if axis is None:\n axis = batch_dims\n if axis < 0:\n axis = axis + len(params.shape)\n # NOTE: For only the numpy backend, this function could create a single result\n # ndarray and use in-place updates. For the Jax backend, this function\n # vmaps `np.take`.\n if JAX_MODE:\n params = np.asarray(params)\n indices = np.asarray(indices)\n take = lambda params, indices: np.take(params, indices, # pylint: disable=g-long-lambda\n axis=axis - batch_dims)\n take = functools.reduce(\n lambda g, f: f(g), [jax.vmap] * int(batch_dims),\n take\n )\n return take(params, indices)\n params = ops.convert_to_tensor(params)\n res = np.array([\n np.take(params[i], indices[i], axis=axis - batch_dims)\n for i in np.ndindex(*params.shape[:batch_dims])\n ])\n return np.reshape(\n res,\n params.shape[:axis] + indices.shape[batch_dims:] + params.shape[axis+1:])\n\n\ndef _args_to_matching_arrays(args_list, dtype_hint=None):\n \"\"\"Converts a list to array using the first element for dtype.\n\n This method is used to match the behavior of `tf.concat`.\n\n Args:\n args_list: A list or tuple of arguments.\n dtype_hint: An optional hint used when converting the args to tensors.\n Returns:\n A list of tensors.\n \"\"\"\n dtype = None\n for arg in args_list:\n if ops.is_tensor(arg):\n dtype = arg.dtype\n break\n if dtype is None:\n ret = []\n for arg in args_list:\n ret.append(ops.convert_to_tensor(arg, dtype, dtype_hint=dtype_hint))\n if dtype is None:\n dtype = ret[-1].dtype\n else:\n ret = [ops.convert_to_tensor(arg, dtype) for arg in args_list]\n return ret\n\n\ndef _concat(values, axis, name='concat'):\n del name\n if axis is None:\n raise ValueError('None values for `axis` argument not supported.')\n if not isinstance(values, (list, tuple)):\n values = [values]\n if len(values) == 1:\n return values[0]\n values = _args_to_matching_arrays(values)\n return np.concatenate(values, axis=axis)\n\n\ndef _gather_nd_single(params, indices):\n idx = tuple(np.moveaxis(indices, -1, 0))\n return params[idx]\n\n\ndef _gather_nd( # pylint: disable=unused-argument\n params,\n indices,\n batch_dims=0,\n name=None):\n \"\"\"gather_nd.\"\"\"\n params = ops.convert_to_tensor(params)\n indices = ops.convert_to_tensor(indices, dtype_hint=np.int32)\n if batch_dims < 0:\n raise NotImplementedError('Negative `batch_dims` is currently unsupported.')\n if not JAX_MODE and batch_dims > 0:\n raise NotImplementedError(\n '`batch_dims > 0` currently unsupported in NumPy backend.')\n gather_nd_ = _gather_nd_single\n if JAX_MODE:\n gather_nd_ = functools.reduce(\n lambda g, f: f(g), [jax.vmap] * int(batch_dims),\n gather_nd_\n )\n return gather_nd_(params, indices)\n\n\ndef _linspace(start, stop, num, name=None, axis=0): # pylint: disable=unused-argument\n \"\"\"Match TF behavior with np.linspace.\"\"\"\n start = ops.convert_to_tensor(start)\n # Match TF weirdness arising from truediv(int32, int32) = float64\n if np.issubdtype(start.dtype, np.integer):\n start = start.astype(np.float64)\n stop = ops.convert_to_tensor(stop, dtype=start.dtype)\n if not np.issubdtype(np.array(num).dtype, np.integer):\n raise TypeError('`num` must be an integer but got {}'.format(num.dtype))\n return np.linspace(start, stop, int(num), axis=axis).astype(start.dtype)\n\n\ndef _one_hot( # pylint: disable=unused-argument\n indices,\n depth,\n on_value=None,\n off_value=None,\n axis=None,\n dtype=None,\n name=None):\n \"\"\"One hot.\"\"\"\n if on_value is None:\n on_value = 1\n if off_value is None:\n off_value = 0\n if dtype is None:\n dtype = utils.common_dtype([on_value, off_value], np.float32)\n else:\n dtype = utils.numpy_dtype(dtype)\n indices = np.array(indices)\n pred = abs(np.arange(depth, dtype=indices.dtype) -\n indices[..., np.newaxis]) > 0\n y_out = np.where(pred, np.array(off_value, dtype), np.array(on_value, dtype))\n if axis is not None:\n y_out = np.moveaxis(y_out, -1, axis)\n return y_out\n\n\ndef _ones_like(input, dtype=None, name=None): # pylint: disable=redefined-builtin,unused-argument\n return np.ones_like(ops.convert_to_tensor(input),\n dtype=utils.numpy_dtype(dtype))\n\n\n# TODO(b/136555907): Add unit-test.\ndef _pad( # pylint: disable=unused-argument\n tensor,\n paddings,\n mode='CONSTANT',\n constant_values=0,\n name=None):\n tensor = ops.convert_to_tensor(tensor)\n constant_values = ops.convert_to_tensor(constant_values)\n return np.pad(\n tensor, paddings,\n mode=mode.lower(),\n constant_values=constant_values)\n\n\ndef _range(start, limit=None, delta=1, dtype=None, name='range'): # pylint: disable=unused-argument\n \"\"\"Emulates tf.range.\"\"\"\n # Emulating dtype inference logic from tf.range\n dtype = utils.numpy_dtype(dtype)\n infer_dtype = lambda t: ops.convert_to_tensor(t, dtype=dtype).dtype\n # We must keep start, limit, and delta static np.array since they determine\n # the size of the result array, which JAX requires to be static.\n start = onp.array(start, dtype=infer_dtype(start))\n limit = None if limit is None else onp.array(limit, dtype=infer_dtype(limit))\n delta = onp.array(delta, dtype=infer_dtype(delta))\n if dtype is None:\n dtype_hierarchy = [np.int32, np.int64, np.float32, np.float64]\n inferred_dtype = max([arg.dtype for arg in [start, limit, delta]\n if arg is not None],\n key=dtype_hierarchy.index)\n else:\n inferred_dtype = dtype\n return np.arange(start, limit, delta).astype(inferred_dtype)\n\n\ndef _reverse(tensor, axis, name=None): # pylint: disable=unused-argument\n if np.array(axis).ndim == 0:\n return np.flip(tensor, axis)\n for ax in axis:\n tensor = np.flip(tensor, ax)\n return tensor\n\n\ndef _sequence_mask(lengths, maxlen=None, dtype=np.bool_, name=None): # pylint: disable=unused-argument\n lengths = np.array(lengths, dtype=np.int32)\n if maxlen is None:\n maxlen = np.max(lengths).astype(lengths.dtype)\n return (np.arange(maxlen) < lengths[..., np.newaxis]).astype(dtype)\n\n\nif JAX_MODE:\n _searchsorted_vmap_sides = {\n side: jax.vmap(functools.partial(jax.numpy.searchsorted, side=side))\n for side in ('left', 'right')\n }\n\n\ndef _searchsorted( # pylint: disable=unused-argument\n sorted_sequence,\n values,\n side='left',\n out_type=np.int32,\n name=None):\n \"\"\"Find indices for insertion for list to remain sorted.\"\"\"\n if JAX_MODE:\n try:\n func = _searchsorted_vmap_sides[side]\n except KeyError:\n raise ValueError(\"'%s' is an invalid value for keyword 'side'\" % side)\n sorted_sequence_2d = np.reshape(sorted_sequence,\n (-1, sorted_sequence.shape[-1]))\n values_2d = np.reshape(values, (-1, values.shape[-1]))\n if sorted_sequence_2d.shape[0] != values_2d.shape[0]:\n raise ValueError('Leading dim_size of both tensors must match.')\n return np.reshape(func(sorted_sequence_2d, values_2d).astype(out_type),\n values.shape)\n # We don't use np.searchsorted in the numpy backend because it doesn't support\n # batching.\n sorted_sequence = sorted_sequence[..., np.newaxis, :]\n values = values[..., :, np.newaxis]\n if side == 'left':\n is_in_right_location = sorted_sequence < values\n elif side == 'right':\n is_in_right_location = sorted_sequence <= values\n return np.sum(is_in_right_location, axis=-1).astype(out_type)\n\n\ndef _shape(input, out_type=np.int32, name=None): # pylint: disable=redefined-builtin,unused-argument\n return ops.convert_to_tensor(ops.convert_to_tensor(input).shape).astype(\n out_type)\n\n\ndef _size(input, out_type=np.int32, name=None): # pylint: disable=redefined-builtin, unused-argument\n return np.asarray(\n onp.prod(ops.convert_to_tensor(input).shape), dtype=out_type)\n\n\nbuiltin_slice = slice # pylint: disable=invalid-name\n\n\ndef _slice(input_, begin, size, name=None): # pylint: disable=unused-argument,redefined-outer-name\n if JAX_MODE:\n input_ = np.asarray(input_)\n size = [dim_size - start if size == -1 else size\n for (size, start, dim_size) in zip(size, begin, input_.shape)]\n return jax.lax.dynamic_slice(input_, begin, size)\n slices = tuple(\n builtin_slice(b, b + s if s != -1 else None) for b, s in zip(begin, size))\n return input_[slices]\n\n\ndef _split(value, num_or_size_splits, axis=0, num=None, name='split'): # pylint: disable=unused-argument\n \"\"\"Map tf.split -> np.split.\"\"\"\n if np.isscalar(num_or_size_splits):\n return np.split(value, num_or_size_splits, axis)\n\n indices_or_sections = onp.array(num_or_size_splits)\n if indices_or_sections.ndim == 1:\n if any(idx == -1 for idx in indices_or_sections):\n # Numpy parameterizes by split indices and returns nsplits+1 arrays.\n total_splits = sum(idx for idx in indices_or_sections if idx != -1)\n remainder = int(max(0, np.array(value).shape[axis] - total_splits))\n indices_or_sections = [\n idx if idx != -1 else remainder for idx in indices_or_sections\n ]\n indices_or_sections = onp.cumsum(onp.array(indices_or_sections))[:-1]\n return np.split(value, indices_or_sections, axis)\n\n\ndef _transpose(a, perm=None, conjugate=False, name='transpose'): # pylint: disable=unused-argument\n x = np.transpose(ops.convert_to_tensor(a), perm)\n return np.conjugate(x) if conjugate else x\n\n\ndef _unstack(value, num=None, axis=0, name='unstack'):\n del name\n value = np.array(value)\n return list(\n np.squeeze(x, axis=axis)\n for x in np.split(value, value.shape[axis] if num is None else num, axis))\n\n\ndef _zeros_like(input, dtype=None, name=None): # pylint: disable=redefined-builtin,unused-argument\n return np.zeros_like(input, dtype=utils.numpy_dtype(dtype))\n\n\n# --- Begin Public Functions --------------------------------------------------\n\n\nconcat = utils.copy_docstring(\n 'tf.concat',\n _concat)\n\n\nexpand_dims = utils.copy_docstring(\n 'tf.expand_dims',\n lambda input, axis, name=None: np.expand_dims(input, axis))\n\nfill = utils.copy_docstring(\n 'tf.fill',\n lambda dims, value, name=None: np.full(dims, ops.convert_to_tensor(value)))\n\ngather = utils.copy_docstring(\n 'tf.gather',\n _gather)\n\ngather_nd = utils.copy_docstring(\n 'tf.gather_nd',\n _gather_nd)\n\nreverse = utils.copy_docstring('tf.reverse', _reverse)\n\nlinspace = utils.copy_docstring(\n 'tf.linspace',\n _linspace)\n\nmeshgrid = utils.copy_docstring(\n 'tf.meshgrid',\n np.meshgrid)\n\nnorm = utils.copy_docstring(\n 'tf.norm',\n norm)\n\none_hot = utils.copy_docstring(\n 'tf.one_hot',\n _one_hot)\n\nones = utils.copy_docstring(\n 'tf.ones',\n lambda shape, dtype=np.float32, name=None: np.ones( # pylint: disable=g-long-lambda\n shape, utils.numpy_dtype(dtype)))\n\nones_like = utils.copy_docstring(\n 'tf.ones_like',\n _ones_like)\n\npad = utils.copy_docstring(\n 'tf.pad',\n _pad)\n\nrange = utils.copy_docstring( # pylint: disable=redefined-builtin\n 'tf.range',\n _range)\n\nrank = utils.copy_docstring(\n 'tf.rank',\n lambda input, name=None: np.int32(np.array(input).ndim)) # pylint: disable=redefined-builtin,g-long-lambda\n\nrepeat = utils.copy_docstring(\n 'tf.repeat',\n lambda input, repeats, axis=None, name=None: np.repeat( # pylint: disable=g-long-lambda\n input, repeats, axis=axis))\n\nreshape = utils.copy_docstring(\n 'tf.reshape',\n lambda tensor, shape, name=None: np.reshape( # pylint: disable=g-long-lambda\n ops.convert_to_tensor(tensor), shape))\n\nroll = utils.copy_docstring(\n 'tf.roll',\n lambda input, shift, axis: np.roll(input, shift, axis)) # pylint: disable=unnecessary-lambda\n\nsequence_mask = utils.copy_docstring(\n 'tf.sequence_mask',\n _sequence_mask)\n\nsearchsorted = utils.copy_docstring(\n 'tf.searchsorted',\n _searchsorted)\n\nshape = utils.copy_docstring(\n 'tf.shape',\n _shape)\n\nsize = utils.copy_docstring(\n 'tf.size',\n _size)\n\nslice = utils.copy_docstring( # pylint: disable=redefined-builtin\n 'tf.slice', _slice)\n\nsplit = utils.copy_docstring('tf.split', _split)\n\nsqueeze = utils.copy_docstring(\n 'tf.squeeze',\n lambda input, axis=None, name=None: np.squeeze(input, _astuple(axis)))\n\nstack = utils.copy_docstring(\n 'tf.stack', lambda values, axis=0, name='stack': np.moveaxis( # pylint: disable=g-long-lambda\n ops.convert_to_tensor(values), 0, axis))\n\ntile = utils.copy_docstring(\n 'tf.tile',\n lambda input, multiples, name=None: np.tile(np.array(input), multiples))\n\ntranspose = utils.copy_docstring(\n 'tf.transpose',\n _transpose)\n\nunstack = utils.copy_docstring(\n 'tf.unstack',\n _unstack)\n\nwhere = utils.copy_docstring(\n 'tf.where',\n lambda condition, x=None, y=None, name=None: np.where(condition, x, y))\n\nzeros = utils.copy_docstring(\n 'tf.zeros',\n lambda shape, dtype=np.float32, name=None: np.zeros( # pylint: disable=g-long-lambda\n shape, utils.numpy_dtype(dtype)))\n\nzeros_like = utils.copy_docstring(\n 'tf.zeros_like',\n _zeros_like)\n",
"# Copyright 2018 The TensorFlow Probability Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"The Gamma distribution class.\"\"\"\n\n# Dependency imports\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\nfrom tensorflow_probability.python import math as tfp_math\nfrom tensorflow_probability.python.bijectors import softplus as softplus_bijector\nfrom tensorflow_probability.python.distributions import distribution\nfrom tensorflow_probability.python.distributions import kullback_leibler\nfrom tensorflow_probability.python.internal import assert_util\nfrom tensorflow_probability.python.internal import batched_rejection_sampler as brs\nfrom tensorflow_probability.python.internal import custom_gradient as tfp_custom_gradient\nfrom tensorflow_probability.python.internal import distribution_util\nfrom tensorflow_probability.python.internal import dtype_util\nfrom tensorflow_probability.python.internal import implementation_selection\nfrom tensorflow_probability.python.internal import parameter_properties\nfrom tensorflow_probability.python.internal import prefer_static as ps\nfrom tensorflow_probability.python.internal import reparameterization\nfrom tensorflow_probability.python.internal import samplers\nfrom tensorflow_probability.python.internal import tensor_util\nfrom tensorflow_probability.python.internal import tensorshape_util\nfrom tensorflow_probability.python.util.deferred_tensor import DeferredTensor\n\n__all__ = [\n 'Gamma',\n 'kl_gamma_gamma',\n 'random_gamma',\n]\n\n\nclass Gamma(distribution.AutoCompositeTensorDistribution):\n \"\"\"Gamma distribution.\n\n The Gamma distribution is defined over positive real numbers using\n parameters `concentration` (aka \"alpha\") and `rate` (aka \"beta\").\n\n #### Mathematical Details\n\n The probability density function (pdf) is,\n\n ```none\n pdf(x; alpha, beta, x > 0) = x**(alpha - 1) exp(-x beta) / Z\n Z = Gamma(alpha) beta**(-alpha)\n ```\n\n where:\n\n * `concentration = alpha`, `alpha > 0`,\n * `rate = beta`, `beta > 0`,\n * `Z` is the normalizing constant, and,\n * `Gamma` is the [gamma function](\n https://en.wikipedia.org/wiki/Gamma_function).\n\n The cumulative density function (cdf) is,\n\n ```none\n cdf(x; alpha, beta, x > 0) = GammaInc(alpha, beta x) / Gamma(alpha)\n ```\n\n where `GammaInc` is the [lower incomplete Gamma function](\n https://en.wikipedia.org/wiki/Incomplete_gamma_function).\n\n The parameters can be intuited via their relationship to mean and stddev,\n\n ```none\n concentration = alpha = (mean / stddev)**2\n rate = beta = mean / stddev**2 = concentration / mean\n ```\n\n Distribution parameters are automatically broadcast in all functions; see\n examples for details.\n\n Warning: The samples of this distribution are always non-negative. However,\n the samples that are smaller than `np.finfo(dtype).tiny` are rounded\n to this value, so it appears more often than it should.\n This should only be noticeable when the `concentration` is very small, or the\n `rate` is very large. See note in `tf.random.gamma` docstring. To avoid this\n hazard, consider `tfp.distributions.ExpGamma`.\n\n Samples of this distribution are reparameterized (pathwise differentiable).\n The derivatives are computed using the approach described in the paper\n\n [Michael Figurnov, Shakir Mohamed, Andriy Mnih.\n Implicit Reparameterization Gradients, 2018](https://arxiv.org/abs/1805.08498)\n\n #### Examples\n\n ```python\n import tensorflow_probability as tfp\n tfd = tfp.distributions\n\n dist = tfd.Gamma(concentration=3.0, rate=2.0)\n dist2 = tfd.Gamma(concentration=[3.0, 4.0], rate=[2.0, 3.0])\n\n # Build a Gamma distribution equivalent to `dist`, parameterized by mean and\n # variance.\n dist_from_mean_var = tfd.Gamma.experimental_from_mean_variance(\n mean=1.5, variance=0.75)\n ```\n\n Compute the gradients of samples w.r.t. the parameters:\n\n ```python\n concentration = tf.constant(3.0)\n rate = tf.constant(2.0)\n dist = tfd.Gamma(concentration, rate)\n samples = dist.sample(5) # Shape [5]\n loss = tf.reduce_mean(tf.square(samples)) # Arbitrary loss function\n # Unbiased stochastic gradients of the loss function\n grads = tf.gradients(loss, [concentration, rate])\n ```\n\n \"\"\"\n\n def __init__(self,\n concentration,\n rate=None,\n log_rate=None,\n validate_args=False,\n allow_nan_stats=True,\n force_probs_to_zero_outside_support=False,\n name='Gamma'):\n \"\"\"Construct Gamma with `concentration` and `rate` parameters.\n\n The parameters `concentration` and `rate` must be shaped in a way that\n supports broadcasting (e.g. `concentration + rate` is a valid operation).\n\n Args:\n concentration: Floating point tensor, the concentration params of the\n distribution(s). Must contain only positive values.\n rate: Floating point tensor, the inverse scale params of the\n distribution(s). Must contain only positive values. Mutually exclusive\n with `log_rate`.\n log_rate: Floating point tensor, natural logarithm of the inverse scale\n params of the distribution(s). Mutually exclusive with `rate`.\n validate_args: Python `bool`, default `False`. When `True` distribution\n parameters are checked for validity despite possibly degrading runtime\n performance. When `False` invalid inputs may silently render incorrect\n outputs.\n allow_nan_stats: Python `bool`, default `True`. When `True`, statistics\n (e.g., mean, mode, variance) use the value \"`NaN`\" to indicate the\n result is undefined. When `False`, an exception is raised if one or\n more of the statistic's batch members are undefined.\n force_probs_to_zero_outside_support: If `True`, force `prob(x) == 0` and\n `log_prob(x) == -inf` for values of x outside the distribution support.\n name: Python `str` name prefixed to Ops created by this class.\n\n Raises:\n TypeError: if `concentration` and `rate` are different dtypes.\n \"\"\"\n parameters = dict(locals())\n self._force_probs_to_zero_outside_support = (\n force_probs_to_zero_outside_support)\n if (rate is None) == (log_rate is None):\n raise ValueError('Exactly one of `rate` or `log_rate` must be specified.')\n with tf.name_scope(name) as name:\n dtype = dtype_util.common_dtype(\n [concentration, rate, log_rate], dtype_hint=tf.float32)\n self._concentration = tensor_util.convert_nonref_to_tensor(\n concentration, dtype=dtype, name='concentration')\n self._rate = tensor_util.convert_nonref_to_tensor(\n rate, dtype=dtype, name='rate')\n self._log_rate = tensor_util.convert_nonref_to_tensor(\n log_rate, dtype=dtype, name='log_rate')\n\n super(Gamma, self).__init__(\n dtype=dtype,\n validate_args=validate_args,\n allow_nan_stats=allow_nan_stats,\n reparameterization_type=reparameterization.FULLY_REPARAMETERIZED,\n parameters=parameters,\n name=name)\n\n @classmethod\n def experimental_from_mean_variance(cls, mean, variance, **kwargs):\n \"\"\"Constructs a Gamma from its mean and variance.\n\n **Experimental: Naming, location of this API may change.**\n\n Args:\n mean: The mean of the constructed distribution. Must be greater than 0.\n variance: The variance of the distribution. Must be greater than 0.\n **kwargs: Other keyword arguments passed directly to `__init__`, e.g.\n `validate_args`.\n\n Returns:\n gamma: A distribution with the given parameterization.\n \"\"\"\n dtype = dtype_util.common_dtype([mean, variance], dtype_hint=tf.float32)\n mean = tensor_util.convert_nonref_to_tensor(mean, dtype=dtype)\n variance = tensor_util.convert_nonref_to_tensor(variance, dtype=dtype)\n\n rate = DeferredTensor(mean, lambda mean: mean / variance)\n return cls(\n concentration=DeferredTensor(mean, lambda mean: mean * rate),\n rate=rate,\n **kwargs)\n\n @classmethod\n def _parameter_properties(cls, dtype, num_classes=None):\n # pylint: disable=g-long-lambda\n return dict(\n concentration=parameter_properties.ParameterProperties(\n default_constraining_bijector_fn=(\n lambda: softplus_bijector.Softplus(low=dtype_util.eps(dtype)))),\n rate=parameter_properties.ParameterProperties(\n default_constraining_bijector_fn=(\n lambda: softplus_bijector.Softplus(low=dtype_util.eps(dtype))),\n is_preferred=False),\n log_rate=parameter_properties.ParameterProperties())\n # pylint: enable=g-long-lambda\n\n @property\n def concentration(self):\n \"\"\"Concentration parameter.\"\"\"\n return self._concentration\n\n @property\n def rate(self):\n \"\"\"Rate parameter.\"\"\"\n return self._rate\n\n @property\n def log_rate(self):\n \"\"\"Log-rate parameter.\"\"\"\n return self._log_rate\n\n @property\n def force_probs_to_zero_outside_support(self):\n return self._force_probs_to_zero_outside_support\n\n def _event_shape_tensor(self):\n return tf.constant([], dtype=tf.int32)\n\n def _event_shape(self):\n return tf.TensorShape([])\n\n def _rate_parameter(self):\n if self.rate is None:\n return tf.math.exp(self.log_rate)\n return tf.convert_to_tensor(self.rate)\n\n def _log_rate_parameter(self):\n if self.log_rate is None:\n return tf.math.log(self.rate)\n return tf.convert_to_tensor(self.log_rate)\n\n @distribution_util.AppendDocstring(\n \"\"\"Note: See `tf.random.gamma` docstring for sampling details and\n caveats.\"\"\")\n def _sample_n(self, n, seed=None):\n seed = samplers.sanitize_seed(seed, salt='gamma')\n\n return random_gamma(\n shape=ps.convert_to_shape_tensor([n]),\n concentration=tf.convert_to_tensor(self.concentration),\n rate=None if self.rate is None else tf.convert_to_tensor(self.rate),\n log_rate=(None if self.log_rate is None else\n tf.convert_to_tensor(self.log_rate)),\n seed=seed)\n\n def _log_prob(self, x, rate=None):\n concentration = tf.convert_to_tensor(self.concentration)\n if rate is not None:\n rate = tf.convert_to_tensor(rate)\n log_rate = tf.math.log(rate)\n elif self.rate is None:\n log_rate = tf.convert_to_tensor(self.log_rate)\n rate = tf.math.exp(log_rate)\n else:\n rate = tf.convert_to_tensor(self.rate)\n log_rate = tf.math.log(rate)\n log_unnormalized_prob = tf.math.xlogy(concentration - 1., x) - rate * x\n log_normalization = tf.math.lgamma(concentration) - concentration * log_rate\n lp = log_unnormalized_prob - log_normalization\n if self.force_probs_to_zero_outside_support:\n return tf.where(x >= 0, lp, -float('inf'))\n return lp\n\n def _cdf(self, x):\n # Note that igamma returns the regularized incomplete gamma function,\n # which is what we want for the CDF.\n cdf = tf.math.igamma(self.concentration, self._rate_parameter() * x)\n return distribution_util.extend_cdf_outside_support(x, cdf, low=0.)\n\n def _quantile(self, p):\n return tfp_math.igammainv(self.concentration, p) / self._rate_parameter()\n\n def _entropy(self):\n concentration = tf.convert_to_tensor(self.concentration)\n log_rate = self._log_rate_parameter()\n return (concentration - log_rate + tf.math.lgamma(concentration) +\n ((1. - concentration) * tf.math.digamma(concentration)))\n\n def _mean(self):\n return self.concentration / self._rate_parameter()\n\n def _variance(self):\n rate_sq = (tf.math.exp(self.log_rate * 2) if self.rate is None else\n tf.square(self.rate))\n return self.concentration / rate_sq\n\n def _stddev(self):\n return tf.sqrt(self.concentration) / self._rate_parameter()\n\n @distribution_util.AppendDocstring(\n \"\"\"The mode of a gamma distribution is `(shape - 1) / rate` when\n `shape > 1`, and `NaN` otherwise. If `self.allow_nan_stats` is `False`,\n an exception will be raised rather than returning `NaN`.\"\"\")\n def _mode(self):\n concentration = tf.convert_to_tensor(self.concentration)\n mode = (concentration - 1.) / self._rate_parameter()\n if self.allow_nan_stats:\n assertions = []\n else:\n assertions = [assert_util.assert_less(\n tf.ones([], self.dtype), concentration,\n message='Mode not defined when any concentration <= 1.')]\n with tf.control_dependencies(assertions):\n return tf.where(\n concentration > 1.,\n mode,\n dtype_util.as_numpy_dtype(self.dtype)(np.nan))\n\n def _default_event_space_bijector(self):\n return softplus_bijector.Softplus(validate_args=self.validate_args)\n\n @classmethod\n def _maximum_likelihood_parameters(cls, value):\n expected_x = tf.reduce_mean(value, axis=0)\n log_expected_x = tf.math.log(expected_x)\n expected_log_x = tf.reduce_mean(tf.math.log(value), axis=0)\n # The following implements the generalized Newton iteration\n # proposed as eqn (10) in Tom Minka's note \"Estimating a Gamma Distribution\"\n # (2002, https://tminka.github.io/papers/minka-gamma.pdf).\n inv_concentration = 2. * (log_expected_x - expected_log_x)\n for _ in range(5): # Typically sufficient for float64 convergence.\n concentration = 1. / inv_concentration\n inv_concentration += (\n expected_log_x - log_expected_x +\n tf.math.log(concentration) - tf.math.digamma(concentration)) / (\n concentration**2 * (\n inv_concentration - tf.math.polygamma(1., concentration)))\n concentration = 1. / inv_concentration\n return {'concentration': concentration, 'rate': concentration / expected_x}\n\n def _sample_control_dependencies(self, x):\n assertions = []\n if not self.validate_args:\n return assertions\n assertions.append(assert_util.assert_non_negative(\n x, message='Sample must be non-negative.'))\n return assertions\n\n def _parameter_control_dependencies(self, is_init):\n if not self.validate_args:\n return []\n assertions = []\n if is_init != tensor_util.is_ref(self.concentration):\n assertions.append(assert_util.assert_positive(\n self.concentration,\n message='Argument `concentration` must be positive.'))\n if self.rate is not None and is_init != tensor_util.is_ref(self.rate):\n assertions.append(assert_util.assert_positive(\n self.rate,\n message='Argument `rate` must be positive.'))\n return assertions\n\n\n@kullback_leibler.RegisterKL(Gamma, Gamma)\ndef kl_gamma_gamma(g0, g1, name=None):\n \"\"\"Calculate the batched KL divergence KL(g0 || g1) with g0 and g1 Gamma.\n\n Args:\n g0: Instance of a `Gamma` distribution object.\n g1: Instance of a `Gamma` distribution object.\n name: Python `str` name to use for created operations.\n Default value: `None` (i.e., `'kl_gamma_gamma'`).\n\n Returns:\n kl_gamma_gamma: `Tensor`. The batchwise KL(g0 || g1).\n \"\"\"\n with tf.name_scope(name or 'kl_gamma_gamma'):\n # Result from:\n # http://www.fil.ion.ucl.ac.uk/~wpenny/publications/densities.ps\n # For derivation see:\n # http://stats.stackexchange.com/questions/11646/kullback-leibler-divergence-between-two-gamma-distributions pylint: disable=line-too-long\n g0_concentration = tf.convert_to_tensor(g0.concentration)\n g0_log_rate = g0._log_rate_parameter() # pylint: disable=protected-access\n g1_concentration = tf.convert_to_tensor(g1.concentration)\n g1_log_rate = g1._log_rate_parameter() # pylint: disable=protected-access\n return (((g0_concentration - g1_concentration) *\n tf.math.digamma(g0_concentration)) +\n tf.math.lgamma(g1_concentration) -\n tf.math.lgamma(g0_concentration) +\n g1_concentration * g0_log_rate -\n g1_concentration * g1_log_rate +\n g0_concentration * tf.math.expm1(g1_log_rate - g0_log_rate))\n\n\ndef _shape_or_scalar(v0, v1):\n if v0 is not None:\n return ps.shape(v0)\n if v1 is not None:\n return ps.shape(v1)\n return ps.convert_to_shape_tensor([], dtype=tf.int32)\n\n\ndef _tensorshape_or_scalar(v0, v1):\n if v0 is not None:\n if not hasattr(v0, 'shape'):\n v0 = tf.convert_to_tensor(v0)\n return v0.shape\n if v1 is not None:\n if not hasattr(v1, 'shape'):\n v1 = tf.convert_to_tensor(v1)\n return v1.shape\n return tf.TensorShape([])\n\n\ndef _random_gamma_cpu(\n shape, concentration, rate=None, log_rate=None, seed=None, log_space=False):\n \"\"\"Sample using *fast* `tf.random.stateless_gamma`.\"\"\"\n bad_concentration = (concentration < 0.) | tf.math.is_nan(concentration)\n safe_concentration = tf.where(\n bad_concentration,\n dtype_util.as_numpy_dtype(concentration.dtype)(100.), concentration)\n\n if rate is None:\n if log_rate is None:\n rate = tf.ones([], concentration.dtype)\n log_rate = tf.zeros([], concentration.dtype)\n else:\n rate = tf.math.exp(log_rate)\n\n bad_rate = (rate <= 0.) | tf.math.is_nan(rate)\n\n if log_space:\n # The underlying gamma sampler uses a recurrence for conc < 1. When\n # a ~ gamma(conc + 1) and x ~ uniform(0, 1), we have\n # b = a * x ** (1/conc) ~ gamma(conc)\n # Given that we want log(b) anyway, it's more accurate to just ask the\n # sampler for a (by passing conc + 1 to it in the first place) and\n # do the correction in log-space below.\n orig_safe_concentration = safe_concentration\n safe_concentration = tf.where(\n orig_safe_concentration < 1,\n orig_safe_concentration + 1.,\n orig_safe_concentration)\n seed, conc_fix_seed = samplers.split_seed(seed)\n log_rate = tf.math.log(rate) if log_rate is None else log_rate\n rate = tf.ones_like(log_rate) # Do the division later in log-space.\n\n safe_rate = tf.where(\n bad_rate,\n dtype_util.as_numpy_dtype(concentration.dtype)(100.), rate)\n samples = tf.random.stateless_gamma(\n shape=shape, seed=seed, alpha=safe_concentration,\n beta=safe_rate, dtype=concentration.dtype)\n\n if log_space:\n # Apply the concentration < 1 recurrence here, in log-space.\n samples = tf.math.log(samples)\n conc_fix_unif = samplers.uniform( # in [0, 1)\n shape, dtype=samples.dtype, seed=conc_fix_seed)\n\n conc_lt_one_fix = tf.where(\n orig_safe_concentration < 1,\n # Why do we use log1p(-x)? x is in [0, 1) and log(0) = -inf, is bad.\n # x ~ U(0,1) => 1-x ~ U(0,1)\n # But at the boundary, 1-x in (0, 1]. Good.\n # So we can take log(unif(0,1)) safely as log(1-unif(0,1)).\n # log1p(-0) = 0, and log1p(-almost_one) = -not_quite_inf. Good.\n tf.math.log1p(-conc_fix_unif) / orig_safe_concentration,\n tf.zeros((), dtype=samples.dtype))\n samples += (conc_lt_one_fix - log_rate)\n\n # 0 rate is infinite scale, which implies a +inf sample.\n # `if log_space` clobbered the `rate` variable with 1 a score lines ago.\n return tf.where(\n (log_rate <= -np.inf if log_space else tf.equal(rate, 0.)),\n tf.constant(np.inf, dtype=concentration.dtype),\n tf.where(\n bad_rate | bad_concentration,\n dtype_util.as_numpy_dtype(concentration.dtype)(np.nan), samples))\n\n\ndef _random_gamma_noncpu(\n shape, concentration, rate=None, log_rate=None, seed=None, log_space=False):\n \"\"\"Sample using XLA-friendly python-based rejection sampler.\"\"\"\n return _random_gamma_rejection(\n shape, concentration, rate, log_rate, seed, log_space)\n\n\n# tf.function required to access Grappler's implementation_selector.\n@implementation_selection.never_runs_functions_eagerly\n# TODO(b/163029794): Shape relaxation breaks XLA.\[email protected](autograph=False, experimental_relax_shapes=False)\ndef _random_gamma_no_gradient(\n shape, concentration, rate, log_rate, seed, log_space):\n \"\"\"Sample a gamma, CPU specialized to stateless_gamma.\n\n Args:\n shape: Sample shape.\n concentration: Concentration of gamma distribution.\n rate: Rate parameter of gamma distribution.\n log_rate: Log-rate parameter of gamma distribution.\n seed: PRNG seed; see `tfp.random.sanitize_seed` for details.\n log_space: If `True`, draw log-of-gamma samples.\n\n Returns:\n samples: Samples from gamma distributions.\n \"\"\"\n seed = samplers.sanitize_seed(seed)\n\n sampler_impl = implementation_selection.implementation_selecting(\n fn_name='gamma',\n default_fn=_random_gamma_noncpu,\n cpu_fn=_random_gamma_cpu)\n return sampler_impl(\n shape=shape, concentration=concentration, rate=rate, log_rate=log_rate,\n seed=seed, log_space=log_space)\n\n\ndef _compute_partials(samples, concentration, rate, log_rate, log_space):\n \"\"\"Shared partials between forward and reverse mode.\"\"\"\n if log_space:\n # The function is log(gamma_sample(conc, rate, log_rate)).\n # So:\n # d log(gamma_sample(..)) / d conc\n # = (d gamma_sample(..) / d conc) / gamma_sample(..)\n # d log(gamma_sample(..)) / d rate\n # = d log(gamma_sample(.., rate=1) / rate) / d rate\n # = d (log(gamma_sample(.., rate=1)) - log(rate)) / d rate\n # = d (-log(rate)) / d rate\n # = - 1. / rate\n # d log(gamma_sample(..)) / d log_rate\n # = d (log(gamma_sample(.., rate=1)) - log_rate) / d log_rate\n # = d (- log_rate) / d log_rate\n # = -1.\n partial_rate = 0.\n partial_log_rate = 0.\n if log_rate is not None:\n exp_samples_rate = tf.math.exp(samples + log_rate)\n partial_log_rate = -1.\n elif rate is not None:\n exp_samples_rate = tf.math.exp(samples) * rate\n partial_rate = -1. / rate\n else:\n exp_samples_rate = tf.math.exp(samples)\n partial_concentration = tf.raw_ops.RandomGammaGrad(\n alpha=concentration, sample=exp_samples_rate) / exp_samples_rate\n\n else:\n partial_rate = 0.\n partial_log_rate = 0.\n if log_rate is not None:\n # d gamma_sample(exp(log_rate)) / d log_rate\n # = d gamma_sample(rate) / d rate * d exp(log_rate) / d log_rate\n # = d gamma_sample(rate) / d rate * exp(log_rate)\n # = d gamma_sample(rate) / d rate * rate\n # Note that d gamma_sample(rate) / d rate = -gamma_sample(rate) / rate\n # So d gamma_sample(exp(log_rate)) / d log_rate = -gamma_sample(rate)\n rate = tf.math.exp(log_rate)\n partial_log_rate = -samples\n elif rate is not None:\n partial_rate = -samples / rate\n else:\n rate = 1.\n partial_concentration = tf.raw_ops.RandomGammaGrad(\n alpha=concentration, sample=samples * rate) / rate\n\n return partial_concentration, partial_rate, partial_log_rate\n\n\ndef _random_gamma_fwd(shape, concentration, rate, log_rate, seed, log_space):\n \"\"\"Compute output, aux (collaborates with _random_gamma_bwd).\"\"\"\n samples, impl = _random_gamma_no_gradient(\n shape, concentration, rate, log_rate, seed, log_space)\n return ((samples, impl),\n (samples, concentration, rate, log_rate))\n\n\ndef _random_gamma_bwd(shape, log_space, aux, g):\n \"\"\"The gradient of the gamma samples.\"\"\"\n samples, concentration, rate, log_rate = aux\n dsamples, dimpl = g\n # Ignore any gradient contributions that come from the implementation enum.\n del dimpl\n partial_concentration, partial_rate, partial_log_rate = _compute_partials(\n samples, concentration, rate, log_rate, log_space)\n\n # These will need to be shifted by the extra dimensions added from\n # `sample_shape`.\n rate_shape = _shape_or_scalar(rate, log_rate)\n reduce_dims = tf.range(tf.size(shape) - tf.maximum(tf.rank(concentration),\n tf.size(rate_shape)))\n grad_concentration = tf.math.reduce_sum(\n dsamples * partial_concentration, axis=reduce_dims)\n grad_log_rate = None\n grad_rate = None\n if rate is not None:\n grad_rate = tf.math.reduce_sum(dsamples * partial_rate, axis=reduce_dims)\n elif log_rate is not None:\n grad_log_rate = tf.math.reduce_sum(\n dsamples * partial_log_rate, axis=reduce_dims)\n\n rate_tensorshape = _tensorshape_or_scalar(rate, log_rate)\n if (tensorshape_util.is_fully_defined(concentration.shape) and\n tensorshape_util.is_fully_defined(rate_tensorshape) and\n concentration.shape == rate_tensorshape):\n return grad_concentration, grad_rate, grad_log_rate, None # seed=None\n\n ax_conc, ax_rate = tf.raw_ops.BroadcastGradientArgs(\n s0=tf.shape(concentration), s1=rate_shape)\n grad_concentration = tf.reshape(\n tf.math.reduce_sum(grad_concentration, axis=ax_conc),\n tf.shape(concentration))\n if grad_rate is not None:\n grad_rate = tf.reshape(\n tf.math.reduce_sum(grad_rate, axis=ax_rate), rate_shape)\n if grad_log_rate is not None:\n grad_log_rate = tf.reshape(\n tf.math.reduce_sum(grad_log_rate, axis=ax_rate), rate_shape)\n\n return grad_concentration, grad_rate, grad_log_rate, None # seed=None\n\n\ndef _random_gamma_jvp(shape, log_space, primals, tangents):\n \"\"\"Computes JVP for gamma sample (supports JAX custom derivative).\"\"\"\n concentration, rate, log_rate, seed = primals\n dconcentration, drate, dlog_rate, dseed = tangents\n del dseed\n # TODO(https://github.com/google/jax/issues/3768): eliminate broadcast_to?\n dconcentration = tf.broadcast_to(dconcentration, shape)\n drate = 0 if drate is None else tf.broadcast_to(drate, shape)\n dlog_rate = 0 if dlog_rate is None else tf.broadcast_to(dlog_rate, shape)\n\n samples, impl = _random_gamma_no_gradient(\n shape, concentration, rate, log_rate, seed, log_space)\n\n partial_concentration, partial_rate, partial_log_rate = _compute_partials(\n samples, concentration, rate, log_rate, log_space)\n\n dsamples = (partial_concentration * dconcentration +\n partial_rate * drate +\n partial_log_rate * dlog_rate)\n return (\n (samples, impl),\n (dsamples, tf.zeros_like(impl)))\n\n\n@tfp_custom_gradient.custom_gradient(\n vjp_fwd=_random_gamma_fwd,\n vjp_bwd=_random_gamma_bwd,\n jvp_fn=_random_gamma_jvp,\n nondiff_argnums=(0, 5))\ndef _random_gamma_gradient(\n shape, concentration, rate, log_rate, seed, log_space):\n return _random_gamma_no_gradient(\n shape, concentration, rate, log_rate, seed, log_space)\n\n\ndef _fix_zero_samples(s):\n # We use `tf.where` instead of `tf.maximum` because we need to allow for\n # `samples` to be `nan`, but `tf.maximum(nan, x) == x`.\n return tf.where(\n tf.equal(s, 0), np.finfo(dtype_util.as_numpy_dtype(s.dtype)).tiny, s)\n\n\n# TF custom_gradient doesn't support kwargs, so we wrap _random_gamma_gradient.\ndef random_gamma_with_runtime(\n shape, concentration, rate=None, log_rate=None, seed=None, log_space=False):\n \"\"\"Returns both a sample and the id of the implementation-selected runtime.\"\"\"\n # This method exists chiefly for testing purposes.\n dtype = dtype_util.common_dtype([concentration, rate, log_rate], tf.float32)\n concentration = tf.convert_to_tensor(concentration, dtype=dtype)\n shape = ps.convert_to_shape_tensor(shape, dtype_hint=tf.int32, name='shape')\n\n if rate is not None and log_rate is not None:\n raise ValueError('At most one of `rate` and `log_rate` may be specified.')\n if rate is not None:\n rate = tf.convert_to_tensor(rate, dtype=dtype)\n if log_rate is not None:\n log_rate = tf.convert_to_tensor(log_rate, dtype=dtype)\n total_shape = ps.concat(\n [shape, ps.broadcast_shape(ps.shape(concentration),\n _shape_or_scalar(rate, log_rate))],\n axis=0)\n seed = samplers.sanitize_seed(seed, salt='random_gamma')\n return _random_gamma_gradient(\n total_shape, concentration, rate, log_rate, seed, log_space)\n\n\ndef random_gamma(\n shape, concentration, rate=None, log_rate=None, seed=None, log_space=False):\n return random_gamma_with_runtime(\n shape, concentration, rate, log_rate, seed, log_space)[0]\n\n\ndef _random_gamma_rejection(\n shape, concentration, rate=None, log_rate=None, seed=None, log_space=False,\n internal_dtype=None):\n \"\"\"Samples from the gamma distribution.\n\n The sampling algorithm is rejection sampling [1], and pathwise gradients with\n respect to concentration are computed via implicit differentiation [2].\n\n Args:\n shape: The output sample shape. Trailing dims must match broadcast of\n `concentration` with `rate` or `log_rate`.\n concentration: Floating point tensor, the concentration params of the\n distribution(s). Must contain only positive values. Must broadcast with\n `rate` or `log_rate`, if given.\n rate: Floating point tensor, the inverse scale params of the\n distribution(s). Must contain only positive values. Must broadcast with\n `concentration`. If `None`, handled as if 1 (but possibly more\n efficiently). Mutually exclusive with `log_rate`.\n log_rate: Floating point tensor, log of the inverse scale params of the\n distribution(s). Must broadcast with `concentration`. If `None`, handled\n as if 0 (but possibly more efficiently). Mutually exclusive with `rate`.\n seed: PRNG seed; see `tfp.random.sanitize_seed` for details.\n log_space: Optionally sample log(gamma) variates.\n internal_dtype: dtype to use for internal computations. If unspecified, we\n use the same dtype as the output (i.e. the dtype of `concentration`,\n `rate`, or `log_rate`) when `log_space==True`, and `tf.float64` otherwise.\n\n Returns:\n Differentiable samples from the gamma distribution.\n\n #### References\n\n [1] George Marsaglia and Wai Wan Tsang. A simple method for generating Gamma\n variables. ACM Transactions on Mathematical Software, 2000.\n\n [2] Michael Figurnov, Shakir Mohamed, and Andriy Mnih. Implicit\n Reparameterization Gradients. Neural Information Processing Systems, 2018.\n \"\"\"\n generate_and_test_samples_seed, concentration_fix_seed = samplers.split_seed(\n seed, salt='random_gamma')\n output_dtype = dtype_util.common_dtype([concentration, rate, log_rate],\n dtype_hint=tf.float32)\n if internal_dtype is None:\n internal_dtype = output_dtype if log_space else tf.float64\n\n def rejection_sample(concentration):\n \"\"\"Gamma rejection sampler.\"\"\"\n # Note, concentration here already has a shape that is broadcast with rate.\n cast_concentration = tf.cast(concentration, internal_dtype)\n\n good_params_mask = (concentration >= 0.)\n # When replacing NaN values, use 100. for concentration, since that leads to\n # a high-likelihood of the rejection sampler accepting on the first pass.\n safe_concentration = tf.where(good_params_mask, cast_concentration, 100.)\n\n modified_safe_concentration = tf.where(\n safe_concentration < 1., safe_concentration + 1., safe_concentration)\n\n one_third = tf.constant(1. / 3, dtype=internal_dtype)\n d = modified_safe_concentration - one_third\n c = one_third * tf.math.rsqrt(d)\n\n def generate_and_test_samples(seed):\n \"\"\"Generate and test samples.\"\"\"\n v_seed, u_seed = samplers.split_seed(seed)\n\n x = samplers.normal(shape, dtype=internal_dtype, seed=v_seed)\n # This implicitly broadcasts concentration up to sample shape.\n v = 1 + c * x\n # In [1], there is an 'inner' rejection sampling loop which checks that\n # v > 0 and generates a new normal sample if it's not, saving the rest of\n # the computations below. We found that merging the check for v > 0 with\n # the `good_sample_mask` not only simplifies the code, but leads to a\n # ~2x speedup for small concentrations on GPU, at the cost of deviating\n # slightly from the implementation given in Ref. [1].\n accept_v = v > 0.\n logv = tf.math.log1p(c * x)\n x2 = x * x\n v3 = v * v * v\n logv3 = logv * 3\n\n u = samplers.uniform(\n shape, dtype=internal_dtype, seed=u_seed)\n\n # In [1], the suggestion is to first check u < 1 - 0.331 * x2 * x2, and to\n # run the check below only if it fails, in order to avoid the relatively\n # expensive logarithm calls. Our algorithm operates in batch mode: we will\n # have to compute or not compute the logarithms for the entire batch, and\n # as the batch gets larger, the odds we compute it grow. Therefore we\n # don't bother with the \"cheap\" check.\n good_sample_mask = tf.logical_and(\n tf.math.log(u) < (x2 / 2. + d * (1 - v3 + logv3)), accept_v)\n\n return logv3 if log_space else v3, good_sample_mask\n\n samples = brs.batched_las_vegas_algorithm(\n generate_and_test_samples, seed=generate_and_test_samples_seed)[0]\n\n concentration_fix_unif = samplers.uniform( # in [0, 1)\n shape, dtype=internal_dtype, seed=concentration_fix_seed)\n\n if log_space:\n concentration_lt_one_fix = tf.where(\n safe_concentration < 1.,\n # Why do we use log1p(-x)? x is in [0, 1) and log(0) = -inf, is bad.\n # x ~ U(0,1) => 1-x ~ U(0,1)\n # But at the boundary, 1-x in (0, 1]. Good.\n # So we can take log(unif(0,1)) safely as log(1-unif(0,1)).\n # log1p(-0) = 0, and log1p(-almost_one) = -not_quite_inf. Good.\n tf.math.log1p(-concentration_fix_unif) / safe_concentration,\n tf.zeros((), dtype=internal_dtype))\n samples = samples + tf.math.log(d) + concentration_lt_one_fix\n else:\n concentration_lt_one_fix = tf.where(\n safe_concentration < 1.,\n tf.math.pow(concentration_fix_unif,\n tf.math.reciprocal(safe_concentration)),\n tf.ones((), dtype=internal_dtype))\n samples = samples * d * concentration_lt_one_fix\n\n samples = tf.where(good_params_mask, samples, np.nan)\n output_type_samples = tf.cast(samples, output_dtype)\n\n return output_type_samples\n\n broadcast_conc_shape = ps.broadcast_shape(ps.shape(concentration),\n _shape_or_scalar(rate, log_rate))\n broadcast_concentration = tf.broadcast_to(concentration, broadcast_conc_shape)\n concentration_samples = rejection_sample(broadcast_concentration)\n\n if rate is not None and log_rate is not None:\n raise ValueError('`rate` and `log_rate` are mutually exclusive.')\n\n if rate is None and log_rate is None:\n if not log_space:\n concentration_samples = _fix_zero_samples(concentration_samples)\n return concentration_samples\n\n if log_space:\n if log_rate is None:\n log_rate = tf.math.log(tf.where(rate >= 0., rate, np.nan))\n return concentration_samples - log_rate\n else:\n if rate is None:\n rate = tf.math.exp(log_rate)\n corrected_rate = tf.where(rate >= 0., rate, np.nan)\n # 0 rate is infinite scale, which implies a +inf sample.\n ret = tf.where(\n tf.equal(corrected_rate, 0), tf.constant(np.inf, dtype=output_dtype),\n _fix_zero_samples(concentration_samples / corrected_rate))\n return ret\n"
] |
[
[
"numpy.split",
"numpy.expand_dims",
"numpy.take",
"numpy.asarray",
"numpy.issubdtype",
"numpy.squeeze",
"numpy.concatenate",
"numpy.max",
"numpy.moveaxis",
"numpy.where",
"numpy.roll",
"numpy.conjugate",
"numpy.reshape",
"numpy.arange",
"numpy.repeat",
"numpy.array",
"numpy.flip",
"numpy.sum",
"numpy.isscalar",
"numpy.ndindex"
],
[
"tensorflow.compat.v2.math.is_nan",
"tensorflow.compat.v2.rank",
"tensorflow.compat.v2.random.stateless_gamma",
"tensorflow.compat.v2.sqrt",
"tensorflow.compat.v2.shape",
"tensorflow.compat.v2.convert_to_tensor",
"tensorflow.compat.v2.ones",
"tensorflow.compat.v2.TensorShape",
"tensorflow.compat.v2.math.exp",
"tensorflow.compat.v2.math.xlogy",
"tensorflow.compat.v2.name_scope",
"tensorflow.compat.v2.math.lgamma",
"tensorflow.compat.v2.where",
"tensorflow.compat.v2.math.reduce_sum",
"tensorflow.compat.v2.zeros",
"tensorflow.compat.v2.math.log",
"tensorflow.compat.v2.math.rsqrt",
"tensorflow.compat.v2.function",
"tensorflow.compat.v2.equal",
"tensorflow.compat.v2.control_dependencies",
"tensorflow.compat.v2.raw_ops.RandomGammaGrad",
"tensorflow.compat.v2.size",
"tensorflow.compat.v2.square",
"tensorflow.compat.v2.reduce_mean",
"tensorflow.compat.v2.math.digamma",
"tensorflow.compat.v2.math.polygamma",
"tensorflow.compat.v2.constant",
"tensorflow.compat.v2.math.reciprocal",
"tensorflow.compat.v2.zeros_like",
"tensorflow.compat.v2.ones_like",
"tensorflow.compat.v2.broadcast_to",
"tensorflow.compat.v2.cast",
"tensorflow.compat.v2.math.log1p",
"tensorflow.compat.v2.math.expm1"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
lisurui6/acdrnet
|
[
"bf7e5a93149dd1e71a42669f2463212e7bb82bd3"
] |
[
"data/transforms.py"
] |
[
"from __future__ import division\nimport torch\nimport math\nimport sys\nimport random\nfrom PIL import Image\n\ntry:\n import accimage\nexcept ImportError:\n accimage = None\nimport numpy as np\nimport numbers\nimport collections\nimport warnings\n\nfrom torchvision.transforms import functional as F\n\nif sys.version_info < (3, 3):\n Sequence = collections.Sequence\n Iterable = collections.Iterable\nelse:\n Sequence = collections.abc.Sequence\n Iterable = collections.abc.Iterable\n\n__all__ = [\"Compose\", \"ToTensor\", \"ToPILImage\", \"Normalize\", \"Resize\", \"CenterCrop\", \"Pad\",\n \"Lambda\", \"RandomApply\", \"RandomChoice\", \"RandomOrder\", \"RandomCrop\", \"RandomHorizontalFlip\",\n \"RandomVerticalFlip\", \"RandomResizedCrop\", \"FiveCrop\", \"TenCrop\",\n \"ColorJitter\", \"RandomRotation\", \"RandomAffine\",\n \"RandomPerspective\", \"RandomAffineFromSet\"]\n\n_pil_interpolation_to_str = {\n Image.NEAREST: 'PIL.Image.NEAREST',\n Image.BILINEAR: 'PIL.Image.BILINEAR',\n Image.BICUBIC: 'PIL.Image.BICUBIC',\n Image.LANCZOS: 'PIL.Image.LANCZOS',\n Image.HAMMING: 'PIL.Image.HAMMING',\n Image.BOX: 'PIL.Image.BOX',\n}\n\n\nclass Compose(object):\n def __init__(self, transforms):\n self.transforms = transforms\n\n def __call__(self, img, mask):\n for t in self.transforms:\n img, mask = t(img, mask)\n return img, mask\n\n\nclass ToTensor(object):\n def __call__(self, img, mask):\n # return F.to_tensor(img), F.to_tensor(mask)\n img = torch.from_numpy(np.array(img)).permute(2, 0, 1).float()\n mask = torch.from_numpy(np.array(mask)).float()\n return img, mask\n\n\nclass ToPILImage(object):\n def __init__(self, mode=None):\n self.mode = mode\n\n def __call__(self, img, mask):\n return F.to_pil_image(img, self.mode), F.to_pil_image(mask, self.mode)\n\n\nclass Normalize(object):\n def __init__(self, mean, std, inplace=False):\n self.mean = mean\n self.std = std\n self.inplace = inplace\n\n def __call__(self, img, mask):\n return F.normalize(img, self.mean, self.std, self.inplace), mask\n\n\nclass NormalizeInstance(object):\n def __call__(self, img, mask):\n img = img / 255\n mean = img.reshape(3, -1).mean(-1).unsqueeze(-1).unsqueeze(-1)\n std = img.reshape(3, -1).std(-1).unsqueeze(-1).unsqueeze(-1)\n norm_img = (img - mean) / (std + 1e-8)\n return norm_img, mask\n\n\nclass Resize(object):\n def __init__(self, size, interpolation=Image.BILINEAR, do_mask=True):\n assert isinstance(size, int) or (isinstance(size, Iterable) and len(size) == 2)\n self.size = size\n self.interpolation = interpolation\n self.do_mask = do_mask\n\n def __call__(self, img, mask):\n if self.do_mask:\n return F.resize(img, self.size, self.interpolation), F.resize(mask, self.size, Image.NEAREST)\n else:\n return F.resize(img, self.size, self.interpolation), mask\n\n\nclass CenterCrop(object):\n def __init__(self, size):\n if isinstance(size, numbers.Number):\n self.size = (int(size), int(size))\n else:\n self.size = size\n\n def __call__(self, img, mask):\n return F.center_crop(img, self.size), F.center_crop(mask, self.size)\n\n\nclass Pad(object):\n def __init__(self, padding, fill=0, padding_mode='constant'):\n assert isinstance(padding, (numbers.Number, tuple))\n assert isinstance(fill, (numbers.Number, str, tuple))\n assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric']\n if isinstance(padding, Sequence) and len(padding) not in [2, 4]:\n raise ValueError(\"Padding must be an int or a 2, or 4 element tuple, not a \" +\n \"{} element tuple\".format(len(padding)))\n\n self.padding = padding\n self.fill = fill\n self.padding_mode = padding_mode\n\n def __call__(self, img, mask):\n return F.pad(img, self.padding, self.fill, self.padding_mode), \\\n F.pad(mask, self.padding, self.fill, self.padding_mode)\n\n\nclass Lambda(object):\n def __init__(self, lambd):\n assert callable(lambd), repr(type(lambd).__name__) + \" object is not callable\"\n self.lambd = lambd\n\n def __call__(self, img, mask):\n return self.lambd(img), self.lambd(mask)\n\n\nclass Lambda_image(object):\n def __init__(self, lambd):\n assert callable(lambd), repr(type(lambd).__name__) + \" object is not callable\"\n self.lambd = lambd\n\n def __call__(self, img, mask):\n return self.lambd(img), mask\n\n\nclass RandomTransforms(object):\n def __init__(self, transforms):\n assert isinstance(transforms, (list, tuple))\n self.transforms = transforms\n\n def __call__(self, *args, **kwargs):\n raise NotImplementedError()\n\n\nclass RandomApply(RandomTransforms):\n def __init__(self, transforms, p=0.5):\n super(RandomApply, self).__init__(transforms)\n self.p = p\n\n def __call__(self, img, mask):\n if self.p < random.random():\n return img, mask\n for t in self.transforms:\n img, mask = t(img, mask)\n return img, mask\n\n\nclass RandomOrder(RandomTransforms):\n def __call__(self, img, mask):\n order = list(range(len(self.transforms)))\n random.shuffle(order)\n for i in order:\n img, mask = self.transforms[i](img, mask)\n return img, mask\n\n\nclass RandomChoice(RandomTransforms):\n def __call__(self, img, mask):\n t = random.choice(self.transforms)\n return t(img, mask)\n\n\nclass RandomCrop(object):\n def __init__(self, size, padding=None, pad_if_needed=False, fill=0, padding_mode='constant'):\n if isinstance(size, numbers.Number):\n self.size = (int(size), int(size))\n else:\n self.size = size\n self.padding = padding\n self.pad_if_needed = pad_if_needed\n self.fill = fill\n self.padding_mode = padding_mode\n\n @staticmethod\n def get_params(img, output_size):\n w, h = img.size\n th, tw = output_size\n if w == tw and h == th:\n return 0, 0, h, w\n\n i = random.randint(0, h - th)\n j = random.randint(0, w - tw)\n return i, j, th, tw\n\n def __call__(self, img, mask):\n if self.padding is not None:\n img = F.pad(img, self.padding, self.fill, self.padding_mode)\n\n # pad the width if needed\n if self.pad_if_needed and img.size[0] < self.size[1]:\n img = F.pad(img, (self.size[1] - img.size[0], 0), self.fill, self.padding_mode)\n # pad the height if needed\n if self.pad_if_needed and img.size[1] < self.size[0]:\n img = F.pad(img, (0, self.size[0] - img.size[1]), self.fill, self.padding_mode)\n\n i, j, h, w = self.get_params(img, self.size)\n\n return F.crop(img, i, j, h, w), F.crop(mask, i, j, h, w)\n\n\nclass RandomHorizontalFlip(object):\n def __init__(self, p=0.5):\n self.p = p\n\n def __call__(self, img, mask):\n if random.random() < self.p:\n return F.hflip(img), F.hflip(mask)\n return img, mask\n\n\nclass RandomVerticalFlip(object):\n def __init__(self, p=0.5):\n self.p = p\n\n def __call__(self, img, mask):\n if random.random() < self.p:\n return F.vflip(img), F.vflip(mask)\n return img\n\n\nclass RandomPerspective(object):\n def __init__(self, distortion_scale=0.5, p=0.5, interpolation=Image.BICUBIC):\n self.p = p\n self.interpolation = interpolation\n self.distortion_scale = distortion_scale\n\n def __call__(self, img, mask):\n if not F._is_pil_image(img):\n raise TypeError('img should be PIL Image. Got {}'.format(type(img)))\n\n if random.random() < self.p:\n width, height = img.size\n startpoints, endpoints = self.get_params(width, height, self.distortion_scale)\n return F.perspective(img, startpoints, endpoints, self.interpolation), \\\n F.perspective(mask, startpoints, endpoints, Image.NEAREST)\n return img, mask\n\n @staticmethod\n def get_params(width, height, distortion_scale):\n half_height = int(height / 2)\n half_width = int(width / 2)\n topleft = (random.randint(0, int(distortion_scale * half_width)),\n random.randint(0, int(distortion_scale * half_height)))\n topright = (random.randint(width - int(distortion_scale * half_width) - 1, width - 1),\n random.randint(0, int(distortion_scale * half_height)))\n botright = (random.randint(width - int(distortion_scale * half_width) - 1, width - 1),\n random.randint(height - int(distortion_scale * half_height) - 1, height - 1))\n botleft = (random.randint(0, int(distortion_scale * half_width)),\n random.randint(height - int(distortion_scale * half_height) - 1, height - 1))\n startpoints = [(0, 0), (width - 1, 0), (width - 1, height - 1), (0, height - 1)]\n endpoints = [topleft, topright, botright, botleft]\n return startpoints, endpoints\n\n\nclass RandomResizedCrop(object):\n def __init__(self, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), interpolation=Image.BILINEAR):\n if isinstance(size, tuple):\n self.size = size\n else:\n self.size = (size, size)\n if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):\n warnings.warn(\"range should be of kind (min, max)\")\n\n self.interpolation = interpolation\n self.scale = scale\n self.ratio = ratio\n\n @staticmethod\n def get_params(img, scale, ratio):\n area = img.size[0] * img.size[1]\n\n for attempt in range(10):\n target_area = random.uniform(*scale) * area\n log_ratio = (math.log(ratio[0]), math.log(ratio[1]))\n aspect_ratio = math.exp(random.uniform(*log_ratio))\n\n w = int(round(math.sqrt(target_area * aspect_ratio)))\n h = int(round(math.sqrt(target_area / aspect_ratio)))\n\n if w <= img.size[0] and h <= img.size[1]:\n i = random.randint(0, img.size[1] - h)\n j = random.randint(0, img.size[0] - w)\n return i, j, h, w\n\n # Fallback to central crop\n in_ratio = img.size[0] / img.size[1]\n if (in_ratio < min(ratio)):\n w = img.size[0]\n h = w / min(ratio)\n elif (in_ratio > max(ratio)):\n h = img.size[1]\n w = h * max(ratio)\n else: # whole image\n w = img.size[0]\n h = img.size[1]\n i = (img.size[1] - h) // 2\n j = (img.size[0] - w) // 2\n return i, j, h, w\n\n def __call__(self, img, mask):\n i, j, h, w = self.get_params(img, self.scale, self.ratio)\n return F.resized_crop(img, i, j, h, w, self.size, self.interpolation), \\\n F.resized_crop(mask, i, j, h, w, self.size, Image.NEAREST)\n\n\nclass FiveCrop(object):\n def __init__(self, size):\n self.size = size\n if isinstance(size, numbers.Number):\n self.size = (int(size), int(size))\n else:\n assert len(size) == 2, \"Please provide only two dimensions (h, w) for size.\"\n self.size = size\n\n def __call__(self, img, mask):\n return F.five_crop(img, self.size), F.five_crop(mask, self.size)\n\n\nclass TenCrop(object):\n def __init__(self, size, vertical_flip=False):\n self.size = size\n if isinstance(size, numbers.Number):\n self.size = (int(size), int(size))\n else:\n assert len(size) == 2, \"Please provide only two dimensions (h, w) for size.\"\n self.size = size\n self.vertical_flip = vertical_flip\n\n def __call__(self, img, mask):\n return F.ten_crop(img, self.size, self.vertical_flip), F.ten_crop(mask, self.size, self.vertical_flip)\n\n\nclass ColorJitter(object):\n def __init__(self, brightness=0, contrast=0, saturation=0, hue=0):\n self.brightness = self._check_input(brightness, 'brightness')\n self.contrast = self._check_input(contrast, 'contrast')\n self.saturation = self._check_input(saturation, 'saturation')\n self.hue = self._check_input(hue, 'hue', center=0, bound=(-0.5, 0.5),\n clip_first_on_zero=False)\n\n def _check_input(self, value, name, center=1, bound=(0, float('inf')), clip_first_on_zero=True):\n if isinstance(value, numbers.Number):\n if value < 0:\n raise ValueError(\"If {} is a single number, it must be non negative.\".format(name))\n value = [center - value, center + value]\n if clip_first_on_zero:\n value[0] = max(value[0], 0)\n elif isinstance(value, (tuple, list)) and len(value) == 2:\n if not bound[0] <= value[0] <= value[1] <= bound[1]:\n raise ValueError(\"{} values should be between {}\".format(name, bound))\n else:\n raise TypeError(\"{} should be a single number or a list/tuple with lenght 2.\".format(name))\n\n # if value is 0 or (1., 1.) for brightness/contrast/saturation\n # or (0., 0.) for hue, do nothing\n if value[0] == value[1] == center:\n value = None\n return value\n\n @staticmethod\n def get_params(brightness, contrast, saturation, hue):\n transforms = []\n\n if brightness is not None:\n brightness_factor = random.uniform(brightness[0], brightness[1])\n transforms.append(Lambda_image(lambda img: F.adjust_brightness(img, brightness_factor)))\n\n if contrast is not None:\n contrast_factor = random.uniform(contrast[0], contrast[1])\n transforms.append(Lambda_image(lambda img: F.adjust_contrast(img, contrast_factor)))\n\n if saturation is not None:\n saturation_factor = random.uniform(saturation[0], saturation[1])\n transforms.append(Lambda_image(lambda img: F.adjust_saturation(img, saturation_factor)))\n\n if hue is not None:\n hue_factor = random.uniform(hue[0], hue[1])\n transforms.append(Lambda_image(lambda img: F.adjust_hue(img, hue_factor)))\n\n random.shuffle(transforms)\n transform = Compose(transforms)\n\n return transform\n\n def __call__(self, img, mask):\n transform = self.get_params(self.brightness, self.contrast,\n self.saturation, self.hue)\n return transform(img, mask)\n\n\nclass RandomRotation(object):\n def __init__(self, degrees, resample=False, expand=False, center=None):\n if isinstance(degrees, numbers.Number):\n if degrees < 0:\n raise ValueError(\"If degrees is a single number, it must be positive.\")\n self.degrees = (-degrees, degrees)\n else:\n if len(degrees) != 2:\n raise ValueError(\"If degrees is a sequence, it must be of len 2.\")\n self.degrees = degrees\n\n self.resample = resample\n self.expand = expand\n self.center = center\n\n @staticmethod\n def get_params(degrees):\n angle = random.uniform(degrees[0], degrees[1])\n\n return angle\n\n def __call__(self, img, mask):\n angle = self.get_params(self.degrees)\n\n return F.rotate(img, angle, Image.BILINEAR, self.expand, self.center), \\\n F.rotate(mask, angle, Image.NEAREST, self.expand, self.center)\n\n\nclass RandomRotationFromSet(object):\n def __init__(self, degrees=[0, 15, 60, 90, 135, 180, 225, 270], resample=False, expand=False, center=None):\n self.degrees = degrees\n self.resample = resample\n self.expand = expand\n self.center = center\n\n def __call__(self, img, mask):\n angle = random.choice(self.degrees)\n\n return F.rotate(img, angle, Image.BILINEAR, self.expand, self.center), \\\n F.rotate(mask, angle, Image.NEAREST, self.expand, self.center)\n\n\nclass RandomAffine(object):\n def __init__(self, degrees, translate=None, scale=None, shear=None, resample=False, fillcolor=0):\n if isinstance(degrees, numbers.Number):\n if degrees < 0:\n raise ValueError(\"If degrees is a single number, it must be positive.\")\n self.degrees = (-degrees, degrees)\n else:\n assert isinstance(degrees, (tuple, list)) and len(degrees) == 2, \\\n \"degrees should be a list or tuple and it must be of length 2.\"\n self.degrees = degrees\n\n if translate is not None:\n assert isinstance(translate, (tuple, list)) and len(translate) == 2, \\\n \"translate should be a list or tuple and it must be of length 2.\"\n for t in translate:\n if not (0.0 <= t <= 1.0):\n raise ValueError(\"translation values should be between 0 and 1\")\n self.translate = translate\n\n if scale is not None:\n assert isinstance(scale, (tuple, list)) and len(scale) == 2, \\\n \"scale should be a list or tuple and it must be of length 2.\"\n for s in scale:\n if s <= 0:\n raise ValueError(\"scale values should be positive\")\n self.scale = scale\n\n if shear is not None:\n if isinstance(shear, numbers.Number):\n if shear < 0:\n raise ValueError(\"If shear is a single number, it must be positive.\")\n self.shear = (-shear, shear)\n else:\n assert isinstance(shear, (tuple, list)) and len(shear) == 2, \\\n \"shear should be a list or tuple and it must be of length 2.\"\n self.shear = shear\n else:\n self.shear = shear\n\n self.resample = resample\n self.fillcolor = fillcolor\n\n @staticmethod\n def get_params(degrees, translate, scale_ranges, shears, img_size):\n angle = random.uniform(degrees[0], degrees[1])\n if translate is not None:\n max_dx = translate[0] * img_size[0]\n max_dy = translate[1] * img_size[1]\n translations = (np.round(random.uniform(-max_dx, max_dx)),\n np.round(random.uniform(-max_dy, max_dy)))\n else:\n translations = (0, 0)\n\n if scale_ranges is not None:\n scale = random.uniform(scale_ranges[0], scale_ranges[1])\n else:\n scale = 1.0\n\n if shears is not None:\n shear = random.uniform(shears[0], shears[1])\n else:\n shear = 0.0\n\n return angle, translations, scale, shear\n\n def __call__(self, img, mask):\n ret = self.get_params(self.degrees, self.translate, self.scale, self.shear, img.size)\n return F.affine(img, *ret, resample=Image.BILINEAR, fillcolor=self.fillcolor), \\\n F.affine(mask, *ret, resample=Image.NEAREST, fillcolor=self.fillcolor)\n\n\nclass RandomAffineFromSet(object):\n def __init__(self, degrees, translate=None, scale=None, shear=None, resample=False, fillcolor=0):\n assert isinstance(degrees, (tuple, list)), \\\n \"degrees should be a list or tuple.\"\n self.degrees = degrees\n\n if translate is not None:\n assert isinstance(translate, (tuple, list)) and len(translate) == 2, \\\n \"translate should be a list or tuple and it must be of length 2.\"\n for t in translate:\n if not (0.0 <= t <= 1.0):\n raise ValueError(\"translation values should be between 0 and 1\")\n self.translate = translate\n\n if scale is not None:\n assert isinstance(scale, (tuple, list)) and len(scale) == 2, \\\n \"scale should be a list or tuple and it must be of length 2.\"\n for s in scale:\n if s <= 0:\n raise ValueError(\"scale values should be positive\")\n self.scale = scale\n\n if shear is not None:\n if isinstance(shear, numbers.Number):\n if shear < 0:\n raise ValueError(\"If shear is a single number, it must be positive.\")\n self.shear = (-shear, shear)\n else:\n assert isinstance(shear, (tuple, list)) and len(shear) == 2, \\\n \"shear should be a list or tuple and it must be of length 2.\"\n self.shear = shear\n else:\n self.shear = shear\n\n self.resample = resample\n self.fillcolor = fillcolor\n\n @staticmethod\n def get_params(degrees, translate, scale_ranges, shears, img_size):\n angle = random.choice(degrees)\n if translate is not None:\n max_dx = translate[0] * img_size[0]\n max_dy = translate[1] * img_size[1]\n translations = (np.round(random.uniform(-max_dx, max_dx)),\n np.round(random.uniform(-max_dy, max_dy)))\n else:\n translations = (0, 0)\n\n if scale_ranges is not None:\n scale = random.uniform(scale_ranges[0], scale_ranges[1])\n else:\n scale = 1.0\n\n if shears is not None:\n shear = random.uniform(shears[0], shears[1])\n else:\n shear = 0.0\n\n return angle, translations, scale, shear\n\n def __call__(self, img, mask):\n ret = self.get_params(self.degrees, self.translate, self.scale, self.shear, img.size)\n return F.affine(img, *ret, resample=Image.BILINEAR, fillcolor=self.fillcolor), \\\n F.affine(mask, *ret, resample=Image.NEAREST, fillcolor=self.fillcolor)"
] |
[
[
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
guillochon/humantree
|
[
"94b8e01561da98701633a26452678e50c285c45c"
] |
[
"humantree/humantree.py"
] |
[
"\"\"\"Find trees on a property, make suggestions for new trees.\"\"\"\nimport json\nimport os\nimport pprint\nfrom glob import glob\n\nimport numpy as np\nimport requests\nfrom scipy import misc\nfrom skimage.io import imsave\nfrom skimage.transform import resize\nfrom tqdm import tqdm\n\npp = pprint.PrettyPrinter(indent=4)\n\n\nclass HumanTree(object):\n \"\"\"Count trees, make suggestions where new trees should be added.\"\"\"\n\n # Math.\n _TO_RAD = np.pi / 180\n\n # Geo-related variables.\n _PARCELS_URL = (\n \"https://raw.githubusercontent.com/cambridgegis/cambridgegis_data\"\n \"/master/Assessing/FY2018/FY2018_Parcels/\"\n \"ASSESSING_ParcelsFY2018.geojson\")\n _TREE_CANOPY_URL = (\n \"https://raw.githubusercontent.com/cambridgegis/cambridgegis_data/\"\n \"master/Environmental/Tree_Canopy_2014/\"\n \"ENVIRONMENTAL_TreeCanopy2014.topojson\")\n _PATTERN = (\n \"https://maps.googleapis.com/maps/api/staticmap?\"\n \"center={},{}&zoom={}&maptype=satellite&size={}x{}\"\n \"&key={}\")\n _LAT_OFFSET = 2.e-5 # The LIDAR data is slightly offset from the images.\n _ZOOM = 20\n _INPUT_IMG_SIZE = 640\n _OUTPUT_IMG_SIZE = 512\n _CROPPIX = 20\n _DPI = 100.0\n _SBUFF = 2.e-6 # buffer size for smoothing tree regions\n _POINT_BUFF = 2.e-5\n\n _SMOOTH = 1.0\n\n # UNet variables.\n _UNET_N = 512\n _UNET_LEVELS = 4\n _BATCH_SIZE = 8\n _TRAIN_EPOCHS = 20\n\n # Property metric variables.\n _DEFAULT_SQFT = 1000.0\n _DEFAULT_LOT_SQFT = 3000.0\n _ONE_TREE_SQFT = 500.0\n _REGIONS = {\n 'ENC': ['IL', 'IN', 'MI', 'OH', 'WI'],\n 'WNC': ['IA', 'KS', 'MN', 'MO', 'NE', 'ND', 'SD'],\n 'PAC': ['CA', 'OR', 'WA', 'AK'],\n 'MTN': ['AZ', 'CO', 'ID', 'MT', 'NV', 'NM', 'UT', 'WY'],\n 'NEC': ['CT', 'ME', 'MA', 'NH', 'RI', 'VT'],\n 'MAC': ['NY', 'NJ', 'PE', 'WV'],\n 'SAC': ['MD', 'DE', 'DC', 'WV', 'VA', 'NC', 'SC', 'GA', 'FL'],\n 'ESC': ['KY', 'TN', 'MS', 'AL'],\n 'WSC': ['TX', 'OK', 'AR', 'LA']\n }\n\n def __init__(self, **kwargs):\n \"\"\"Initialize, loading data.\"\"\"\n import eia\n import googlemaps\n import zillow\n from shapely.geometry import Polygon\n\n self._p = kwargs.get('logger')\n\n load_canopy_polys = kwargs.get('load_canopy_polys', True)\n\n self._dir_name = os.path.dirname(os.path.realpath(__file__))\n\n # Load meta.json.\n self.prt('Loading meta file...')\n meta_path = os.path.join(self._dir_name, '..', 'meta.json')\n if os.path.exists(meta_path):\n with open(meta_path, 'r') as f:\n meta = json.load(f)\n self._imgs_mean = meta['mean']\n self._imgs_std = meta['std']\n self._train_count = meta['train_count']\n\n # Load parcel data.\n self._parcels_fname = self.download_file(self._PARCELS_URL)\n\n with open(self._parcels_fname, 'r') as f:\n self._parcels = json.load(f)\n\n self._parcel_polygons = [\n x.get('geometry', {}).get('coordinates', [])\n for x in self._parcels.get('features', [])]\n\n self._parcel_polygons = list(filter(None, ([\n [y for y in x if len(y) >= 3] for x in self._parcel_polygons])))\n\n self._parcel_polygons = [[Polygon(y) for y in x if len(y) >= 3]\n for x in self._parcel_polygons]\n\n with open(os.path.join(self._dir_name, '..', 'google.key'), 'r') as f:\n self._google_key = f.readline().strip()\n self._google_client = googlemaps.Client(key=self._google_key)\n\n with open(os.path.join(self._dir_name, '..', 'eia.key'), 'r') as f:\n self._eia_key = f.readline().strip()\n self._eia_client = eia.API(self._eia_key)\n\n with open(os.path.join(self._dir_name, '..', 'zillow.key'), 'r') as f:\n self._zillow_key = f.readline().strip()\n self._zillow_client = zillow.ValuationApi()\n\n self._cropsize = self._INPUT_IMG_SIZE - 2 * self._CROPPIX\n\n # Load canopy data.\n if not load_canopy_polys:\n return\n\n self._canopy_fname = os.path.join(\n self._dir_name, '..', 'geo', 'ENVIRONMENTAL_TreeCanopy2014.json')\n with open(self._canopy_fname, 'r') as f:\n self._canopies = json.load(f)\n\n raw_canpols = [\n x.get('geometry', {}).get(\n 'coordinates', []) for x in self._canopies.get(\n 'features', []) if x.get('geometry', {}) is not None]\n\n raw_canpols = list(filter(None, ([\n [y for y in x if len(y) >= 3] for x in raw_canpols])))\n\n raw_canpols = [[Polygon([(\n a, b + self._LAT_OFFSET) for a, b in y]) for y in x if len(\n y) >= 3] for x in raw_canpols]\n\n self._canopy_polygons = []\n for canpoly in tqdm(raw_canpols, desc='Extracting canopy polygons'):\n cps = [x.buffer(0) for x in canpoly]\n cps = self._canopy_polygons.extend([a for b in [\n list(x.geoms) if 'multi' in str(type(\n x)).lower() else [x] for x in cps] for a in b])\n\n self._model = None\n\n def prt(self, txt):\n \"\"\"Print using the right printer function.\"\"\"\n if self._p is None:\n print(txt)\n else:\n self._p.info(txt)\n\n def download_file(self, url, fname=None):\n \"\"\"Download file if it doesn't exist locally.\"\"\"\n if fname is None:\n fname = url.split('/')[-1]\n if not os.path.exists(fname):\n response = requests.get(url, stream=True)\n block_size = 1024\n total_size = int(response.headers.get('content-length', 0))\n with open(fname, 'wb') as handle:\n for data in tqdm(\n response.iter_content(1024),\n total=np.ceil(total_size // block_size),\n unit='KB', unit_scale=True):\n handle.write(data)\n return fname\n\n def find_poly(self, address):\n \"\"\"Count trees on a property.\"\"\"\n from shapely.geometry import Point\n\n lon, lat = self.get_coordinates(address)\n if lon is None or lat is None:\n return None, None\n pt = Point(lon, lat)\n\n result = None\n for polys in self._parcel_polygons:\n for poly in polys:\n if poly.contains(pt):\n result = poly\n break\n\n return result, pt\n\n def get_bound_poly(self, poly):\n \"\"\"Get bounding polygon for property.\"\"\"\n from shapely.geometry import Polygon\n\n mlon, mlat = poly.centroid.coords[0]\n min_lon, min_lat, max_lon, max_lat = poly.bounds\n bp = self.get_static_map_bounds(\n mlat, mlon, self._ZOOM, self._cropsize, self._cropsize)\n\n return Polygon([\n bp[0], [bp[0][0], bp[1][1]], bp[1], [\n bp[1][0], bp[0][1]]]), mlat, mlon, bp\n\n def get_image(\n self, poly, mlat, mlon, zoom=None, imgsize=None, fname=None,\n target_dir=None, address=''):\n \"\"\"Get satellite image from polygon boundaries.\"\"\"\n import uuid\n import random\n\n zoom = self._ZOOM if zoom is None else zoom\n imgsize = self._INPUT_IMG_SIZE if imgsize is None else imgsize\n target_dir = 'parcels' if target_dir is None else target_dir\n\n if fname is None:\n rd = random.Random()\n rd.seed(address.lower().strip())\n fname = str(uuid.UUID(int=rd.getrandbits(128)))\n\n tdir = os.path.join(self._dir_name, '..', target_dir)\n if not os.path.isdir(tdir):\n os.mkdir(tdir)\n fpath = os.path.join(self._dir_name, '..', tdir, fname + '.png')\n process_image = False if os.path.exists(fpath) else True\n query_url = self._PATTERN.format(\n mlat, mlon, zoom, imgsize, imgsize,\n self._google_key)\n self.download_file(query_url, fname=fpath)\n if process_image:\n pic = misc.imread(fpath)\n npic = pic[self._CROPPIX:-self._CROPPIX,\n self._CROPPIX:-self._CROPPIX]\n npic = resize(\n npic, (self._OUTPUT_IMG_SIZE, self._OUTPUT_IMG_SIZE, 3),\n preserve_range=False, mode='constant')\n misc.imsave(fpath, npic)\n\n return fpath\n\n def get_image_from_address(self, address, fname=None):\n \"\"\"Get an image from an address.\"\"\"\n if not address:\n raise ValueError('Invalid address `{}`!'.format(address))\n\n poly, pt = self.find_poly(address)\n if pt is None:\n return None\n if poly is None:\n poly = pt.buffer(self._POINT_BUFF)\n bound_poly, mlat, mlon, __ = self.get_bound_poly(poly)\n fpath = self.get_image(\n bound_poly, mlat, mlon, address=address, target_dir='queries',\n fname=fname)\n pic = misc.imread(fpath)\n json_path = fpath.replace('.png', '.json')\n if not os.path.exists(json_path):\n with open(json_path, 'w') as f:\n json.dump(pic.tolist(), f, separators=(',', ':'))\n return fpath\n\n def make_mask_from_polys(self, polys, fpath, bound_poly=None, bp=None,\n buff=None, reverse_y=False):\n from shapely.ops import cascaded_union\n from matplotlib.patches import Polygon as MPPoly\n from shapely.geometry import Polygon\n from matplotlib.collections import PatchCollection\n import matplotlib.pyplot as plt\n plt.switch_backend('agg')\n\n if buff is None:\n buff = self._SBUFF\n\n if bound_poly is None:\n bp = [(0, 0), (self._OUTPUT_IMG_SIZE, self._OUTPUT_IMG_SIZE)]\n bound_poly = Polygon(\n [bp[0], (bp[1][0], bp[0][1]), bp[1], (bp[0][0], bp[1][1])])\n\n ipolys = []\n for cp in polys:\n if cp.disjoint(bound_poly):\n continue\n try:\n ipolys.append(cp.intersection(bound_poly).buffer(\n buff).buffer(buff).buffer(buff).buffer(buff))\n except Exception as ee:\n print(ee)\n\n merged_polys = ipolys\n # merged_polys = cascaded_union(ipolys)\n\n if 'Multi' not in str(type(merged_polys)) and not isinstance(\n merged_polys, list):\n merged_polys = [merged_polys]\n\n fig = plt.figure()\n ax = fig.gca()\n plt.axis('off')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n patches = [MPPoly(\n [[y[0], self._OUTPUT_IMG_SIZE - y[1]] for y in x.exterior.coords\n ] if reverse_y else\n x.exterior.coords) for x in merged_polys if hasattr(x, 'exterior')]\n if 'mask' in fpath:\n pc = PatchCollection(\n patches, alpha=1, facecolors='black',\n edgecolors='none', antialiased=False)\n plt.gray()\n else:\n pc = PatchCollection(\n patches, facecolors=(1, 0, 1, 0.2),\n edgecolors='magenta', antialiased=True,\n linewidth=4)\n ax.autoscale_view(True, True, True)\n ax.add_collection(pc)\n ax.set_xlim(bp[0][0], bp[1][0])\n ax.set_ylim(bp[0][1], bp[1][1])\n\n fig.subplots_adjust(\n bottom=0, left=0, top=self._OUTPUT_IMG_SIZE / self._DPI,\n right=self._OUTPUT_IMG_SIZE / self._DPI)\n fig.set_size_inches(1, 1)\n if 'mask' in fpath:\n plt.savefig(fpath, bbox_inches='tight', dpi=self._DPI,\n pad_inches=0)\n else:\n plt.savefig(fpath, bbox_inches='tight', dpi=self._DPI,\n pad_inches=0, transparent=True)\n plt.close()\n\n # If image is wrong size\n pic = misc.imread(fpath)\n shape = pic.shape\n if (shape[0] != self._OUTPUT_IMG_SIZE or\n shape[1] != self._OUTPUT_IMG_SIZE):\n dx = (shape[0] - self._OUTPUT_IMG_SIZE) / 2.0\n dy = (shape[1] - self._OUTPUT_IMG_SIZE) / 2.0\n dxm, dxp = int(np.ceil(dx)), int(np.floor(dx))\n dym, dyp = int(np.ceil(dy)), int(np.floor(dy))\n npic = pic[dxm:-dxp, dym:-dyp]\n misc.imsave(fpath, npic)\n\n def make_outline_from_mask(self, mask_path, outline_path):\n import rasterio\n from rasterio.features import shapes\n from shapely.geometry import shape\n\n with rasterio.open(mask_path) as src:\n image = src.read(1)\n mask = image != 255\n results = (\n {'properties': {'raster_val': v}, 'geometry': s}\n for i, (s, v)\n in enumerate(\n shapes(image, mask=mask, transform=src.affine)))\n shapes = [shape(x['geometry']) for x in list(results)]\n if not os.path.exists(outline_path):\n self.make_mask_from_polys(\n shapes, outline_path, buff=0.25, reverse_y=True)\n\n def get_poly_images(self, limit=None, purge=False):\n \"\"\"Retrieve images of all polygons on Google Maps.\"\"\"\n import matplotlib.pyplot as plt\n plt.switch_backend('agg')\n\n if not os.path.isdir('parcels'):\n os.mkdir('parcels')\n if purge:\n files = glob(os.path.join('parcels', '*'))\n for f in files:\n os.remove(f)\n\n votes = {}\n with open('votes.json', 'r') as f:\n votes = json.load(f)\n self._blacklist = [int(\n k[1:]) for k, v in votes.items() if k.startswith('t') and (\n float(v.get('bad', 0)) / max(v.get('good', 0) + v.get(\n 'okay', 0) + v.get('bad', 0), 1)) >= 0.9]\n print('Number of blacklisted masks: {}'.format(len(self._blacklist)))\n\n self._train_count = 0\n lots_skipped = 0\n lots_blacklisted = 0\n for pi, polys in enumerate(tqdm(self._parcel_polygons, total=limit)):\n if limit is not None and pi >= limit:\n break\n if pi in self._blacklist:\n lots_blacklisted += 1\n continue\n poly = polys[0]\n bound_poly, mlat, mlon, bp = self.get_bound_poly(poly)\n if not bound_poly.contains(poly):\n lots_skipped += 1\n continue\n\n fname = str(pi).zfill(5)\n\n mask_path = os.path.join(\n self._dir_name, '..', 'parcels', fname + '-mask.png')\n outline_path = os.path.join(\n self._dir_name, '..', 'parcels', fname + '-outline.png')\n\n if not os.path.exists(mask_path):\n self.make_mask_from_polys(\n self._canopy_polygons, mask_path, bound_poly, bp)\n\n if not os.path.exists(outline_path):\n self.make_outline_from_mask(mask_path, outline_path)\n\n self.get_image(bound_poly, mlat, mlon, fname=fname)\n\n self._train_count += 1\n\n print('Training on {} lots, skipped {} because they were '\n 'too large, and {} lots because they were '\n 'blacklisted.'.format(\n self._train_count, lots_skipped, lots_blacklisted))\n\n def get_state(self, address):\n \"\"\"Get lat/lon from address using Geocode API.\"\"\"\n result = self._google_client.geocode(address)\n\n acs = result[0].get('address_components', {})\n state = [x for x in acs if 'administrative_area_level_1' in x.get(\n 'types')][0].get('short_name')\n\n return state\n\n def get_zip(self, address):\n \"\"\"Get zip from address using Geocode API.\"\"\"\n result = self._google_client.geocode(address)\n\n acs = result[0].get('address_components', {})\n pc = [x for x in acs if 'postal_code' in x.get(\n 'types')][0].get('short_name')\n\n return pc\n\n def get_electricity_price(self, state):\n \"\"\"Get price of electricity per kwh.\"\"\"\n series = 'ELEC.PRICE.{}-ALL.M'.format(state)\n result = self._eia_client.data_by_series(series)\n\n result = [(int(k.replace(' ', '')), v) for k, v in result[\n list(result.keys())[0]].items()]\n result = sorted(result)[-1][1]\n return result\n\n def get_degree_days(self, state, type='cooling'):\n \"\"\"Get degree days for a given state.\"\"\"\n region = [k for k, v in self._REGIONS.items() if state in v][0]\n\n series = 'STEO.ZW{}D_{}.A'.format(\n 'C' if type == 'cooling' else 'H', region)\n result = self._eia_client.data_by_series(series)\n\n result = [(int(k.replace(' ', '')), v) for k, v in result[\n list(result.keys())[0]].items()]\n result = sorted(result)[-1][1]\n return result\n\n def get_zillow(self, address):\n \"\"\"Get deep search results for a property.\"\"\"\n zadd = address.replace(', USA', '')\n zzip = self.get_zip(zadd)\n return self._zillow_client.GetDeepSearchResults(\n self._zillow_key, zadd, zzip, True)\n\n def get_sqft(self, zill, lot=False):\n \"\"\"Get square feet from a zillow object.\"\"\"\n if not zill.has_extended_data:\n return None\n sqft = None\n if lot:\n sqft = (\n float(\n zill.extended_data.lot_size_sqft) if (\n zill.extended_data.lot_size_sqft is not None)\n else None)\n else:\n sqft = (\n float(\n zill.extended_data.finished_sqft) if (\n zill.extended_data.finished_sqft is not None)\n else None)\n return sqft\n\n def get_address_radius(self, address):\n \"\"\"Get effective radius of an address.\"\"\"\n try:\n zill = self.get_zillow(address)\n sqft = self.get_sqft(zill, lot=True)\n except Exception:\n sqft = None\n if sqft is None:\n sqft = self._DEFAULT_LOT_SQFT\n return 0.4 * np.sqrt(2.0 / np.pi * sqft)\n\n def get_zill_radius(self, zill):\n \"\"\"Get effective radius from a `Zillow` object.\"\"\"\n try:\n sqft = self.get_sqft(zill, lot=True)\n except Exception:\n sqft = None\n if sqft is None:\n sqft = self._DEFAULT_LOT_SQFT\n return 0.4 * np.sqrt(2.0 / np.pi * sqft)\n\n def get_updated_prop_details(self, zpid):\n \"\"\"Get extra details on properties provided by Zillow users.\"\"\"\n import xmltodict\n from zillow.place import Place\n from zillow.error import ZillowError\n url = 'https://www.zillow.com/webservice/GetUpdatedPropertyDetails.htm'\n parameters = {\n 'zws-id': self._zillow_key,\n 'zpid': zpid\n }\n resp = self._zillow_client._RequestUrl(url, 'GET', data=parameters)\n data = resp.content.decode('utf-8')\n\n xmltodict_data = xmltodict.parse(data)\n\n place = Place()\n try:\n place.set_data(xmltodict_data.get(\n 'SearchResults:searchresults',\n None)['response']['results']['result'])\n except Exception:\n raise ZillowError(\n {'message':\n \"Zillow did not return a valid response: %s\" % data})\n\n return place\n\n def get_coordinates(self, address):\n \"\"\"Get lat/lon from address using Geocode API.\"\"\"\n result = self._google_client.geocode(address)\n\n if not len(result) or 'geometry' not in result[0]:\n return (None, None)\n\n location = result[0].get('geometry', {}).get('location', {})\n\n lon = location.get('lng')\n lat = location.get('lat')\n\n return (lon, lat)\n\n def get_static_map_bounds(self, lat, lng, zoom, sx, sy):\n \"\"\"Get bounds of a static map from Google.\n\n From https://stackoverflow.com/questions/12507274/\n how-to-get-bounds-of-a-google-static-map\n \"\"\"\n # lat, lng - center\n # sx, sy - map size in pixels\n\n # 256 pixels - initial map size for zoom factor 0\n sz = 256 * 2 ** zoom\n\n # resolution in degrees per pixel\n res_lat = np.cos(lat * self._TO_RAD) * 360. / sz\n res_lng = 360. / sz\n\n d_lat = res_lat * sy / 2\n d_lng = res_lng * sx / 2\n\n return ((lng - d_lng, lat - d_lat), (lng + d_lng, lat + d_lat))\n\n def get_data(self, fractions=(0.0, 0.8), use_blacklist=True, limit=None):\n \"\"\"Return image and mask for training image segmentation.\"\"\"\n parcel_paths = list(sorted([\n x for x in glob(os.path.join(\n 'parcels', '*.png')) if (\n 'mask' not in x and 'outline' not in x and\n 'pred' not in x)]))\n mask_paths = list(sorted(glob(os.path.join('parcels', '*-mask.png'))))\n\n images = []\n masks = []\n min_i = 0 if fractions[0] == 0.0 else int(np.floor(\n fractions[0] * self._train_count)) + 1\n max_i = int(np.floor(fractions[1] * self._train_count))\n if limit is not None:\n max_i = min(max_i, limit)\n indices = list(range(min_i, max_i))\n pids = []\n for i in tqdm(indices, desc='Reading images into arrays'):\n image = misc.imread(parcel_paths[i])[:, :, :3]\n if image.shape[0] != self._OUTPUT_IMG_SIZE:\n image = resize(image, (self._UNET_N, self._UNET_N, 3),\n preserve_range=False, mode='constant')\n images.append(image)\n mask = misc.imread(mask_paths[i])[:, :, [0]]\n if mask.shape[0] != self._OUTPUT_IMG_SIZE:\n mask = resize(mask, (self._UNET_N, self._UNET_N, 1),\n preserve_range=False, mode='constant')\n masks.append(mask)\n pids.append(int(parcel_paths[i].split('/')[-1].split('.')[0]))\n\n return np.array(images), np.array(masks), pids\n\n def get_unet(self):\n \"\"\"Construct UNet.\"\"\"\n from keras.optimizers import Adam\n from keras.models import Model\n from keras.layers import (Conv2D, Conv2DTranspose, Input, MaxPooling2D,\n concatenate, Dropout)\n\n inputs = Input((self._UNET_N, self._UNET_N, 3))\n dlayers = [None for n in range(self._UNET_LEVELS + 1)]\n dlayers[0] = inputs\n layer = inputs\n for n in range(self._UNET_LEVELS):\n np1 = n + 1\n m = 32 * 2 ** n\n dlayers[np1] = Conv2D(\n m, (3, 3), activation='relu', padding='same',\n kernel_initializer='he_normal')(layer)\n dlayers[np1] = Dropout(0.5)(dlayers[np1])\n dlayers[np1] = Conv2D(\n m, (3, 3), activation='relu', padding='same',\n kernel_initializer='he_normal')(dlayers[np1])\n if n == self._UNET_LEVELS - 1: # don't pool last layer.\n break\n layer = MaxPooling2D(pool_size=(2, 2))(dlayers[np1])\n\n layer = dlayers[-1]\n for n in range(self._UNET_LEVELS - 1):\n m = 32 * 2 ** (self._UNET_LEVELS - n - 2)\n layer = concatenate([Conv2DTranspose(\n m, (2, 2), strides=(2, 2), padding='same')(\n layer), dlayers[self._UNET_LEVELS - n - 1]], axis=3)\n layer = Conv2D(\n m, (3, 3), activation='relu', padding='same',\n kernel_initializer='he_normal')(layer)\n layer = Dropout(0.5)(layer)\n layer = Conv2D(\n m, (3, 3), activation='relu', padding='same',\n kernel_initializer='he_normal')(layer)\n\n layer = Conv2D(1, (1, 1), activation='sigmoid')(layer)\n\n model = Model(inputs=[inputs], outputs=[layer])\n\n model.summary()\n\n model.compile(optimizer=Adam(lr=1e-5),\n loss='binary_crossentropy',\n metrics=['binary_crossentropy', 'acc'])\n\n return model\n\n def preprocess(self, imgs, channels=3, label='images'):\n \"\"\"Put images in the appropriate format.\"\"\"\n imgs_p = np.ndarray(\n (imgs.shape[0], self._UNET_N, self._UNET_N, channels),\n dtype=np.uint8)\n for i in tqdm(range(\n imgs.shape[0]), desc='Converting {}'.format(label)):\n imgs_p[i] = imgs[i].astype(np.uint8)\n\n return imgs_p\n\n def prepare_data(self):\n \"\"\"Get images and masks ready for UNet.\"\"\"\n imgs_train, imgs_mask_train, __ = self.get_data(fractions=(0.0, 0.8))\n\n imgs_train = self.preprocess(imgs_train, 3)\n imgs_mask_train = self.preprocess(imgs_mask_train, 1)\n\n self._imgs_train = imgs_train.astype('float32')\n self._imgs_mean = np.mean(self._imgs_train) # mean for data centering\n self._imgs_std = np.std(self._imgs_train) # std for data normalization\n\n self._imgs_train -= self._imgs_mean\n self._imgs_train /= self._imgs_std\n\n self._imgs_mask_train = imgs_mask_train.astype('float32')\n self._imgs_mask_train /= 255. # scale masks to [0, 1]\n\n def notice(self, txt=''):\n \"\"\"Print a notice for the user.\"\"\"\n print('-' * 30)\n print(txt)\n print('-' * 30)\n\n def train(self):\n \"\"\"Train DNN for image segmentation.\"\"\"\n from keras.callbacks import ModelCheckpoint, TensorBoard\n\n self.notice('Loading and preprocessing train data...')\n\n self.prepare_data()\n\n with open(os.path.join(self._dir_name, '..', 'meta.json'), 'w') as f:\n json.dump({\n 'train_count': self._train_count,\n 'mean': float(self._imgs_mean),\n 'std': float(self._imgs_std)}, f)\n\n self.notice('Creating and compiling model...')\n self._model = self.get_unet()\n model_checkpoint = ModelCheckpoint(\n os.path.join(self._dir_name, '..', 'weights.h5'),\n monitor='val_loss', save_best_only=True)\n\n self.notice('Fitting model...')\n\n tbCallBack = TensorBoard(write_grads=True, batch_size=self._BATCH_SIZE)\n\n self._model.fit(\n self._imgs_train, self._imgs_mask_train,\n batch_size=self._BATCH_SIZE, epochs=self._TRAIN_EPOCHS, verbose=1,\n shuffle=True, validation_split=0.2,\n # callbacks=[model_checkpoint])\n callbacks=[model_checkpoint, tbCallBack])\n\n def shade_fraction_of_address(self, address):\n fpath = self.predict_for_address(address)\n\n image = misc.imread(fpath)\n\n image[image < 255 / 2.0] = 1\n image[image > 255 / 2.0] = 0\n\n return np.sum(image) / (image.shape[0] * image.shape[1])\n\n def predict_for_address(self, address, fname=None):\n if not self._model:\n self._model = self.get_unet()\n self._model.load_weights(\n os.path.join(self._dir_name, '..', 'weights.h5'))\n\n fpath = self.get_image_from_address(address, fname=fname)\n\n image = misc.imread(fpath)[:, :, :3]\n image = image[np.newaxis, :, :, :].astype('float32')\n image -= self._imgs_mean\n image /= self._imgs_std\n\n pred = self._model.predict(image)\n\n pred_dir = 'preds'\n if not os.path.exists(pred_dir):\n os.mkdir(pred_dir)\n\n image = (pred[0, :, :, 0] * 255.).astype(np.uint8)\n pred_path = fpath.replace('.png', '-pred.png')\n imsave(pred_path, image)\n\n return pred_path\n\n def predict(self, kind='test', limit=-1):\n \"\"\"Test trained UNet.\"\"\"\n self.notice('Creating and compiling model...')\n self._model = self.get_unet()\n\n if kind == 'test':\n fractions = (0.8, 1.0)\n elif kind == 'train':\n fractions = (0.0, 0.8)\n elif kind == 'all':\n fractions = (0.0, 1.0)\n\n self.notice('Loading and preprocessing {} data...'.format(kind))\n imgs, masks, ids = self.get_data(\n fractions=fractions, use_blacklist=False, limit=limit)\n imgs = self.preprocess(imgs, 3)\n\n imgs = imgs.astype('float32')\n imgs -= self._imgs_mean\n imgs /= self._imgs_std\n\n self.notice('Loading saved weights...')\n self._model.load_weights(\n os.path.join(self._dir_name, '..', 'weights.h5'))\n\n self.notice('Predicting masks on test data...')\n imgs_preds = self._model.predict(\n imgs, verbose=1, batch_size=self._BATCH_SIZE)\n if imgs_preds.shape[1] != self._OUTPUT_IMG_SIZE:\n new_imgs_preds = np.empty((\n imgs_preds.shape[0], self._OUTPUT_IMG_SIZE,\n self._OUTPUT_IMG_SIZE, 1))\n for i in range(imgs_preds.shape[0]):\n new_imgs_preds[i] = resize(\n imgs_preds[i], (\n self._OUTPUT_IMG_SIZE, self._OUTPUT_IMG_SIZE, 1),\n preserve_range=False, mode='constant')\n imgs_preds = new_imgs_preds\n np.save('imgs_mask_test.npy', imgs_preds)\n\n self.notice('Saving predicted masks to files...')\n pred_dir = 'preds'\n if not os.path.exists(pred_dir):\n os.mkdir(pred_dir)\n for image, id in zip(imgs_preds, ids):\n image = (image[:, :, 0] * 255.).astype(np.uint8)\n zid = str(id).zfill(5)\n pred_path = os.path.join(pred_dir, zid + '-pred.png')\n imsave(pred_path, image)\n mask = image\n mask[mask < 255 / 2.0] = 0\n mask[mask > 255 / 2.0] = 255\n mask_path = os.path.join(pred_dir, zid + '-mask.png')\n imsave(mask_path, mask)\n outline_path = os.path.join(pred_dir, zid + '-outline.png')\n self.make_outline_from_mask(mask_path, outline_path)\n"
] |
[
[
"numpy.sqrt",
"numpy.ndarray",
"numpy.mean",
"matplotlib.patches.Polygon",
"matplotlib.pyplot.gray",
"numpy.save",
"numpy.ceil",
"numpy.std",
"matplotlib.pyplot.close",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure",
"scipy.misc.imsave",
"matplotlib.pyplot.switch_backend",
"matplotlib.pyplot.savefig",
"numpy.floor",
"numpy.array",
"numpy.sum",
"matplotlib.collections.PatchCollection",
"numpy.cos",
"scipy.misc.imread",
"numpy.empty"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"0.14",
"0.15",
"0.10",
"0.16",
"0.19",
"0.18",
"0.12",
"1.0",
"0.17",
"1.2"
],
"tensorflow": []
}
] |
drammock/mne-tools.github.io
|
[
"5d3a104d174255644d8d5335f58036e32695e85d",
"5d3a104d174255644d8d5335f58036e32695e85d",
"5d3a104d174255644d8d5335f58036e32695e85d",
"5d3a104d174255644d8d5335f58036e32695e85d",
"5d3a104d174255644d8d5335f58036e32695e85d",
"5d3a104d174255644d8d5335f58036e32695e85d",
"5d3a104d174255644d8d5335f58036e32695e85d",
"b54e38c9bbac38c6f53747075b5bad2936fbc5b9",
"b54e38c9bbac38c6f53747075b5bad2936fbc5b9",
"b54e38c9bbac38c6f53747075b5bad2936fbc5b9",
"5d3a104d174255644d8d5335f58036e32695e85d"
] |
[
"stable/_downloads/a0763e9183d7a6c5e07101a3d36cc949/plot_brainstorm_auditory.py",
"0.12/_downloads/plot_stats_cluster_methods.py",
"0.16/_downloads/plot_visualize_evoked.py",
"stable/_downloads/afd72e067412c390ceccc64f99255ba2/plot_compute_raw_data_spectrum.py",
"0.17/_downloads/42ebe982e3b37b9899162c8d60f2b555/plot_label_source_activations.py",
"0.15/_downloads/plot_ecog.py",
"0.11/_downloads/plot_brainstorm_data.py",
"0.13/_downloads/plot_compute_rt_decoder.py",
"0.14/_downloads/plot_ssp_projs_sensitivity_map.py",
"0.14/_downloads/plot_mne_inverse_psi_visual.py",
"0.14/_downloads/plot_object_epochs.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\n.. _tut-brainstorm-auditory:\n\n====================================\nBrainstorm auditory tutorial dataset\n====================================\n\nHere we compute the evoked from raw for the auditory Brainstorm\ntutorial dataset. For comparison, see [1]_ and the associated\n`brainstorm site <https://neuroimage.usc.edu/brainstorm/Tutorials/Auditory>`_.\n\nExperiment:\n\n - One subject, 2 acquisition runs 6 minutes each.\n - Each run contains 200 regular beeps and 40 easy deviant beeps.\n - Random ISI: between 0.7s and 1.7s seconds, uniformly distributed.\n - Button pressed when detecting a deviant with the right index finger.\n\nThe specifications of this dataset were discussed initially on the\n`FieldTrip bug tracker\n<http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=2300>`__.\n\nReferences\n----------\n.. [1] Tadel F, Baillet S, Mosher JC, Pantazis D, Leahy RM.\n Brainstorm: A User-Friendly Application for MEG/EEG Analysis.\n Computational Intelligence and Neuroscience, vol. 2011, Article ID\n 879716, 13 pages, 2011. doi:10.1155/2011/879716\n\"\"\"\n\n# Authors: Mainak Jas <[email protected]>\n# Eric Larson <[email protected]>\n# Jaakko Leppakangas <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport os.path as op\nimport pandas as pd\nimport numpy as np\n\nimport mne\nfrom mne import combine_evoked\nfrom mne.minimum_norm import apply_inverse\nfrom mne.datasets.brainstorm import bst_auditory\nfrom mne.io import read_raw_ctf\n\nprint(__doc__)\n\n###############################################################################\n# To reduce memory consumption and running time, some of the steps are\n# precomputed. To run everything from scratch change this to False. With\n# ``use_precomputed = False`` running time of this script can be several\n# minutes even on a fast computer.\nuse_precomputed = True\n\n###############################################################################\n# The data was collected with a CTF 275 system at 2400 Hz and low-pass\n# filtered at 600 Hz. Here the data and empty room data files are read to\n# construct instances of :class:`mne.io.Raw`.\ndata_path = bst_auditory.data_path()\n\nsubject = 'bst_auditory'\nsubjects_dir = op.join(data_path, 'subjects')\n\nraw_fname1 = op.join(data_path, 'MEG', 'bst_auditory',\n 'S01_AEF_20131218_01.ds')\nraw_fname2 = op.join(data_path, 'MEG', 'bst_auditory',\n 'S01_AEF_20131218_02.ds')\nerm_fname = op.join(data_path, 'MEG', 'bst_auditory',\n 'S01_Noise_20131218_01.ds')\n\n###############################################################################\n# In the memory saving mode we use ``preload=False`` and use the memory\n# efficient IO which loads the data on demand. However, filtering and some\n# other functions require the data to be preloaded in the memory.\npreload = not use_precomputed\nraw = read_raw_ctf(raw_fname1, preload=preload)\nn_times_run1 = raw.n_times\nmne.io.concatenate_raws([raw, read_raw_ctf(raw_fname2, preload=preload)])\nraw_erm = read_raw_ctf(erm_fname, preload=preload)\n\n###############################################################################\n# Data channel array consisted of 274 MEG axial gradiometers, 26 MEG reference\n# sensors and 2 EEG electrodes (Cz and Pz).\n# In addition:\n#\n# - 1 stim channel for marking presentation times for the stimuli\n# - 1 audio channel for the sent signal\n# - 1 response channel for recording the button presses\n# - 1 ECG bipolar\n# - 2 EOG bipolar (vertical and horizontal)\n# - 12 head tracking channels\n# - 20 unused channels\n#\n# The head tracking channels and the unused channels are marked as misc\n# channels. Here we define the EOG and ECG channels.\nraw.set_channel_types({'HEOG': 'eog', 'VEOG': 'eog', 'ECG': 'ecg'})\nif not use_precomputed:\n # Leave out the two EEG channels for easier computation of forward.\n raw.pick(['meg', 'stim', 'misc', 'eog', 'ecg'])\n\n###############################################################################\n# For noise reduction, a set of bad segments have been identified and stored\n# in csv files. The bad segments are later used to reject epochs that overlap\n# with them.\n# The file for the second run also contains some saccades. The saccades are\n# removed by using SSP. We use pandas to read the data from the csv files. You\n# can also view the files with your favorite text editor.\n\nannotations_df = pd.DataFrame()\noffset = n_times_run1\nfor idx in [1, 2]:\n csv_fname = op.join(data_path, 'MEG', 'bst_auditory',\n 'events_bad_0%s.csv' % idx)\n df = pd.read_csv(csv_fname, header=None,\n names=['onset', 'duration', 'id', 'label'])\n print('Events from run {0}:'.format(idx))\n print(df)\n\n df['onset'] += offset * (idx - 1)\n annotations_df = pd.concat([annotations_df, df], axis=0)\n\nsaccades_events = df[df['label'] == 'saccade'].values[:, :3].astype(int)\n\n# Conversion from samples to times:\nonsets = annotations_df['onset'].values / raw.info['sfreq']\ndurations = annotations_df['duration'].values / raw.info['sfreq']\ndescriptions = annotations_df['label'].values\n\nannotations = mne.Annotations(onsets, durations, descriptions)\nraw.set_annotations(annotations)\ndel onsets, durations, descriptions\n\n###############################################################################\n# Here we compute the saccade and EOG projectors for magnetometers and add\n# them to the raw data. The projectors are added to both runs.\nsaccade_epochs = mne.Epochs(raw, saccades_events, 1, 0., 0.5, preload=True,\n reject_by_annotation=False)\n\nprojs_saccade = mne.compute_proj_epochs(saccade_epochs, n_mag=1, n_eeg=0,\n desc_prefix='saccade')\nif use_precomputed:\n proj_fname = op.join(data_path, 'MEG', 'bst_auditory',\n 'bst_auditory-eog-proj.fif')\n projs_eog = mne.read_proj(proj_fname)[0]\nelse:\n projs_eog, _ = mne.preprocessing.compute_proj_eog(raw.load_data(),\n n_mag=1, n_eeg=0)\nraw.add_proj(projs_saccade)\nraw.add_proj(projs_eog)\ndel saccade_epochs, saccades_events, projs_eog, projs_saccade # To save memory\n\n###############################################################################\n# Visually inspect the effects of projections. Click on 'proj' button at the\n# bottom right corner to toggle the projectors on/off. EOG events can be\n# plotted by adding the event list as a keyword argument. As the bad segments\n# and saccades were added as annotations to the raw data, they are plotted as\n# well.\nraw.plot(block=True)\n\n###############################################################################\n# Typical preprocessing step is the removal of power line artifact (50 Hz or\n# 60 Hz). Here we notch filter the data at 60, 120 and 180 to remove the\n# original 60 Hz artifact and the harmonics. The power spectra are plotted\n# before and after the filtering to show the effect. The drop after 600 Hz\n# appears because the data was filtered during the acquisition. In memory\n# saving mode we do the filtering at evoked stage, which is not something you\n# usually would do.\nif not use_precomputed:\n raw.plot_psd(tmax=np.inf, picks='meg')\n notches = np.arange(60, 181, 60)\n raw.notch_filter(notches, phase='zero-double', fir_design='firwin2')\n raw.plot_psd(tmax=np.inf, picks='meg')\n\n###############################################################################\n# We also lowpass filter the data at 100 Hz to remove the hf components.\nif not use_precomputed:\n raw.filter(None, 100., h_trans_bandwidth=0.5, filter_length='10s',\n phase='zero-double', fir_design='firwin2')\n\n###############################################################################\n# Epoching and averaging.\n# First some parameters are defined and events extracted from the stimulus\n# channel (UPPT001). The rejection thresholds are defined as peak-to-peak\n# values and are in T / m for gradiometers, T for magnetometers and\n# V for EOG and EEG channels.\ntmin, tmax = -0.1, 0.5\nevent_id = dict(standard=1, deviant=2)\nreject = dict(mag=4e-12, eog=250e-6)\n# find events\nevents = mne.find_events(raw, stim_channel='UPPT001')\n\n###############################################################################\n# The event timing is adjusted by comparing the trigger times on detected\n# sound onsets on channel UADC001-4408.\nsound_data = raw[raw.ch_names.index('UADC001-4408')][0][0]\nonsets = np.where(np.abs(sound_data) > 2. * np.std(sound_data))[0]\nmin_diff = int(0.5 * raw.info['sfreq'])\ndiffs = np.concatenate([[min_diff + 1], np.diff(onsets)])\nonsets = onsets[diffs > min_diff]\nassert len(onsets) == len(events)\ndiffs = 1000. * (events[:, 0] - onsets) / raw.info['sfreq']\nprint('Trigger delay removed (μ ± σ): %0.1f ± %0.1f ms'\n % (np.mean(diffs), np.std(diffs)))\nevents[:, 0] = onsets\ndel sound_data, diffs\n\n###############################################################################\n# We mark a set of bad channels that seem noisier than others. This can also\n# be done interactively with ``raw.plot`` by clicking the channel name\n# (or the line). The marked channels are added as bad when the browser window\n# is closed.\nraw.info['bads'] = ['MLO52-4408', 'MRT51-4408', 'MLO42-4408', 'MLO43-4408']\n\n###############################################################################\n# The epochs (trials) are created for MEG channels. First we find the picks\n# for MEG and EOG channels. Then the epochs are constructed using these picks.\n# The epochs overlapping with annotated bad segments are also rejected by\n# default. To turn off rejection by bad segments (as was done earlier with\n# saccades) you can use keyword ``reject_by_annotation=False``.\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=['meg', 'eog'],\n baseline=(None, 0), reject=reject, preload=False,\n proj=True)\n\n###############################################################################\n# We only use first 40 good epochs from each run. Since we first drop the bad\n# epochs, the indices of the epochs are no longer same as in the original\n# epochs collection. Investigation of the event timings reveals that first\n# epoch from the second run corresponds to index 182.\nepochs.drop_bad()\nepochs_standard = mne.concatenate_epochs([epochs['standard'][range(40)],\n epochs['standard'][182:222]])\nepochs_standard.load_data() # Resampling to save memory.\nepochs_standard.resample(600, npad='auto')\nepochs_deviant = epochs['deviant'].load_data()\nepochs_deviant.resample(600, npad='auto')\ndel epochs\n\n###############################################################################\n# The averages for each conditions are computed.\nevoked_std = epochs_standard.average()\nevoked_dev = epochs_deviant.average()\ndel epochs_standard, epochs_deviant\n\n###############################################################################\n# Typical preprocessing step is the removal of power line artifact (50 Hz or\n# 60 Hz). Here we lowpass filter the data at 40 Hz, which will remove all\n# line artifacts (and high frequency information). Normally this would be done\n# to raw data (with :func:`mne.io.Raw.filter`), but to reduce memory\n# consumption of this tutorial, we do it at evoked stage. (At the raw stage,\n# you could alternatively notch filter with :func:`mne.io.Raw.notch_filter`.)\nfor evoked in (evoked_std, evoked_dev):\n evoked.filter(l_freq=None, h_freq=40., fir_design='firwin')\n\n###############################################################################\n# Here we plot the ERF of standard and deviant conditions. In both conditions\n# we can see the P50 and N100 responses. The mismatch negativity is visible\n# only in the deviant condition around 100-200 ms. P200 is also visible around\n# 170 ms in both conditions but much stronger in the standard condition. P300\n# is visible in deviant condition only (decision making in preparation of the\n# button press). You can view the topographies from a certain time span by\n# painting an area with clicking and holding the left mouse button.\nevoked_std.plot(window_title='Standard', gfp=True, time_unit='s')\nevoked_dev.plot(window_title='Deviant', gfp=True, time_unit='s')\n\n\n###############################################################################\n# Show activations as topography figures.\ntimes = np.arange(0.05, 0.301, 0.025)\nevoked_std.plot_topomap(times=times, title='Standard', time_unit='s')\nevoked_dev.plot_topomap(times=times, title='Deviant', time_unit='s')\n\n###############################################################################\n# We can see the MMN effect more clearly by looking at the difference between\n# the two conditions. P50 and N100 are no longer visible, but MMN/P200 and\n# P300 are emphasised.\nevoked_difference = combine_evoked([evoked_dev, -evoked_std], weights='equal')\nevoked_difference.plot(window_title='Difference', gfp=True, time_unit='s')\n\n###############################################################################\n# Source estimation.\n# We compute the noise covariance matrix from the empty room measurement\n# and use it for the other runs.\nreject = dict(mag=4e-12)\ncov = mne.compute_raw_covariance(raw_erm, reject=reject)\ncov.plot(raw_erm.info)\ndel raw_erm\n\n###############################################################################\n# The transformation is read from a file. More information about coregistering\n# the data, see :ref:`c_legacy_ch_interactive_analysis` or\n# :func:`mne.gui.coregistration`.\ntrans_fname = op.join(data_path, 'MEG', 'bst_auditory',\n 'bst_auditory-trans.fif')\ntrans = mne.read_trans(trans_fname)\n\n###############################################################################\n# To save time and memory, the forward solution is read from a file. Set\n# ``use_precomputed=False`` in the beginning of this script to build the\n# forward solution from scratch. The head surfaces for constructing a BEM\n# solution are read from a file. Since the data only contains MEG channels, we\n# only need the inner skull surface for making the forward solution. For more\n# information: :ref:`CHDBBCEJ`, :func:`mne.setup_source_space`,\n# :ref:`create_bem_model`, :func:`mne.bem.make_watershed_bem`.\nif use_precomputed:\n fwd_fname = op.join(data_path, 'MEG', 'bst_auditory',\n 'bst_auditory-meg-oct-6-fwd.fif')\n fwd = mne.read_forward_solution(fwd_fname)\nelse:\n src = mne.setup_source_space(subject, spacing='ico4',\n subjects_dir=subjects_dir, overwrite=True)\n model = mne.make_bem_model(subject=subject, ico=4, conductivity=[0.3],\n subjects_dir=subjects_dir)\n bem = mne.make_bem_solution(model)\n fwd = mne.make_forward_solution(evoked_std.info, trans=trans, src=src,\n bem=bem)\n\ninv = mne.minimum_norm.make_inverse_operator(evoked_std.info, fwd, cov)\nsnr = 3.0\nlambda2 = 1.0 / snr ** 2\ndel fwd\n\n###############################################################################\n# The sources are computed using dSPM method and plotted on an inflated brain\n# surface. For interactive controls over the image, use keyword\n# ``time_viewer=True``.\n# Standard condition.\nstc_standard = mne.minimum_norm.apply_inverse(evoked_std, inv, lambda2, 'dSPM')\nbrain = stc_standard.plot(subjects_dir=subjects_dir, subject=subject,\n surface='inflated', time_viewer=False, hemi='lh',\n initial_time=0.1, time_unit='s')\ndel stc_standard, brain\n\n###############################################################################\n# Deviant condition.\nstc_deviant = mne.minimum_norm.apply_inverse(evoked_dev, inv, lambda2, 'dSPM')\nbrain = stc_deviant.plot(subjects_dir=subjects_dir, subject=subject,\n surface='inflated', time_viewer=False, hemi='lh',\n initial_time=0.1, time_unit='s')\ndel stc_deviant, brain\n\n###############################################################################\n# Difference.\nstc_difference = apply_inverse(evoked_difference, inv, lambda2, 'dSPM')\nbrain = stc_difference.plot(subjects_dir=subjects_dir, subject=subject,\n surface='inflated', time_viewer=False, hemi='lh',\n initial_time=0.15, time_unit='s')\n",
"# doc:slow-example\n\"\"\"\n.. _tut_stats_cluster_methods:\n\n======================================================\nPermutation t-test on toy data with spatial clustering\n======================================================\n\nFollowing the illustrative example of Ridgway et al. 2012,\nthis demonstrates some basic ideas behind both the \"hat\"\nvariance adjustment method, as well as threshold-free\ncluster enhancement (TFCE) methods in mne-python.\n\nThis toy dataset consists of a 40 x 40 square with a \"signal\"\npresent in the center (at pixel [20, 20]) with white noise\nadded and a 5-pixel-SD normal smoothing kernel applied.\n\nFor more information, see:\nRidgway et al. 2012, \"The problem of low variance voxels in\nstatistical parametric mapping; a new hat avoids a 'haircut'\",\nNeuroImage. 2012 Feb 1;59(3):2131-41.\n\nSmith and Nichols 2009, \"Threshold-free cluster enhancement:\naddressing problems of smoothing, threshold dependence, and\nlocalisation in cluster inference\", NeuroImage 44 (2009) 83-98.\n\nIn the top row plot the T statistic over space, peaking toward the\ncenter. Note that it has peaky edges. Second, with the \"hat\" variance\ncorrection/regularization, the peak becomes correctly centered. Third,\nthe TFCE approach also corrects for these edge artifacts. Fourth, the\nthe two methods combined provide a tighter estimate, for better or\nworse.\n\nNow considering multiple-comparisons corrected statistics on these\nvariables, note that a non-cluster test (e.g., FDR or Bonferroni) would\nmis-localize the peak due to sharpness in the T statistic driven by\nlow-variance pixels toward the edge of the plateau. Standard clustering\n(first plot in the second row) identifies the correct region, but the\nwhole area must be declared significant, so no peak analysis can be done.\nAlso, the peak is broad. In this method, all significances are\nfamily-wise error rate (FWER) corrected, and the method is\nnon-parametric so assumptions of Gaussian data distributions (which do\nactually hold for this example) don't need to be satisfied. Adding the\n\"hat\" technique tightens the estimate of significant activity (second\nplot). The TFCE approach (third plot) allows analyzing each significant\npoint independently, but still has a broadened estimate. Note that\nthis is also FWER corrected. Finally, combining the TFCE and \"hat\"\nmethods tightens the area declared significant (again FWER corrected),\nand allows for evaluation of each point independently instead of as\na single, broad cluster.\n\nNote that this example does quite a bit of processing, so even on a\nfast machine it can take a few minutes to complete.\n\"\"\"\n# Authors: Eric Larson <[email protected]>\n# License: BSD (3-clause)\n\nimport numpy as np\nfrom scipy import stats\nfrom functools import partial\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D # noqa; this changes hidden mpl vars\n\nfrom mne.stats import (spatio_temporal_cluster_1samp_test,\n bonferroni_correction, ttest_1samp_no_p)\n\ntry:\n from sklearn.feature_extraction.image import grid_to_graph\nexcept ImportError:\n from scikits.learn.feature_extraction.image import grid_to_graph\n\nprint(__doc__)\n\n###############################################################################\n# Set parameters\n# --------------\nwidth = 40\nn_subjects = 10\nsignal_mean = 100\nsignal_sd = 100\nnoise_sd = 0.01\ngaussian_sd = 5\nsigma = 1e-3 # sigma for the \"hat\" method\nthreshold = -stats.distributions.t.ppf(0.05, n_subjects - 1)\nthreshold_tfce = dict(start=0, step=0.2)\nn_permutations = 1024 # number of clustering permutations (1024 for exact)\n\n###############################################################################\n# Construct simulated data\n# ------------------------\n#\n# Make the connectivity matrix just next-neighbor spatially\nn_src = width * width\nconnectivity = grid_to_graph(width, width)\n\n# For each \"subject\", make a smoothed noisy signal with a centered peak\nrng = np.random.RandomState(42)\nX = noise_sd * rng.randn(n_subjects, width, width)\n# Add a signal at the dead center\nX[:, width // 2, width // 2] = signal_mean + rng.randn(n_subjects) * signal_sd\n# Spatially smooth with a 2D Gaussian kernel\nsize = width // 2 - 1\ngaussian = np.exp(-(np.arange(-size, size + 1) ** 2 / float(gaussian_sd ** 2)))\nfor si in range(X.shape[0]):\n for ri in range(X.shape[1]):\n X[si, ri, :] = np.convolve(X[si, ri, :], gaussian, 'same')\n for ci in range(X.shape[2]):\n X[si, :, ci] = np.convolve(X[si, :, ci], gaussian, 'same')\n\n###############################################################################\n# Do some statistics\n# ------------------\n#\n# .. note::\n# X needs to be a multi-dimensional array of shape\n# samples (subjects) x time x space, so we permute dimensions:\nX = X.reshape((n_subjects, 1, n_src))\n\n###############################################################################\n# Now let's do some clustering using the standard method.\n#\n# .. note::\n# Not specifying a connectivity matrix implies grid-like connectivity,\n# which we want here:\nT_obs, clusters, p_values, H0 = \\\n spatio_temporal_cluster_1samp_test(X, n_jobs=1, threshold=threshold,\n connectivity=connectivity,\n tail=1, n_permutations=n_permutations)\n\n# Let's put the cluster data in a readable format\nps = np.zeros(width * width)\nfor cl, p in zip(clusters, p_values):\n ps[cl[1]] = -np.log10(p)\nps = ps.reshape((width, width))\nT_obs = T_obs.reshape((width, width))\n\n# To do a Bonferroni correction on these data is simple:\np = stats.distributions.t.sf(T_obs, n_subjects - 1)\np_bon = -np.log10(bonferroni_correction(p)[1])\n\n# Now let's do some clustering using the standard method with \"hat\":\nstat_fun = partial(ttest_1samp_no_p, sigma=sigma)\nT_obs_hat, clusters, p_values, H0 = \\\n spatio_temporal_cluster_1samp_test(X, n_jobs=1, threshold=threshold,\n connectivity=connectivity,\n tail=1, n_permutations=n_permutations,\n stat_fun=stat_fun)\n\n# Let's put the cluster data in a readable format\nps_hat = np.zeros(width * width)\nfor cl, p in zip(clusters, p_values):\n ps_hat[cl[1]] = -np.log10(p)\nps_hat = ps_hat.reshape((width, width))\nT_obs_hat = T_obs_hat.reshape((width, width))\n\n# Now the threshold-free cluster enhancement method (TFCE):\nT_obs_tfce, clusters, p_values, H0 = \\\n spatio_temporal_cluster_1samp_test(X, n_jobs=1, threshold=threshold_tfce,\n connectivity=connectivity,\n tail=1, n_permutations=n_permutations)\nT_obs_tfce = T_obs_tfce.reshape((width, width))\nps_tfce = -np.log10(p_values.reshape((width, width)))\n\n# Now the TFCE with \"hat\" variance correction:\nT_obs_tfce_hat, clusters, p_values, H0 = \\\n spatio_temporal_cluster_1samp_test(X, n_jobs=1, threshold=threshold_tfce,\n connectivity=connectivity,\n tail=1, n_permutations=n_permutations,\n stat_fun=stat_fun)\nT_obs_tfce_hat = T_obs_tfce_hat.reshape((width, width))\nps_tfce_hat = -np.log10(p_values.reshape((width, width)))\n\n###############################################################################\n# Visualize results\n# -----------------\nfig = plt.figure(facecolor='w')\n\nx, y = np.mgrid[0:width, 0:width]\nkwargs = dict(rstride=1, cstride=1, linewidth=0, cmap='Greens')\n\nTs = [T_obs, T_obs_hat, T_obs_tfce, T_obs_tfce_hat]\ntitles = ['T statistic', 'T with \"hat\"', 'TFCE statistic', 'TFCE w/\"hat\" stat']\nfor ii, (t, title) in enumerate(zip(Ts, titles)):\n ax = fig.add_subplot(2, 4, ii + 1, projection='3d')\n ax.plot_surface(x, y, t, **kwargs)\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_title(title)\n\np_lims = [1.3, -np.log10(1.0 / n_permutations)]\npvals = [ps, ps_hat, ps_tfce, ps_tfce_hat]\ntitles = ['Standard clustering', 'Clust. w/\"hat\"',\n 'Clust. w/TFCE', 'Clust. w/TFCE+\"hat\"']\naxs = []\nfor ii, (p, title) in enumerate(zip(pvals, titles)):\n ax = fig.add_subplot(2, 4, 5 + ii)\n plt.imshow(p, cmap='Purples', vmin=p_lims[0], vmax=p_lims[1])\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_title(title)\n axs.append(ax)\n\nplt.tight_layout()\nfor ax in axs:\n cbar = plt.colorbar(ax=ax, shrink=0.75, orientation='horizontal',\n fraction=0.1, pad=0.025)\n cbar.set_label('-log10(p)')\n cbar.set_ticks(p_lims)\n cbar.set_ticklabels(['%0.1f' % p for p in p_lims])\n\nplt.show()\n",
"\"\"\"\n=====================\nVisualize Evoked data\n=====================\n\nIn this tutorial we focus on the plotting functions of :class:`mne.Evoked`.\n\"\"\"\nimport os.path as op\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\n\n# sphinx_gallery_thumbnail_number = 9\n\n###############################################################################\n# First we read the evoked object from a file. Check out\n# :ref:`tut_epoching_and_averaging` to get to this stage from raw data.\ndata_path = mne.datasets.sample.data_path()\nfname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-ave.fif')\nevoked = mne.read_evokeds(fname, baseline=(None, 0), proj=True)\nprint(evoked)\n\n###############################################################################\n# Notice that ``evoked`` is a list of :class:`evoked <mne.Evoked>` instances.\n# You can read only one of the categories by passing the argument ``condition``\n# to :func:`mne.read_evokeds`. To make things more simple for this tutorial, we\n# read each instance to a variable.\nevoked_l_aud = evoked[0]\nevoked_r_aud = evoked[1]\nevoked_l_vis = evoked[2]\nevoked_r_vis = evoked[3]\n\n###############################################################################\n# Let's start with a simple one. We plot event related potentials / fields\n# (ERP/ERF). The bad channels are not plotted by default. Here we explicitly\n# set the ``exclude`` parameter to show the bad channels in red. All plotting\n# functions of MNE-python return a handle to the figure instance. When we have\n# the handle, we can customise the plots to our liking.\nfig = evoked_l_aud.plot(exclude=(), time_unit='s')\n\n###############################################################################\n# All plotting functions of MNE-python return a handle to the figure instance.\n# When we have the handle, we can customise the plots to our liking. For\n# example, we can get rid of the empty space with a simple function call.\nfig.tight_layout()\n\n###############################################################################\n# Now we will make it a bit fancier and only use MEG channels. Many of the\n# MNE-functions include a ``picks`` parameter to include a selection of\n# channels. ``picks`` is simply a list of channel indices that you can easily\n# construct with :func:`mne.pick_types`. See also :func:`mne.pick_channels` and\n# :func:`mne.pick_channels_regexp`.\n# Using ``spatial_colors=True``, the individual channel lines are color coded\n# to show the sensor positions - specifically, the x, y, and z locations of\n# the sensors are transformed into R, G and B values.\npicks = mne.pick_types(evoked_l_aud.info, meg=True, eeg=False, eog=False)\nevoked_l_aud.plot(spatial_colors=True, gfp=True, picks=picks, time_unit='s')\n\n###############################################################################\n# Notice the legend on the left. The colors would suggest that there may be two\n# separate sources for the signals. This wasn't obvious from the first figure.\n# Try painting the slopes with left mouse button. It should open a new window\n# with topomaps (scalp plots) of the average over the painted area. There is\n# also a function for drawing topomaps separately.\nevoked_l_aud.plot_topomap(time_unit='s')\n\n###############################################################################\n# By default the topomaps are drawn from evenly spread out points of time over\n# the evoked data. We can also define the times ourselves.\ntimes = np.arange(0.05, 0.151, 0.05)\nevoked_r_aud.plot_topomap(times=times, ch_type='mag', time_unit='s')\n\n###############################################################################\n# Or we can automatically select the peaks.\nevoked_r_aud.plot_topomap(times='peaks', ch_type='mag', time_unit='s')\n\n###############################################################################\n# You can take a look at the documentation of :func:`mne.Evoked.plot_topomap`\n# or simply write ``evoked_r_aud.plot_topomap?`` in your python console to\n# see the different parameters you can pass to this function. Most of the\n# plotting functions also accept ``axes`` parameter. With that, you can\n# customise your plots even further. First we create a set of matplotlib\n# axes in a single figure and plot all of our evoked categories next to each\n# other.\nfig, ax = plt.subplots(1, 5, figsize=(8, 2))\nkwargs = dict(times=0.1, show=False, vmin=-300, vmax=300, time_unit='s')\nevoked_l_aud.plot_topomap(axes=ax[0], colorbar=True, **kwargs)\nevoked_r_aud.plot_topomap(axes=ax[1], colorbar=False, **kwargs)\nevoked_l_vis.plot_topomap(axes=ax[2], colorbar=False, **kwargs)\nevoked_r_vis.plot_topomap(axes=ax[3], colorbar=False, **kwargs)\nfor ax, title in zip(ax[:4], ['Aud/L', 'Aud/R', 'Vis/L', 'Vis/R']):\n ax.set_title(title)\nplt.show()\n\n###############################################################################\n# Notice that we created five axes, but had only four categories. The fifth\n# axes was used for drawing the colorbar. You must provide room for it when you\n# create this kind of custom plots or turn the colorbar off with\n# ``colorbar=False``. That's what the warnings are trying to tell you. Also, we\n# used ``show=False`` for the three first function calls. This prevents the\n# showing of the figure prematurely. The behavior depends on the mode you are\n# using for your python session. See http://matplotlib.org/users/shell.html for\n# more information.\n#\n# We can combine the two kinds of plots in one figure using the\n# :func:`mne.Evoked.plot_joint` method of Evoked objects. Called as-is\n# (``evoked.plot_joint()``), this function should give an informative display\n# of spatio-temporal dynamics.\n# You can directly style the time series part and the topomap part of the plot\n# using the ``topomap_args`` and ``ts_args`` parameters. You can pass key-value\n# pairs as a python dictionary. These are then passed as parameters to the\n# topomaps (:func:`mne.Evoked.plot_topomap`) and time series\n# (:func:`mne.Evoked.plot`) of the joint plot.\n# For an example of specific styling using these ``topomap_args`` and\n# ``ts_args`` arguments, here, topomaps at specific time points\n# (90 and 200 ms) are shown, sensors are not plotted (via an argument\n# forwarded to `plot_topomap`), and the Global Field Power is shown:\nts_args = dict(gfp=True, time_unit='s')\ntopomap_args = dict(sensors=False, time_unit='s')\nevoked_r_aud.plot_joint(title='right auditory', times=[.09, .20],\n ts_args=ts_args, topomap_args=topomap_args)\n\n###############################################################################\n# Sometimes, you may want to compare two or more conditions at a selection of\n# sensors, or e.g. for the Global Field Power. For this, you can use the\n# function :func:`mne.viz.plot_compare_evokeds`. The easiest way is to create\n# a Python dictionary, where the keys are condition names and the values are\n# :class:`mne.Evoked` objects. If you provide lists of :class:`mne.Evoked`\n# objects, such as those for multiple subjects, the grand average is plotted,\n# along with a confidence interval band - this can be used to contrast\n# conditions for a whole experiment.\n# First, we load in the evoked objects into a dictionary, setting the keys to\n# '/'-separated tags (as we can do with event_ids for epochs). Then, we plot\n# with :func:`mne.viz.plot_compare_evokeds`.\n# The plot is styled with dict arguments, again using \"/\"-separated tags.\n# We plot a MEG channel with a strong auditory response.\n#\n# For move advanced plotting using :func:`mne.viz.plot_compare_evokeds`.\n# See also :ref:`sphx_glr_auto_tutorials_plot_metadata_epochs.py`.\nconditions = [\"Left Auditory\", \"Right Auditory\", \"Left visual\", \"Right visual\"]\nevoked_dict = dict()\nfor condition in conditions:\n evoked_dict[condition.replace(\" \", \"/\")] = mne.read_evokeds(\n fname, baseline=(None, 0), proj=True, condition=condition)\nprint(evoked_dict)\n\ncolors = dict(Left=\"Crimson\", Right=\"CornFlowerBlue\")\nlinestyles = dict(Auditory='-', visual='--')\npick = evoked_dict[\"Left/Auditory\"].ch_names.index('MEG 1811')\n\nmne.viz.plot_compare_evokeds(evoked_dict, picks=pick, colors=colors,\n linestyles=linestyles, split_legend=True)\n\n###############################################################################\n# We can also plot the activations as images. The time runs along the x-axis\n# and the channels along the y-axis. The amplitudes are color coded so that\n# the amplitudes from negative to positive translates to shift from blue to\n# red. White means zero amplitude. You can use the ``cmap`` parameter to define\n# the color map yourself. The accepted values include all matplotlib colormaps.\nevoked_r_aud.plot_image(picks=picks, time_unit='s')\n\n###############################################################################\n# Finally we plot the sensor data as a topographical view. In the simple case\n# we plot only left auditory responses, and then we plot them all in the same\n# figure for comparison. Click on the individual plots to open them bigger.\ntitle = 'MNE sample data\\n(condition : %s)'\nevoked_l_aud.plot_topo(title=title % evoked_l_aud.comment,\n background_color='k', color=['white'])\nmne.viz.plot_evoked_topo(evoked, title=title % 'Left/Right Auditory/Visual',\n background_color='w')\n\n###############################################################################\n# Visualizing field lines in 3D\n# -----------------------------\n# We now compute the field maps to project MEG and EEG data to the MEG helmet\n# and scalp surface.\n#\n# To do this, we need coregistration information. See\n# :ref:`tut_forward` for more details. Here we just illustrate usage.\n\nsubjects_dir = data_path + '/subjects'\ntrans_fname = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'\n\nmaps = mne.make_field_map(evoked_l_aud, trans=trans_fname, subject='sample',\n subjects_dir=subjects_dir, n_jobs=1)\n\n# Finally, explore several points in time\nfield_map = evoked_l_aud.plot_field(maps, time=.1)\n\n###############################################################################\n# .. note::\n# If trans_fname is set to None then only MEG estimates can be visualized.\n",
"\"\"\"\n==================================================\nCompute the power spectral density of raw data\n==================================================\n\nThis script shows how to compute the power spectral density (PSD)\nof measurements on a raw dataset. It also show the effect of applying SSP\nto the data to reduce ECG and EOG artifacts.\n\"\"\"\n# Authors: Alexandre Gramfort <[email protected]>\n# Martin Luessi <[email protected]>\n# Eric Larson <[email protected]>\n# License: BSD (3-clause)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne import io, read_proj, read_selection\nfrom mne.datasets import sample\nfrom mne.time_frequency import psd_multitaper\n\nprint(__doc__)\n\n###############################################################################\n# Load data\n# ---------\n#\n# We'll load a sample MEG dataset, along with SSP projections that will\n# allow us to reduce EOG and ECG artifacts. For more information about\n# reducing artifacts, see the preprocessing section in :ref:`documentation`.\n\ndata_path = sample.data_path()\nraw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'\nproj_fname = data_path + '/MEG/sample/sample_audvis_eog-proj.fif'\n\ntmin, tmax = 0, 60 # use the first 60s of data\n\n# Setup for reading the raw data (to save memory, crop before loading)\nraw = io.read_raw_fif(raw_fname).crop(tmin, tmax).load_data()\nraw.info['bads'] += ['MEG 2443', 'EEG 053'] # bads + 2 more\n\n# Add SSP projection vectors to reduce EOG and ECG artifacts\nprojs = read_proj(proj_fname)\nraw.add_proj(projs, remove_existing=True)\n\n\nfmin, fmax = 2, 300 # look at frequencies between 2 and 300Hz\nn_fft = 2048 # the FFT size (n_fft). Ideally a power of 2\n\n###############################################################################\n# Plot the raw PSD\n# ----------------\n#\n# First we'll visualize the raw PSD of our data. We'll do this on all of the\n# channels first. Note that there are several parameters to the\n# :meth:`mne.io.Raw.plot_psd` method, some of which will be explained below.\n\nraw.plot_psd(area_mode='range', tmax=10.0, show=False, average=True)\n\n###############################################################################\n# Plot a cleaned PSD\n# ------------------\n#\n# Next we'll focus the visualization on a subset of channels.\n# This can be useful for identifying particularly noisy channels or\n# investigating how the power spectrum changes across channels.\n#\n# We'll visualize how this PSD changes after applying some standard\n# filtering techniques. We'll first apply the SSP projections, which is\n# accomplished with the ``proj=True`` kwarg. We'll then perform a notch filter\n# to remove particular frequency bands.\n\n# Pick MEG magnetometers in the Left-temporal region\nselection = read_selection('Left-temporal')\npicks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False,\n stim=False, exclude='bads', selection=selection)\n\n# Let's just look at the first few channels for demonstration purposes\npicks = picks[:4]\n\nplt.figure()\nax = plt.axes()\nraw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,\n n_jobs=1, proj=False, ax=ax, color=(0, 0, 1), picks=picks,\n show=False, average=True)\n\nraw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,\n n_jobs=1, proj=True, ax=ax, color=(0, 1, 0), picks=picks,\n show=False, average=True)\n\n# And now do the same with SSP + notch filtering\n# Pick all channels for notch since the SSP projection mixes channels together\nraw.notch_filter(np.arange(60, 241, 60), n_jobs=1, fir_design='firwin')\nraw.plot_psd(tmin=tmin, tmax=tmax, fmin=fmin, fmax=fmax, n_fft=n_fft,\n n_jobs=1, proj=True, ax=ax, color=(1, 0, 0), picks=picks,\n show=False, average=True)\n\nax.set_title('Four left-temporal magnetometers')\nplt.legend(ax.lines[::3], ['Without SSP', 'With SSP', 'SSP + Notch'])\n\n###############################################################################\n# Alternative functions for PSDs\n# ------------------------------\n#\n# There are also several functions in MNE that create a PSD using a Raw\n# object. These are in the :mod:`mne.time_frequency` module and begin with\n# ``psd_*``. For example, we'll use a multitaper method to compute the PSD\n# below.\n\nf, ax = plt.subplots()\npsds, freqs = psd_multitaper(raw, low_bias=True, tmin=tmin, tmax=tmax,\n fmin=fmin, fmax=fmax, proj=True, picks=picks,\n n_jobs=1)\npsds = 10 * np.log10(psds)\npsds_mean = psds.mean(0)\npsds_std = psds.std(0)\n\nax.plot(freqs, psds_mean, color='k')\nax.fill_between(freqs, psds_mean - psds_std, psds_mean + psds_std,\n color='k', alpha=.5)\nax.set(title='Multitaper PSD', xlabel='Frequency',\n ylabel='Power Spectral Density (dB)')\nplt.show()\n",
"\"\"\"\n====================================================\nExtracting the time series of activations in a label\n====================================================\n\nWe first apply a dSPM inverse operator to get signed activations in a label\n(with positive and negative values) and we then compare different strategies\nto average the times series in a label. We compare a simple average, with an\naveraging using the dipoles normal (flip mode) and then a PCA,\nalso using a sign flip.\n\"\"\"\n# Author: Alexandre Gramfort <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne.datasets import sample\nfrom mne.minimum_norm import read_inverse_operator, apply_inverse\n\nprint(__doc__)\n\ndata_path = sample.data_path()\nlabel = 'Aud-lh'\nlabel_fname = data_path + '/MEG/sample/labels/%s.label' % label\nfname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'\nfname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'\n\nsnr = 3.0\nlambda2 = 1.0 / snr ** 2\nmethod = \"dSPM\" # use dSPM method (could also be MNE or sLORETA)\n\n# Load data\nevoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))\ninverse_operator = read_inverse_operator(fname_inv)\nsrc = inverse_operator['src']\n\n# Compute inverse solution\npick_ori = \"normal\" # Get signed values to see the effect of sign filp\nstc = apply_inverse(evoked, inverse_operator, lambda2, method,\n pick_ori=pick_ori)\n\nlabel = mne.read_label(label_fname)\n\nstc_label = stc.in_label(label)\nmean = stc.extract_label_time_course(label, src, mode='mean')\nmean_flip = stc.extract_label_time_course(label, src, mode='mean_flip')\npca = stc.extract_label_time_course(label, src, mode='pca_flip')\n\nprint(\"Number of vertices : %d\" % len(stc_label.data))\n\n# View source activations\nplt.figure()\nplt.plot(1e3 * stc_label.times, stc_label.data.T, 'k', linewidth=0.5)\nh0, = plt.plot(1e3 * stc_label.times, mean.T, 'r', linewidth=3)\nh1, = plt.plot(1e3 * stc_label.times, mean_flip.T, 'g', linewidth=3)\nh2, = plt.plot(1e3 * stc_label.times, pca.T, 'b', linewidth=3)\nplt.legend([h0, h1, h2], ['mean', 'mean flip', 'PCA flip'])\nplt.xlabel('Time (ms)')\nplt.ylabel('Source amplitude')\nplt.title('Activations in Label : %s' % label)\nplt.show()\n",
"\"\"\"\n======================\nWorking with ECoG data\n======================\n\nMNE supports working with more than just MEG and EEG data. Here we show some\nof the functions that can be used to facilitate working with\nelectrocorticography (ECoG) data.\n\"\"\"\n# Authors: Eric Larson <[email protected]>\n# Chris Holdgraf <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat\nfrom mayavi import mlab\n\nimport mne\nfrom mne.viz import plot_alignment, snapshot_brain_montage\n\nprint(__doc__)\n\n###############################################################################\n# Let's load some ECoG electrode locations and names, and turn them into\n# a :class:`mne.channels.DigMontage` class.\n\nmat = loadmat(mne.datasets.misc.data_path() + '/ecog/sample_ecog.mat')\nch_names = mat['ch_names'].tolist()\nelec = mat['elec']\ndig_ch_pos = dict(zip(ch_names, elec))\nmon = mne.channels.DigMontage(dig_ch_pos=dig_ch_pos)\nprint('Created %s channel positions' % len(ch_names))\n\n###############################################################################\n# Now that we have our electrode positions in MRI coordinates, we can create\n# our measurement info structure.\n\ninfo = mne.create_info(ch_names, 1000., 'ecog', montage=mon)\n\n###############################################################################\n# We can then plot the locations of our electrodes on our subject's brain.\n#\n# .. note:: These are not real electrodes for this subject, so they\n# do not align to the cortical surface perfectly.\n\nsubjects_dir = mne.datasets.sample.data_path() + '/subjects'\nfig = plot_alignment(info, subject='sample', subjects_dir=subjects_dir,\n surfaces=['pial'])\nmlab.view(200, 70)\n\n###############################################################################\n# Sometimes it is useful to make a scatterplot for the current figure view.\n# This is best accomplished with matplotlib. We can capture an image of the\n# current mayavi view, along with the xy position of each electrode, with the\n# `snapshot_brain_montage` function.\n\n# We'll once again plot the surface, then take a snapshot.\nfig = plot_alignment(info, subject='sample', subjects_dir=subjects_dir,\n surfaces='pial')\nmlab.view(200, 70)\nxy, im = snapshot_brain_montage(fig, mon)\n\n# Convert from a dictionary to array to plot\nxy_pts = np.vstack(xy[ch] for ch in info['ch_names'])\n\n# Define an arbitrary \"activity\" pattern for viz\nactivity = np.linspace(100, 200, xy_pts.shape[0])\n\n# This allows us to use matplotlib to create arbitrary 2d scatterplots\n_, ax = plt.subplots(figsize=(10, 10))\nax.imshow(im)\nax.scatter(*xy_pts.T, c=activity, s=200, cmap='coolwarm')\nax.set_axis_off()\nplt.show()\n",
"\"\"\"\n============================\nBrainstorm tutorial datasets\n============================\n\nHere we compute the evoked from raw for the Brainstorm\ntutorial dataset. For comparison, see:\nhttp://neuroimage.usc.edu/brainstorm/Tutorials/MedianNerveCtf\n\nReferences\n----------\n.. [1] Tadel F, Baillet S, Mosher JC, Pantazis D, Leahy RM.\nBrainstorm: A User-Friendly Application for MEG/EEG Analysis.\nComputational Intelligence and Neuroscience, vol. 2011, Article ID 879716,\n13 pages, 2011. doi:10.1155/2011/879716\n\"\"\"\n\n# Authors: Mainak Jas <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport numpy as np\n\nimport mne\nfrom mne.datasets.brainstorm import bst_raw\nfrom mne.io import Raw\n\nprint(__doc__)\n\ntmin, tmax, event_id = -0.1, 0.3, 2 # take right-hand somato\nreject = dict(mag=4e-12, eog=250e-6)\n\ndata_path = bst_raw.data_path()\n\nraw_fname = data_path + '/MEG/bst_raw/' + \\\n 'subj001_somatosensory_20111109_01_AUX-f_raw.fif'\nraw = Raw(raw_fname, preload=True, add_eeg_ref=False)\nraw.plot()\n\n# set EOG channel\nraw.set_channel_types({'EEG058': 'eog'})\nraw.add_eeg_average_proj()\n\n# show power line interference and remove it\nraw.plot_psd()\nraw.notch_filter(np.arange(60, 181, 60))\n\nevents = mne.find_events(raw, stim_channel='UPPT001')\n\n# pick MEG channels\npicks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,\n exclude='bads')\n\n# Compute epochs\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), reject=reject, preload=False)\n\n# compute evoked\nevoked = epochs.average()\n\n# remove physiological artifacts (eyeblinks, heartbeats) using SSP on baseline\nevoked.add_proj(mne.compute_proj_evoked(evoked.crop(tmax=0, copy=True)))\nevoked.apply_proj()\n\n# fix stim artifact\nmne.preprocessing.fix_stim_artifact(evoked)\n\n# correct delays due to hardware (stim artifact is at 4 ms)\nevoked.shift_time(-0.004)\n\n# plot the result\nevoked.plot()\n\n# show topomaps\nevoked.plot_topomap(times=np.array([0.016, 0.030, 0.060, 0.070]))\n",
"\"\"\"\n=======================\nDecoding real-time data\n=======================\n\nSupervised machine learning applied to MEG data in sensor space.\nHere the classifier is updated every 5 trials and the decoding\naccuracy is plotted\n\"\"\"\n# Authors: Mainak Jas <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport mne\nfrom mne.realtime import MockRtClient, RtEpochs\nfrom mne.datasets import sample\n\nprint(__doc__)\n\n# Fiff file to simulate the realtime client\ndata_path = sample.data_path()\nraw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\nraw = mne.io.read_raw_fif(raw_fname, preload=True)\n\ntmin, tmax = -0.2, 0.5\nevent_id = dict(aud_l=1, vis_l=3)\n\ntr_percent = 60 # Training percentage\nmin_trials = 10 # minimum trials after which decoding should start\n\n# select gradiometers\npicks = mne.pick_types(raw.info, meg='grad', eeg=False, eog=True,\n stim=True, exclude=raw.info['bads'])\n\n# create the mock-client object\nrt_client = MockRtClient(raw)\n\n# create the real-time epochs object\nrt_epochs = RtEpochs(rt_client, event_id, tmin, tmax, picks=picks, decim=1,\n reject=dict(grad=4000e-13, eog=150e-6))\n\n# start the acquisition\nrt_epochs.start()\n\n# send raw buffers\nrt_client.send_data(rt_epochs, picks, tmin=0, tmax=90, buffer_size=1000)\n\n# Decoding in sensor space using a linear SVM\nn_times = len(rt_epochs.times)\n\nfrom sklearn import preprocessing # noqa\nfrom sklearn.svm import SVC # noqa\nfrom sklearn.pipeline import Pipeline # noqa\nfrom sklearn.cross_validation import cross_val_score, ShuffleSplit # noqa\nfrom mne.decoding import Vectorizer, FilterEstimator # noqa\n\n\nscores_x, scores, std_scores = [], [], []\n\nfilt = FilterEstimator(rt_epochs.info, 1, 40)\nscaler = preprocessing.StandardScaler()\nvectorizer = Vectorizer()\nclf = SVC(C=1, kernel='linear')\n\nconcat_classifier = Pipeline([('filter', filt), ('vector', vectorizer),\n ('scaler', scaler), ('svm', clf)])\n\ndata_picks = mne.pick_types(rt_epochs.info, meg='grad', eeg=False, eog=True,\n stim=False, exclude=raw.info['bads'])\n\nfor ev_num, ev in enumerate(rt_epochs.iter_evoked()):\n\n print(\"Just got epoch %d\" % (ev_num + 1))\n\n if ev_num == 0:\n X = ev.data[None, data_picks, :]\n y = int(ev.comment) # the comment attribute contains the event_id\n else:\n X = np.concatenate((X, ev.data[None, data_picks, :]), axis=0)\n y = np.append(y, int(ev.comment))\n\n if ev_num >= min_trials:\n\n cv = ShuffleSplit(len(y), 5, test_size=0.2, random_state=42)\n scores_t = cross_val_score(concat_classifier, X, y, cv=cv,\n n_jobs=1) * 100\n\n std_scores.append(scores_t.std())\n scores.append(scores_t.mean())\n scores_x.append(ev_num)\n\n # Plot accuracy\n plt.clf()\n\n plt.plot(scores_x, scores, '+', label=\"Classif. score\")\n plt.hold(True)\n plt.plot(scores_x, scores)\n plt.axhline(50, color='k', linestyle='--', label=\"Chance level\")\n hyp_limits = (np.asarray(scores) - np.asarray(std_scores),\n np.asarray(scores) + np.asarray(std_scores))\n plt.fill_between(scores_x, hyp_limits[0], y2=hyp_limits[1],\n color='b', alpha=0.5)\n plt.xlabel('Trials')\n plt.ylabel('Classification score (% correct)')\n plt.xlim([min_trials, 50])\n plt.ylim([30, 105])\n plt.title('Real-time decoding')\n plt.show(block=False)\n plt.pause(0.01)\nplt.show()\n",
"\"\"\"\n==================================\nSensitivity map of SSP projections\n==================================\n\nThis example shows the sources that have a forward field\nsimilar to the first SSP vector correcting for ECG.\n\"\"\"\n# Author: Alexandre Gramfort <[email protected]>\n#\n# License: BSD (3-clause)\n\nimport matplotlib.pyplot as plt\n\nfrom mne import read_forward_solution, read_proj, sensitivity_map\nfrom mne.datasets import sample\n\nprint(__doc__)\n\ndata_path = sample.data_path()\n\nsubjects_dir = data_path + '/subjects'\nfname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'\necg_fname = data_path + '/MEG/sample/sample_audvis_ecg-proj.fif'\n\nfwd = read_forward_solution(fname, surf_ori=True)\nprojs = read_proj(ecg_fname)\n# take only one projection per channel type\nprojs = projs[::2]\n\n# Compute sensitivity map\nssp_ecg_map = sensitivity_map(fwd, ch_type='grad', projs=projs, mode='angle')\n\n###############################################################################\n# Show sensitivity map\n\nplt.hist(ssp_ecg_map.data.ravel())\nplt.show()\n\nargs = dict(clim=dict(kind='value', lims=(0.2, 0.6, 1.)), smoothing_steps=7,\n hemi='rh', subjects_dir=subjects_dir)\nssp_ecg_map.plot(subject='sample', time_label='ECG SSP sensitivity', **args)\n",
"\"\"\"\n=====================================================================\nCompute Phase Slope Index (PSI) in source space for a visual stimulus\n=====================================================================\n\nThis example demonstrates how the Phase Slope Index (PSI) [1] can be computed\nin source space based on single trial dSPM source estimates. In addition,\nthe example shows advanced usage of the connectivity estimation routines\nby first extracting a label time course for each epoch and then combining\nthe label time course with the single trial source estimates to compute the\nconnectivity.\n\nThe result clearly shows how the activity in the visual label precedes more\nwidespread activity (a postivive PSI means the label time course is leading).\n\nReferences\n----------\n[1] Nolte et al. \"Robustly Estimating the Flow Direction of Information in\nComplex Physical Systems\", Physical Review Letters, vol. 100, no. 23,\npp. 1-4, Jun. 2008.\n\"\"\"\n# Author: Martin Luessi <[email protected]>\n#\n# License: BSD (3-clause)\n\n\nimport numpy as np\n\nimport mne\nfrom mne.datasets import sample\nfrom mne.minimum_norm import read_inverse_operator, apply_inverse_epochs\nfrom mne.connectivity import seed_target_indices, phase_slope_index\n\nprint(__doc__)\n\ndata_path = sample.data_path()\nsubjects_dir = data_path + '/subjects'\nfname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'\nfname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\nfname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'\nfname_label = data_path + '/MEG/sample/labels/Vis-lh.label'\n\nevent_id, tmin, tmax = 4, -0.2, 0.3\nmethod = \"dSPM\" # use dSPM method (could also be MNE or sLORETA)\n\n# Load data\ninverse_operator = read_inverse_operator(fname_inv)\nraw = mne.io.read_raw_fif(fname_raw)\nevents = mne.read_events(fname_event)\n\n# pick MEG channels\npicks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True,\n exclude='bads')\n\n# Read epochs\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks,\n baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13,\n eog=150e-6))\n\n# Compute inverse solution and for each epoch. Note that since we are passing\n# the output to both extract_label_time_course and the phase_slope_index\n# functions, we have to use \"return_generator=False\", since it is only possible\n# to iterate over generators once.\nsnr = 1.0 # use lower SNR for single epochs\nlambda2 = 1.0 / snr ** 2\nstcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method,\n pick_ori=\"normal\", return_generator=False)\n\n# Now, we generate seed time series by averaging the activity in the left\n# visual corex\nlabel = mne.read_label(fname_label)\nsrc = inverse_operator['src'] # the source space used\nseed_ts = mne.extract_label_time_course(stcs, label, src, mode='mean_flip')\n\n# Combine the seed time course with the source estimates. There will be a total\n# of 7500 signals:\n# index 0: time course extracted from label\n# index 1..7499: dSPM source space time courses\ncomb_ts = zip(seed_ts, stcs)\n\n# Construct indices to estimate connectivity between the label time course\n# and all source space time courses\nvertices = [src[i]['vertno'] for i in range(2)]\nn_signals_tot = 1 + len(vertices[0]) + len(vertices[1])\n\nindices = seed_target_indices([0], np.arange(1, n_signals_tot))\n\n# Compute the PSI in the frequency range 8Hz..30Hz. We exclude the baseline\n# period from the connectivity estimation\nfmin = 8.\nfmax = 30.\ntmin_con = 0.\nsfreq = raw.info['sfreq'] # the sampling frequency\n\npsi, freqs, times, n_epochs, _ = phase_slope_index(\n comb_ts, mode='multitaper', indices=indices, sfreq=sfreq,\n fmin=fmin, fmax=fmax, tmin=tmin_con)\n\n# Generate a SourceEstimate with the PSI. This is simple since we used a single\n# seed (inspect the indices variable to see how the PSI scores are arranged in\n# the output)\npsi_stc = mne.SourceEstimate(psi, vertices=vertices, tmin=0, tstep=1,\n subject='sample')\n\n# Now we can visualize the PSI using the plot method. We use a custom colormap\n# to show signed values\nv_max = np.max(np.abs(psi))\nbrain = psi_stc.plot(surface='inflated', hemi='lh',\n time_label='Phase Slope Index (PSI)',\n subjects_dir=subjects_dir,\n clim=dict(kind='percent', pos_lims=(95, 97.5, 100)))\nbrain.show_view('medial')\nbrain.add_label(fname_label, color='green', alpha=0.7)\n",
"\"\"\"\n.. _tut_epochs_objects:\n\nThe :class:`Epochs <mne.Epochs>` data structure: epoched data\n=============================================================\n\"\"\"\n\nfrom __future__ import print_function\n\nimport mne\nimport os.path as op\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n###############################################################################\n# :class:`Epochs <mne.Epochs>` objects are a way of representing continuous\n# data as a collection of time-locked trials, stored in an array of\n# `shape(n_events, n_channels, n_times)`. They are useful for many statistical\n# methods in neuroscience, and make it easy to quickly overview what occurs\n# during a trial.\n#\n# :class:`Epochs <mne.Epochs>` objects can be created in three ways:\n# 1. From a :class:`Raw <mne.io.RawFIF>` object, along with event times\n# 2. From an :class:`Epochs <mne.Epochs>` object that has been saved as a\n# `.fif` file\n# 3. From scratch using :class:`EpochsArray <mne.EpochsArray>`. See\n# :ref:`tut_creating_data_structures`\n\ndata_path = mne.datasets.sample.data_path()\n# Load a dataset that contains events\nraw = mne.io.read_raw_fif(\n op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif'))\n\n# If your raw object has a stim channel, you can construct an event array\n# easily\nevents = mne.find_events(raw, stim_channel='STI 014')\n\n# Show the number of events (number of rows)\nprint('Number of events:', len(events))\n\n# Show all unique event codes (3rd column)\nprint('Unique event codes:', np.unique(events[:, 2]))\n\n# Specify event codes of interest with descriptive labels.\n# This dataset also has visual left (3) and right (4) events, but\n# to save time and memory we'll just look at the auditory conditions\n# for now.\nevent_id = {'Auditory/Left': 1, 'Auditory/Right': 2}\n\n###############################################################################\n# Now, we can create an :class:`mne.Epochs` object with the events we've\n# extracted. Note that epochs constructed in this manner will not have their\n# data available until explicitly read into memory, which you can do with\n# :func:`get_data <mne.Epochs.get_data>`. Alternatively, you can use\n# `preload=True`.\n#\n# Expose the raw data as epochs, cut from -0.1 s to 1.0 s relative to the event\n# onsets\nepochs = mne.Epochs(raw, events, event_id, tmin=-0.1, tmax=1,\n baseline=(None, 0), preload=True)\nprint(epochs)\n\n###############################################################################\n# Epochs behave similarly to :class:`mne.io.Raw` objects. They have an\n# :class:`info <mne.Info>` attribute that has all of the same\n# information, as well as a number of attributes unique to the events contained\n# within the object.\n\nprint(epochs.events[:3])\nprint()\nprint(epochs.event_id)\n\n###############################################################################\n# You can select subsets of epochs by indexing the :class:`Epochs <mne.Epochs>`\n# object directly. Alternatively, if you have epoch names specified in\n# `event_id` then you may index with strings instead.\n\nprint(epochs[1:5])\nprint(epochs['Auditory/Right'])\n\n###############################################################################\n# It is also possible to iterate through :class:`Epochs <mne.Epochs>` objects\n# in this way. Note that behavior is different if you iterate on `Epochs`\n# directly rather than indexing:\n\n# These will be epochs objects\nfor i in range(3):\n print(epochs[i])\n\n# These will be arrays\nfor ep in epochs[:2]:\n print(ep)\n\n###############################################################################\n# You can manually remove epochs from the Epochs object by using\n# :func:`epochs.drop(idx) <mne.Epochs.drop>`, or by using rejection or flat\n# thresholds with :func:`epochs.drop_bad(reject, flat) <mne.Epochs.drop_bad>`.\n# You can also inspect the reason why epochs were dropped by looking at the\n# list stored in ``epochs.drop_log`` or plot them with\n# :func:`epochs.plot_drop_log() <mne.Epochs.plot_drop_log>`. The indices\n# from the original set of events are stored in ``epochs.selection``.\n\nepochs.drop([0], reason='User reason')\nepochs.drop_bad(reject=dict(grad=2500e-13, mag=4e-12, eog=200e-6), flat=None)\nprint(epochs.drop_log)\nepochs.plot_drop_log()\nprint('Selection from original events:\\n%s' % epochs.selection)\nprint('Removed events (from numpy setdiff1d):\\n%s'\n % (np.setdiff1d(np.arange(len(events)), epochs.selection).tolist(),))\nprint('Removed events (from list comprehension -- should match!):\\n%s'\n % ([li for li, log in enumerate(epochs.drop_log) if len(log) > 0]))\n\n###############################################################################\n# If you wish to save the epochs as a file, you can do it with\n# :func:`mne.Epochs.save`. To conform to MNE naming conventions, the\n# epochs file names should end with '-epo.fif'.\nepochs_fname = op.join(data_path, 'MEG', 'sample', 'sample-epo.fif')\nepochs.save(epochs_fname)\n\n###############################################################################\n# Later on you can read the epochs with :func:`mne.read_epochs`. For reading\n# EEGLAB epochs files see :func:`mne.read_epochs_eeglab`. We can also use\n# ``preload=False`` to save memory, loading the epochs from disk on demand.\nepochs = mne.read_epochs(epochs_fname, preload=False)\n\n###############################################################################\n# If you wish to look at the average across trial types, then you may do so,\n# creating an :class:`Evoked <mne.Evoked>` object in the process. Instances\n# of `Evoked` are usually created by calling :func:`mne.Epochs.average`. For\n# creating `Evoked` from other data structures see :class:`mne.EvokedArray` and\n# :ref:`tut_creating_data_structures`.\n\nev_left = epochs['Auditory/Left'].average()\nev_right = epochs['Auditory/Right'].average()\n\nf, axs = plt.subplots(3, 2, figsize=(10, 5))\n_ = f.suptitle('Left / Right auditory', fontsize=20)\n_ = ev_left.plot(axes=axs[:, 0], show=False)\n_ = ev_right.plot(axes=axs[:, 1], show=False)\nplt.tight_layout()\n\n###############################################################################\n# To export and manipulate Epochs using Pandas see :ref:`tut_io_export_pandas`.\n"
] |
[
[
"pandas.concat",
"pandas.read_csv",
"numpy.abs",
"numpy.arange",
"pandas.DataFrame",
"numpy.std",
"numpy.diff",
"numpy.mean"
],
[
"numpy.convolve",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.tight_layout",
"numpy.arange",
"scipy.stats.distributions.t.ppf",
"matplotlib.pyplot.colorbar",
"numpy.log10",
"scipy.stats.distributions.t.sf",
"numpy.random.RandomState",
"numpy.zeros",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
],
[
"numpy.arange",
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots"
],
[
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.axes",
"numpy.log10",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
],
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
],
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.subplots",
"numpy.vstack",
"numpy.linspace"
],
[
"numpy.arange",
"numpy.array"
],
[
"sklearn.cross_validation.cross_val_score",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.title",
"numpy.asarray",
"matplotlib.pyplot.ylim",
"sklearn.pipeline.Pipeline",
"matplotlib.pyplot.hold",
"numpy.concatenate",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.fill_between",
"sklearn.svm.SVC",
"matplotlib.pyplot.xlabel",
"sklearn.preprocessing.StandardScaler",
"matplotlib.pyplot.show",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.ylabel"
],
[
"matplotlib.pyplot.show"
],
[
"numpy.arange",
"numpy.abs"
],
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplots",
"numpy.unique"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jtianesq/protein-prediction-nmt-evo
|
[
"fd08a92625a7feced03bc2b5c01a6545f03e5a88"
] |
[
"Neural Machine Translation/search/beam.py"
] |
[
"# search.py\n\nimport numpy as np\nimport itertools\n\n\n# score: a beam_size * num_vars matrix, represent current score\n# n: max number of elements to select\n# threshold: prune if score < best + threshold\ndef find_nbest(score, n, threshold=None):\n num_vars = score.shape[1]\n # print(score.shape)\n\n score = score.flatten()\n nbest = np.argpartition(score, n)[:n] # get indices of n smallest costs(unordered because of argpartition impl)\n\n # beam_indices = nbest / num_vars\n beam_indices = [int(np.floor(x / num_vars)) for x in nbest]\n word_indices = nbest % num_vars\n nbest_score = score[nbest]\n\n # print(beam_indices, word_indices, nbest_score)\n\n if threshold: # seems incorrect\n best = np.max(nbest_score)\n cond = nbest_score > best + threshold\n nbest_score = nbest_score[cond]\n beam_indices = beam_indices[cond]\n word_indices = word_indices[cond]\n\n return nbest_score, beam_indices, word_indices\n\n\nclass beam:\n\n def __init__(self, beamsize, threshold=None):\n self.size = beamsize\n self.threshold = threshold\n self.scores = []\n self.candidates = []\n\n def prune(self, log_probs, done_predicate, prev_beam):\n # print(\"prev scores:\", prev_beam.scores)\n prev_score = np.array(prev_beam.scores, log_probs.dtype)\n score = prev_score[:, None] - log_probs # nll\n # print(score, prev_score, log_probs)\n\n nbest_score, beam_indices, word_indices= find_nbest(score, self.size, self.threshold)\n\n finished = []\n remained = []\n\n for score, bid, wid in zip(nbest_score,beam_indices,word_indices):\n prev_candidates = prev_beam.candidates\n candidates = prev_candidates[bid] + [wid]\n # candidates = prev_candidates + [wid]\n\n if done_predicate(candidates):\n finished.append([candidates, score])\n else:\n remained.append(bid)\n self.candidates.append(candidates)\n self.scores.append(score)\n\n return finished, remained"
] |
[
[
"numpy.max",
"numpy.array",
"numpy.argpartition",
"numpy.floor"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
yanlinqian/Temporal-Color-Constancy
|
[
"ebd363962fa8ae0908252cabaf97355da3da8a80"
] |
[
"auxiliary/diffihistogram_wrap.py"
] |
[
"import torch\nimport torch.nn as nn\nimport time,datetime\nimport torch.nn.functional as F\nimport numpy as np\n\nclass Histogram2D_wrap(nn.Module):\n def __init__(self, bins=100, min=0, max=1, norm=True, cuda=False):\n super(Histogram2D_wrap, self).__init__()\n self.bins, self.min, self.max, self.norm=bins,min,max,norm\n self.cuda=cuda\n self.delta=float(max-min)/float(bins)\n self.centers=float(min)+self.delta*(torch.arange(bins).float()+0.5)\n self.eps=1e-5\n if self.cuda:\n self.centers=self.centers.cuda()\n def forward(self,x,mask):\n # x: tensor(n,h*w,2)\n # mask: tensor(n,h*w) where 1 indicates the pixel should be masked, e.g. those on color checker\n\n x=x-self.min\n x=torch.remainder(x,self.max-self.min)#modular operation\n x=x+self.min\n u, v=x[:,:,0], x[:,:,1]\n\n\n #making hist using matrix.\n #speed: for a 240*320 uv image, it takes 0.081s on a 1050ti gpu\n a,b=torch.meshgrid([self.centers, self.centers])\n c =torch.stack((a.flatten(), b.flatten()))\n c =c.permute(1,0)#(1024,2)\n x_sparse=x.unsqueeze(2)#([1, 76800, 1, 2])\n c_sparse=c.unsqueeze(0).unsqueeze(0)#([1, 1, 1024, 2])\n x_sparse=x_sparse.expand(-1,-1,self.bins*self.bins,-1)# ([1, 76800, 1024, 2])\n x_sparse=x_sparse.cuda()\n c_sparse=c_sparse.cuda()\n\n dist=0.5*(torch.abs(x_sparse-c_sparse).sum(3)) # ([1, 76800, 1024])\n ct =torch.relu(self.delta-dist)# ([1, 76800, 1024])\n ct[torch.isinf(u) | torch.isinf(v) | torch.isnan(u) | torch.isnan(v)]=0\n if mask:\n ct[mask!=0]=0\n ct =ct.sum(1)\n counts=ct.view(x.shape[0],self.bins, self.bins)\n\n\n #making hist using 2 loops, this is pretty slow, for a 240*320 uv image, it takes 0.92s on a 1050ti gpu\n # counts=torch.zeros(x.shape[0],self.bins, self.bins)\n # if self.cuda:\n # counts=counts.cuda()\n # for i,center1 in enumerate(self.centers):\n # for j,center2 in enumerate(self.centers):\n # dist=torch.abs(u-center1)+torch.abs(v-center2)\n # dist=0.5*dist\n # ct =torch.relu(self.delta-dist)\n # ct[torch.isinf(u)]=0\n # ct[torch.isinf(v)]=0\n # ct[torch.isnan(u)]=0\n # ct[torch.isnan(v)]=0\n # ct[mask != 0]=0\n # ct =ct.sum(1)\n # counts[:,i,j]=ct\n\n\n if self.norm:\n summ=counts.sum(dim=(1,2))+self.eps\n summ=torch.unsqueeze(summ,1)\n summ=torch.unsqueeze(summ,1)\n return counts/summ\n return counts\n\n#not implemented:\n#class Histogram1D_wrap\n\nif __name__=='__main__':\n print('demo diffihistogram_wrap')\n nbatch=2\n h,w=64,64\n data = 255*torch.rand(nbatch*h*w*2).view(nbatch,h,w,2).cuda()\n #data[:,100:120,100:120,:]=np.log(0/(0+1e-6))\n data=data.view(nbatch,-1,2)\n mask= (data.sum(2)<=1e-4).float()\n #data = torch.relu(data)\n data.requires_grad=True\n\n start_time=time.time()\n nrun=10\n hist2d=Histogram2D_wrap(bins=32,min=0,max=64, norm=True,cuda=True)\n for i in range(nrun):\n out =hist2d.forward(data,mask)\n torch.cuda.synchronize()\n end_time=time.time()-start_time\n print('run time', end_time/nrun)\n\n print(hist2d.centers, out.shape)\n\n from showhistogram import *\n x =hist2d.centers.cpu().numpy()\n y =x\n z =out[0,:,:].cpu().detach().numpy()\n show_histogram_2d(x,y,z)\n"
] |
[
[
"torch.abs",
"torch.cuda.synchronize",
"torch.isinf",
"torch.isnan",
"torch.remainder",
"torch.unsqueeze",
"torch.relu",
"torch.rand",
"torch.arange",
"torch.meshgrid"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
sumanthd17/text-to-text-transfer-transformer
|
[
"df22dc95426f6a8af65edca8a5495eaed00e19bc"
] |
[
"t5/evaluation/metrics.py"
] |
[
"# Copyright 2021 The T5 Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Functions for computing metrics.\n\nEvery function must accept a list of targets and a list of predictions and\nreturn a dict of metrics.\n\nFunctions should assume all text inputs are unicode strings.\n\"\"\"\n\nimport collections\nimport itertools\nimport re\nimport string\nfrom typing import Dict, Mapping, Optional, Sequence, Tuple, Union\n\nfrom absl import logging\nimport numpy as np\nimport sacrebleu\nimport scipy.stats\nimport sklearn.metrics\nfrom t5.evaluation import qa_utils\n\nfrom rouge_score import rouge_scorer\nfrom rouge_score import scoring\n\n\ndef bleu(targets, predictions):\n \"\"\"Computes BLEU score.\n\n Args:\n targets: list of strings or list of list of strings if multiple references\n are present.\n predictions: list of strings\n\n Returns:\n bleu_score across all targets and predictions\n \"\"\"\n print(f'Type of targets: {type(targets)}')\n print(f'Type of predictions: {type(predictions)}')\n print(predictions[0])\n print(targets[0])\n # targets = targets.tolist()\n # predictions = predictions.tolist()\n # if isinstance(targets[0], list):\n # targets = [[x for x in target] for target in targets]\n # print('going into if condiction')\n # else:\n # # Need to wrap targets in another list for corpus_bleu.\n # targets = [targets]\n\n bleu_score = sacrebleu.corpus_bleu(predictions, [targets],\n smooth_method=\"exp\",\n smooth_value=0.0,\n force=False,\n lowercase=False,\n tokenize=\"13a\",\n use_effective_order=False)\n return {\"bleu\": bleu_score.score}\n\n\ndef rouge(targets, predictions, score_keys=None):\n \"\"\"Computes rouge score.\n\n Args:\n targets: list of strings\n predictions: list of strings\n score_keys: list of strings with the keys to compute.\n Returns:\n dict with score_key: rouge score across all targets and predictions\n \"\"\"\n\n if score_keys is None:\n score_keys = [\"rouge1\", \"rouge2\", \"rougeLsum\"]\n scorer = rouge_scorer.RougeScorer(score_keys)\n aggregator = scoring.BootstrapAggregator()\n\n def _prepare_summary(summary):\n # Make sure the summary is not bytes-type\n # Add newlines between sentences so that rougeLsum is computed correctly.\n summary = summary.replace(\" . \", \" .\\n\")\n return summary\n\n for prediction, target in zip(predictions, targets):\n target = _prepare_summary(target)\n prediction = _prepare_summary(prediction)\n aggregator.add_scores(scorer.score(target=target, prediction=prediction))\n result = aggregator.aggregate()\n for key in score_keys:\n logging.info(\n \"%s = %.2f, 95%% confidence [%.2f, %.2f]\",\n key,\n result[key].mid.fmeasure*100,\n result[key].low.fmeasure*100,\n result[key].high.fmeasure*100,\n )\n return {key: result[key].mid.fmeasure*100 for key in score_keys}\n\n\ndef span_squad(targets, predictions):\n \"\"\"Computes SQuAD metrics for span prediction tasks.\n\n Uses qa metric function to compute EM and F1 score.\n\n Args:\n targets: list of dict of answers (list of strings) and context (string)\n predictions: list of strings, each string is contains the space tokenized\n ids in the format: \"start: 3 end: 6\"\n\n Returns:\n dict with score_key: squad score across all targets and predictions\n \"\"\"\n assert len(targets) == len(predictions)\n\n def space_tok(s):\n return re.sub(r\"\\W\", \" \", s).split()\n\n def get_answer_text_from_context(context, answer_tokens):\n \"\"\"Find the answer in the context given the answer tokens.\"\"\"\n # In the initial training iterations, the model can output garbage.\n # Returning an empty string in such cases.\n if len(answer_tokens) < 4:\n return \"\"\n\n # Model sometimes predicts words instead of numbers in the answer. Return\n # an empty string in that case.\n try:\n start_index = int(answer_tokens[1])\n end_index = int(answer_tokens[3])\n except ValueError:\n return \"\"\n\n return \" \".join(context[start_index:end_index+1])\n\n contexts = [space_tok(t[\"context\"]) for t in targets]\n answers = [t[\"answers\"] for t in targets]\n\n predictions = [space_tok(p) for p in predictions]\n final_predictions = [\n get_answer_text_from_context(c, p) for c, p in zip(contexts, predictions)\n ]\n\n return squad(answers, final_predictions)\n\n\ndef squad(targets, predictions):\n \"\"\"Computes SQuAD metrics, maximizing over answers per question.\n\n Args:\n targets: list of lists of strings\n predictions: list of strings\n\n Returns:\n dict with score_key: squad score across all targets and predictions\n \"\"\"\n targets = [[qa_utils.normalize_squad(t) for t in u] for u in targets]\n predictions = [qa_utils.normalize_squad(p) for p in predictions]\n return qa_utils.qa_metrics(targets, predictions)\n\n\ndef trivia_qa(targets, predictions):\n \"\"\"Computes TriviaQA metrics, maximizing over answers per question.\n\n Args:\n targets: list of lists of strings\n predictions: list of strings\n\n Returns:\n dict with score_key: squad score across all targets and predictions\n \"\"\"\n targets = [[qa_utils.normalize_trivia_qa(t) for t in u] for u in targets]\n predictions = [qa_utils.normalize_trivia_qa(p) for p in predictions]\n return qa_utils.qa_metrics(targets, predictions)\n\n\ndef accuracy(targets, predictions):\n return {\"accuracy\": 100*sklearn.metrics.accuracy_score(targets, predictions)}\n\n\ndef sequence_accuracy(targets, predictions):\n \"\"\"Computes per-sequence accuracy.\n\n For each example, returns 1.0 if the target sequence EXACTLY matches the\n predicted sequence. Else, 0.0.\n\n Args:\n targets: list of strings\n predictions: list of strings\n Returns:\n float. Average sequence-level accuracy.\n \"\"\"\n assert len(targets) == len(predictions)\n seq_acc = 100 * np.mean([p == t for p, t in zip(predictions, targets)])\n logging.info(\"sequence_accuracy = %.2f\", seq_acc)\n return {\"sequence_accuracy\": seq_acc}\n\n\ndef pearson_corrcoef(targets, predictions):\n \"\"\"Pearson correlation coefficient.\"\"\"\n return {\"pearson_corrcoef\":\n 100 * scipy.stats.pearsonr(targets, predictions)[0]}\n\n\ndef spearman_corrcoef(targets, predictions):\n \"\"\"Spearman correlation coefficient.\"\"\"\n return {\"spearman_corrcoef\":\n 100 * scipy.stats.spearmanr(targets, predictions)[0]}\n\n\ndef mean_multiclass_f1(num_classes, **metric_fn_kwargs):\n \"\"\"Computes the unweighted average of the F1 per class.\"\"\"\n return sklearn_metrics_wrapper(\n \"fbeta_score\",\n metric_dict_str=\"mean_%dclass_f1\" % num_classes,\n metric_post_process_fn=lambda x: 100 * x,\n beta=1,\n labels=range(num_classes),\n average=\"macro\",\n **metric_fn_kwargs)\n\n\ndef exact_match(targets, predictions):\n \"\"\"Computes whether the targets match predictions exactly.\"\"\"\n return {\"exact_match\": 100 * float(np.array_equal(targets, predictions))}\n\n\ndef f1_score_with_invalid(targets, predictions):\n \"\"\"Compute F1 score, but any prediction != 0 or 1 is counted as incorrect.\n\n Args:\n targets: np.ndarray of targets, either 0 or 1\n predictions: np.ndarray of predictions, any integer value\n Returns:\n F1 score, where any prediction != 0 or 1 is counted as wrong.\n \"\"\"\n targets, predictions = np.asarray(targets), np.asarray(predictions)\n # Get indices of invalid predictions\n invalid_idx_mask = np.logical_and(predictions != 0, predictions != 1)\n # For any prediction != 0 or 1, set it to the opposite of what the target is\n predictions[invalid_idx_mask] = 1 - targets[invalid_idx_mask]\n return {\"f1\": 100 * sklearn.metrics.f1_score(targets, predictions)}\n\n\ndef mean_group_metric(metric_fn, group_key=\"group\", value_key=\"value\"):\n \"\"\"Returns a metric that averages `metric_fn` on sub-groups of results.\n\n The sub-groups are defined by aggregating results (targets and predictions)\n by accessing the feature specified by `group_key` in the target dicts.\n\n **WARNING**: Using this function can produce unreliable results if you do not\n pass in full groups. For example, if you evaluate over a random subsample of a\n validation set and do not retain all of the examples in each group, you may\n get results which aren't directly comparable to using the full validation set.\n\n Args:\n metric_fn: function, the metric to compute on the subgroups.\n group_key: string, the key for the grouping value in the target dictionary.\n value_key: string, the key for the value in the dictionaries.\n \"\"\"\n def my_metric(targets, predictions):\n \"\"\"Computes mean of `metric_fn` over subgroups of results.\"\"\"\n grouped_values = collections.defaultdict(lambda: ([], []))\n for targ, pred in zip(targets, predictions):\n g = targ[group_key]\n grouped_values[g][0].append(targ[value_key])\n grouped_values[g][1].append(pred[value_key])\n group_scores = collections.defaultdict(list)\n for (targets, predictions) in grouped_values.values():\n for metric, score in metric_fn(targets, predictions).items():\n group_scores[metric].append(score)\n return {metric: np.mean(scores) for metric, scores in group_scores.items()}\n return my_metric\n\n\ndef multirc_f1_over_all_answers(targets, predictions):\n \"\"\"Special metric for MultiRC which computes F1 score over all examples.\n\n This is necessary because the targets/predictions for MultiRC are dicts and\n the f1_score_with_invalid expects a list of True/False labels, not dicts. As\n a result we just need to key in the \"value\" for each of the example dicts\n before feeding into f1_score_with_invalid.\n\n Args:\n targets: list of dicts, where each dict has a \"value\" key.\n predictions: list of dicts, where each dict has a \"value\" key.\n Returns:\n F1 score over values, where any prediction != 0 or 1 is counted as wrong.\n \"\"\"\n return f1_score_with_invalid(\n [t[\"value\"] for t in targets], [p[\"value\"] for p in predictions]\n )\n\n\ndef auc(targets, predictions, targets_threshold=None):\n \"\"\"Compute Area Under the ROC and PR curves.\n\n ROC - Receiver Operating Characteristic\n PR - Precision and Recall\n\n Args:\n targets: np.ndarray of targets, either 0 or 1, or continuous values.\n predictions: np.ndarray of predictions, any value.\n targets_threshold: float, if target values are continuous values, this\n threshold binarizes them.\n Returns:\n A dictionary with AUC-ROC and AUC-PR scores.\n \"\"\"\n\n if targets_threshold is not None:\n targets = np.array(targets)\n targets = np.where(targets < targets_threshold,\n np.zeros_like(targets, dtype=np.int32),\n np.ones_like(targets, dtype=np.int32))\n\n return {\n \"auc-roc\": sklearn.metrics.roc_auc_score(targets, predictions),\n \"auc-pr\": sklearn.metrics.average_precision_score(targets, predictions),\n }\n\n\ndef sklearn_metrics_wrapper(metric_str,\n metric_dict_str=None,\n metric_post_process_fn=None,\n **metric_fn_kwargs):\n \"\"\"Wraps any sklearn.metric function and returns a t5 metric function.\n\n Args:\n metric_str: string, the function from `sklearn.metrics` to use.\n metric_dict_str: optional string, if not specified `metric_str` is used as\n the key in the returned dictionary.\n metric_post_process_fn: callable, if specified the final computed metric\n will be passed through this.\n **metric_fn_kwargs: kwargs, passed to the metric function we are calling.\n Returns:\n the function that calculates the metric in a dict.\n \"\"\"\n if not hasattr(sklearn.metrics, metric_str):\n raise ValueError(\"sklearn.metrics does not have: %s\" % metric_str)\n\n def fn(targets, predictions):\n metric_fn = getattr(sklearn.metrics, metric_str)\n metric_val = metric_fn(targets, predictions, **metric_fn_kwargs)\n if metric_post_process_fn is not None:\n metric_val = metric_post_process_fn(metric_val)\n return {metric_dict_str or metric_str: metric_val}\n return fn\n\n\ndef rank_classification(\n targets: Sequence[Tuple[Sequence[int], bool, float]],\n scores: Sequence[float],\n num_classes: Optional[int] = None) -> Dict[str, Union[float, int]]:\n \"\"\"Computes standard metrics classification based on log likelihood ranking.\n\n This metric is intended to be used along with the `rank_classification`\n preprocessor and postprocessor. Each example is scored (by log likelihood)\n for every possible label, and the label with the best score is selected as the\n prediction.\n\n In the case of multiple labels, a prediction matching any will be considered\n correct.\n\n Args:\n targets: list of tuples, the 'idx', 'is_correct' and 'weight' fields from\n ground truth examples.\n scores: list of float, a flat list of log likelihood scores for each\n possible label for each example.\n num_classes: int or None, the number of possible classes for the label or\n None if the number of classes vary.\n\n Returns:\n Accuracy, f1, and AUC scores.\n\n Raises:\n ValueError: if `targets` is not a sequence of 3-tuples.\n \"\"\"\n assert len(targets) == len(scores)\n if len(targets[0]) != 3:\n raise ValueError(\n f\"`targets` should contain 3 elements but has {len(targets[0])}.\")\n\n idx_0 = targets[0][0]\n if not hasattr(idx_0, \"__len__\") or len(idx_0) != 2:\n raise ValueError(\n \"The first element of `targets` ('idx') should be 2-dimensional. \"\n f\"Got {idx_0}.\")\n\n # Sort by 'idx' since the function relies on this assumption.\n # ((idx, is_correct, weight), score)\n get_idx = lambda x: x[0][0]\n targets, scores = zip(*sorted(zip(targets, scores), key=get_idx))\n\n if not num_classes:\n # Assuming variable classes. Can only compute accuracy.\n num_correct = 0\n total = 0\n\n # (((input idx, output idx), is_correct, weight), score)\n get_grp = lambda x: x[0][0][0]\n\n for _, grp in itertools.groupby(zip(targets, scores), get_grp):\n exs, log_likelihoods = zip(*grp)\n prediction = np.argmax(log_likelihoods)\n weights = exs[prediction][2]\n num_correct += exs[prediction][1] * weights\n total += weights\n return {\n \"accuracy\": 100 * num_correct / total\n }\n\n assert len(targets) % num_classes == 0\n\n labels_indicator = np.array([is_correct for _, is_correct, _ in targets\n ]).reshape((-1, num_classes))\n weights = np.array([weight for _, _, weight in targets]).reshape(\n (-1, num_classes))[:, 0]\n log_likelihoods = np.array(scores, np.float32).reshape((-1, num_classes))\n predictions = log_likelihoods.argmax(-1)\n\n if np.any(labels_indicator.sum(axis=-1) > 1):\n # multiple-answer case\n logging.info(\n \"Multiple labels detected. Predictions matching any label will be \"\n \"considered correct.\")\n num_examples = len(labels_indicator)\n return {\n \"accuracy\": (100 * np.average(\n labels_indicator[np.arange(num_examples), predictions],\n weights=weights))\n }\n\n predictions_indicator = np.eye(num_classes)[predictions]\n\n def exp_normalize(x):\n b = x.max(-1)[:, np.newaxis]\n y = np.exp(x - b)\n return y / y.sum(-1)[:, np.newaxis]\n probs = exp_normalize(log_likelihoods)\n\n if num_classes > 2:\n metrics = mean_multiclass_f1(\n num_classes, sample_weight=weights)(labels_indicator,\n predictions_indicator)\n else:\n metrics = {\n \"f1\":\n 100 * sklearn.metrics.f1_score(\n labels_indicator.argmax(-1), predictions, sample_weight=weights)\n }\n metrics.update({\n \"auc-roc\":\n 100 * sklearn.metrics.roc_auc_score(\n labels_indicator, probs, multi_class=\"ovr\",\n sample_weight=weights),\n \"auc-pr\":\n 100 * sklearn.metrics.average_precision_score(\n labels_indicator, probs, sample_weight=weights),\n \"accuracy\":\n 100 * sklearn.metrics.accuracy_score(\n labels_indicator, predictions_indicator, sample_weight=weights),\n })\n return metrics\n\n\ndef _coqa_tokenize(inp: str) -> Sequence[str]:\n \"\"\"Normalize English text and tokenize into words based on spaces.\n\n Adapted from official evaluation tokenization at\n https://stanfordnlp.github.io/coqa/.\n\n Args:\n inp: string.\n\n Returns:\n Tokenization of normalized text as List[str]\n \"\"\"\n\n def remove_articles(text):\n regex = re.compile(r\"\\b(a|an|the)\\b\", re.UNICODE)\n return re.sub(regex, \" \", text)\n\n def normalize_whitespace(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n return normalize_whitespace(remove_articles(remove_punc(inp.lower()))).split()\n\n\ndef _sequence_f1(target_tokens: Sequence[str],\n prediction_tokens: Sequence[str]) -> float:\n \"\"\"Given target and prediction tokens, return token-wise F1 score.\"\"\"\n\n if not (target_tokens or prediction_tokens):\n return int(target_tokens == prediction_tokens)\n\n common_token_counts = (\n collections.Counter(target_tokens) &\n collections.Counter(prediction_tokens))\n sum_common = sum(common_token_counts.values())\n if sum_common == 0:\n return 0\n\n precision = 1.0 * sum_common / len(prediction_tokens)\n recall = 1.0 * sum_common / len(target_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1\n\n\ndef coqa_f1(\n targets: Sequence[Sequence[str]], predictions: Sequence[str]\n) -> Mapping[str, float]:\n \"\"\"Return mean sequence F1 score over all QA turns.\"\"\"\n f1s = []\n for (t, p) in zip(targets, predictions):\n assert len(t) == 1\n target_tokens = _coqa_tokenize(t[0])\n prediction_tokens = _coqa_tokenize(p)\n f1s.append(_sequence_f1(target_tokens, prediction_tokens))\n return {\"f1\": np.mean(np.array(f1s))}\n"
] |
[
[
"numpy.ones_like",
"numpy.logical_and",
"numpy.array_equal",
"numpy.asarray",
"numpy.arange",
"numpy.eye",
"numpy.argmax",
"numpy.mean",
"numpy.zeros_like",
"numpy.exp",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gmhaber/gnn_laminar_flow
|
[
"13070d046c30e30ce7820f93a373b903a1a0b6dd"
] |
[
"network_utils.py"
] |
[
"import tensorflow as tf\n\n\ndef update_symmetry_edge_features(node_features, edges, edge_features, message_fn):\n\n \"\"\"\n Pass messages between nodes and sum the incoming messages at each node.\n Implements equation 1 and 2 in the paper, i.e. m_{.j}^t &= \\\\sum_{i \\\\in N(j)} f(h_i^{t-1}, h_j^{t-1})\n : nodes_features: (n_nodes, n_features) tensor of node hidden states.\n : edges : (n_edges, 2) tensor of indices (i, j) indicating an edge from nodes[i] to nodes[j].\n : edge_features : features for each edge. Set to zero if the edges don't have features.\n : message_fn : message function, or convolution filter, takes input (n_edges, 2*n_features+n_output) and returns\n output (n_edges, n_output)\n : return : (n_nodes, n_output) Sum of messages arriving at each node.\n \"\"\"\n n_nodes = tf.shape(node_features)[0]\n n_features = tf.shape(node_features)[1]\n\n reshaped = tf.reshape(tf.gather(node_features, edges), (-1, 2 * n_features))\n symmetric = tf.math.multiply(0.5, tf.math.add(reshaped[:, 0:n_features], reshaped[:, n_features:2*n_features]))\n asymmetric = tf.math.multiply(0.5, tf.math.abs(tf.math.subtract(reshaped[:, 0:n_features],\n reshaped[:, n_features:2*n_features])))\n messages = message_fn(tf.concat([symmetric, asymmetric, edge_features], axis=1)) # n_edges, n_output\n\n updates = tf.math.add(tf.math.unsorted_segment_sum(messages, edges[:, 0], n_nodes), tf.math.unsorted_segment_sum(\n messages, edges[:, 1], n_nodes)) # aggregate the edge messages around every node\n\n return messages, updates\n\n\ndef update_node_features(node_features, grad_P1, message_fn):\n \"\"\"\n Pass messages from edges to the nodes\n : node_features: (n_nodes, n_features) tensor of node hidden states.\n : edge_features: 1st-order gradient (n_nodes, 2, n_features)\n : message_fn : message function, takes input (n_nodes, n_features+n_output)\n and returns output (n_nodes, n_features)\n \"\"\"\n message_input = tf.keras.layers.concatenate([node_features, grad_P1], axis=1)\n updated = message_fn(message_input)\n\n return updated\n\n\nclass EdgeSmoothing(tf.keras.layers.Layer):\n def __init__(self):\n super(EdgeSmoothing, self).__init__()\n \n def call(self, to_concat, node_features, edges, count):\n n_nodes = tf.shape(node_features)[0]\n flow_on_edge = tf.math.reduce_mean(tf.gather(node_features, edges), 1) # n_edges, n_features\n aggre_flow = tf.math.add(tf.math.unsorted_segment_sum(flow_on_edge[:, :], edges[:, 0], n_nodes),\n tf.math.unsorted_segment_sum(flow_on_edge[:, :], edges[:, 1], n_nodes))\n\n return tf.keras.layers.concatenate([to_concat, tf.math.divide(aggre_flow, count)], axis=1)\n\n\nclass MLP(tf.keras.layers.Layer):\n \"\"\"\n Message passing function used for graph convolution layer. It is used both for edge convolution and node convolution\n The implemented MLP has one single hidden layer with ReLu activation. The output layer is a linear layer.\n : hidden_nodes : number of neurons in the hidden layer.\n : output_dim : dimension of the output\n : initializer : method to initialize the trainable weights and bias. When MLP is embedded in a graph\n convolution layer, it inherits the layer's initializer\n \"\"\"\n \n def __init__(self, hidden_nodes, output_dim, initializer):\n\n super(MLP, self).__init__()\n self.hidden_nodes = hidden_nodes\n self.output_dim = output_dim\n self.initializer = initializer\n\n def build(self, input_shape):\n\n self.weights_1 = self.add_weight(name='hid_layer', shape=(input_shape[-1]+1, self.hidden_nodes),\n initializer=self.initializer, trainable=True)\n self.weights_2 = self.add_weight(name='out_layer', shape=(self.hidden_nodes+1, self.output_dim),\n initializer=self.initializer, trainable=True)\n\n def call(self, inputs):\n \n x = tf.math.add(tf.linalg.matmul(inputs, self.weights_1[:-1, :]), self.weights_1[-1, :])\n hidden_values = tf.math.multiply(x, tf.nn.sigmoid(x))\n \n y = tf.math.add(tf.linalg.matmul(hidden_values, self.weights_2[:-1, :]), self.weights_2[-1, :])\n out_layer = tf.math.multiply(y, tf.nn.sigmoid(y))\n \n return out_layer\n\n\nclass InvariantEdgeConv(tf.keras.layers.Layer):\n \"\"\"\n Graph convolution adapted from the implementation in GraphNets@DeepMind ( https://arxiv.org/abs/1806.01261 ).\n Node features on the two nodes of an edge, along with the old features on this edge, are used to update\n the edge features.\n Updated edges features around a nodes are summed, along with the old features on this node, are used to update\n the node features\n :\n \"\"\"\n\n def __init__(self, edge_feature_dim, num_filters, initializer):\n\n super(InvariantEdgeConv, self).__init__()\n\n self.edge_feat_dim = edge_feature_dim\n self.num_filters = num_filters\n self.initializer = initializer\n self.message_fn_edge = MLP(128, self.edge_feat_dim, self.initializer)\n self.message_fn_node = MLP(128, self.num_filters, self.initializer)\n\n def call(self, node_features, edge_features, edges):\n\n updated_edge_features, contribution_edges = update_symmetry_edge_features(node_features, edges,\n edge_features,\n self.message_fn_edge)\n updated_node_features = update_node_features(node_features, contribution_edges,\n self.message_fn_node)\n\n return updated_node_features, updated_edge_features\n\n\nclass InvariantEdgeModel(tf.keras.Model):\n def __init__(self, edge_feature_dims, num_filters, initializer):\n super(InvariantEdgeModel, self).__init__()\n\n self.edge_feat_dims = edge_feature_dims\n self.num_filters = num_filters\n self.initializer = initializer\n\n self.layer0 = InvariantEdgeConv(self.edge_feat_dims[0], self.num_filters[0], self.initializer)\n self.layer00 = EdgeSmoothing()\n \n self.layer1 = InvariantEdgeConv(self.edge_feat_dims[1], self.num_filters[1], self.initializer)\n self.layer11 = EdgeSmoothing()\n \n self.layer2 = InvariantEdgeConv(self.edge_feat_dims[2], self.num_filters[2], self.initializer)\n self.layer22 = EdgeSmoothing()\n \n self.layer3 = InvariantEdgeConv(self.edge_feat_dims[3], self.num_filters[3], self.initializer)\n self.layer33 = EdgeSmoothing()\n \n self.layer4 = InvariantEdgeConv(self.edge_feat_dims[4], self.num_filters[4], self.initializer)\n self.layer44 = EdgeSmoothing()\n \n self.layer5 = InvariantEdgeConv(self.edge_feat_dims[5], self.num_filters[5], self.initializer)\n self.layer55 = EdgeSmoothing()\n \n self.layer6 = InvariantEdgeConv(self.edge_feat_dims[6], self.num_filters[6], self.initializer)\n self.layer66 = EdgeSmoothing()\n \n self.layer7 = InvariantEdgeConv(self.edge_feat_dims[7], self.num_filters[7], self.initializer)\n self.layer77 = EdgeSmoothing()\n \n self.layer8 = tf.keras.layers.Dense(3, activation=None, kernel_initializer=self.initializer)\n \n def call(self, node_input, edges, edge_input, smoothing_weights):\n\n # graph convolution\n new_node_features_0, new_edge_features_0 = self.layer0(node_input, edge_input, edges)\n\n # smoothing plus concatenation\n smoothed_0 = self.layer00(node_input[:, 0:2], new_node_features_0, edges, smoothing_weights)\n\n new_node_features_1, new_edge_features_1 = self.layer1(smoothed_0, new_edge_features_0, edges)\n smoothed_1 = self.layer11(node_input[:, 0:2], new_node_features_1, edges, smoothing_weights)\n\n new_node_features_2, new_edge_features_2 = self.layer2(smoothed_1, new_edge_features_1, edges)\n smoothed_2 = self.layer22(node_input[:, 0:2], new_node_features_2, edges, smoothing_weights)\n\n new_node_features_3, new_edge_features_3 = self.layer3(smoothed_2, new_edge_features_2, edges)\n smoothed_3 = self.layer33(node_input[:, 0:2], new_node_features_3, edges, smoothing_weights)\n\n new_node_features_4, new_edge_features_4 = self.layer4(smoothed_3, new_edge_features_3, edges)\n smoothed_4 = self.layer44(node_input[:, 0:2], new_node_features_4, edges, smoothing_weights)\n\n new_node_features_5, new_edge_features_5 = self.layer5(smoothed_4, new_edge_features_4, edges)\n smoothed_5 = self.layer55(node_input[:, 0:2], new_node_features_5, edges, smoothing_weights)\n\n new_node_features_6, new_edge_features_6 = self.layer6(smoothed_5, new_edge_features_5, edges)\n smoothed_6 = self.layer66(node_input[:, 0:2], new_node_features_6, edges, smoothing_weights)\n\n new_node_features_7, new_edge_features_7 = self.layer7(smoothed_6, new_edge_features_6, edges)\n smoothed_7 = self.layer77(node_input[:, 0:2], new_node_features_7, edges, smoothing_weights)\n\n # output dense layer, without nonlinear activation\n node_outputs = self.layer8(smoothed_7[:, 0:])\n\n return node_outputs\n"
] |
[
[
"tensorflow.math.subtract",
"tensorflow.math.add",
"tensorflow.concat",
"tensorflow.nn.sigmoid",
"tensorflow.shape",
"tensorflow.math.unsorted_segment_sum",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.concatenate",
"tensorflow.linalg.matmul",
"tensorflow.gather",
"tensorflow.math.divide"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
midiya/food-detection
|
[
"c88cb89dc4a4fd1bd0677ef2017b6793a7289faf",
"c88cb89dc4a4fd1bd0677ef2017b6793a7289faf"
] |
[
"app.py",
"model/utils/utils.py"
] |
[
"import os\nimport argparse\nimport requests\nimport cv2\nimport numpy as np\nimport tldextract\nimport pytube\nimport hashlib\nimport tldextract\nimport pytube\nimport time\nimport base64\n\nfrom PIL import Image\nfrom flask import Flask, request, render_template, redirect, make_response, jsonify\nfrom pathlib import Path\nfrom werkzeug.utils import secure_filename\nfrom modules import get_prediction, get_video_prediction\nfrom flask_ngrok import run_with_ngrok\nfrom flask_cors import CORS, cross_origin\nfrom werkzeug.utils import secure_filename\n\nparser = argparse.ArgumentParser('YOLOv5 Online Food Recognition')\nparser.add_argument('--ngrok', action='store_true',\n default=False, help=\"Run on local or ngrok\")\nparser.add_argument('--host', type=str,\n default='localhost:8000', help=\"Local IP\")\nparser.add_argument('--debug', action='store_true',\n default=False, help=\"Run app in debug mode\")\n\nASSETS_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\napp = Flask(__name__, template_folder='templates', static_folder='static')\nCORS(app, resources={r\"/api/*\": {\"origins\": \"*\"}})\n\napp.config['SEND_FILE_MAX_AGE_DEFAULT'] = 1\n\n\nUPLOAD_FOLDER = './static/assets/uploads'\nCSV_FOLDER = './static/csv'\nVIDEO_FOLDER = './static/assets/videos'\nDETECTION_FOLDER = './static/assets/detections'\nMETADATA_FOLDER = './static/metadata'\n\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\napp.config['CSV_FOLDER'] = CSV_FOLDER\napp.config['DETECTION_FOLDER'] = DETECTION_FOLDER\napp.config['VIDEO_FOLDER'] = VIDEO_FOLDER\n\nIMAGE_ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}\nVIDEO_ALLOWED_EXTENSIONS = {'mp4', 'avi', '3gpp', '3gp'}\n\n\ndef allowed_file_image(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in IMAGE_ALLOWED_EXTENSIONS\n\n\ndef allowed_file_video(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in VIDEO_ALLOWED_EXTENSIONS\n\n\ndef make_dir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef file_type(path):\n filename = path.split('/')[-1]\n if allowed_file_image(filename):\n filetype = 'image'\n elif allowed_file_video(filename):\n filetype = 'video'\n else:\n filetype = 'invalid'\n return filetype\n\n\ndef download_yt(url):\n \"\"\"\n Download youtube video by url and save to video folder\n \"\"\"\n youtube = pytube.YouTube(url)\n video = youtube.streams.get_highest_resolution()\n path = video.download(app.config['VIDEO_FOLDER'])\n\n return path\n\n\ndef hash_video(video_path):\n \"\"\"\n Hash a frame in video and use as a filename\n \"\"\"\n _, ext = os.path.splitext(video_path)\n stream = cv2.VideoCapture(video_path)\n success, ori_frame = stream.read()\n stream.release()\n stream = None\n image_bytes = cv2.imencode('.jpg', ori_frame)[1].tobytes()\n filename = hashlib.sha256(image_bytes).hexdigest() + f'{ext}'\n return filename\n\n\ndef download(url):\n \"\"\"\n Handle input url from client \n \"\"\"\n\n ext = tldextract.extract(url)\n if ext.domain == 'youtube':\n\n make_dir(app.config['VIDEO_FOLDER'])\n\n print('Youtube')\n ori_path = download_yt(url)\n filename = hash_video(ori_path)\n\n path = os.path.join(app.config['VIDEO_FOLDER'], filename)\n\n Path(ori_path).rename(path)\n\n else:\n make_dir(app.config['UPLOAD_FOLDER'])\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2)',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding': 'none',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Connection': 'keep-alive'}\n r = requests.get(url, stream=True, headers=headers)\n print('Image Url')\n\n # Get cache name by hashing image\n data = r.content\n ori_filename = url.split('/')[-1]\n _, ext = os.path.splitext(ori_filename)\n filename = hashlib.sha256(data).hexdigest() + f'{ext}'\n\n path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n\n with open(path, \"wb\") as file:\n file.write(r.content)\n\n return filename, path\n\n\ndef save_upload(file):\n \"\"\"\n Save uploaded image and video if its format is allowed\n \"\"\"\n filename = secure_filename(file.filename)\n if allowed_file_image(filename):\n make_dir(app.config['UPLOAD_FOLDER'])\n path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n\n elif allowed_file_video(filename):\n make_dir(app.config['VIDEO_FOLDER'])\n path = os.path.join(app.config['VIDEO_FOLDER'], filename)\n\n file.save(path)\n\n return path\n\n\npath = Path(__file__).parent\n\n\[email protected]('/')\ndef homepage():\n resp = make_response(render_template(\"upload-file.html\"))\n resp.headers['Access-Control-Allow-Origin'] = '*'\n return resp\n\n\[email protected]('/about')\ndef about_page():\n return render_template(\"about-page.html\")\n\n\[email protected]('/url')\ndef detect_by_url_page():\n return render_template(\"input-url.html\")\n\n\[email protected]('/webcam')\ndef detect_by_webcam_page():\n return render_template(\"webcam-capture.html\")\n\n\[email protected]('/analyze', methods=['POST', 'GET'])\n@cross_origin(supports_credentials=True)\ndef analyze():\n if request.method == 'POST':\n out_name = None\n filepath = None\n filename = None\n filetype = None\n csv_name1 = None\n csv_name2 = None\n\n print(\"File: \", request.files)\n\n if 'webcam-button' in request.form:\n # Get webcam capture\n\n f = request.files['blob-file']\n ori_file_name = secure_filename(f.filename)\n filetype = file_type(ori_file_name)\n\n filename = time.strftime(\"%Y%m%d-%H%M%S\") + '.png'\n filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n\n # save file to /static/uploads\n img = Image.open(f.stream)\n # img.show()\n img.save(filepath)\n\n elif 'url-button' in request.form:\n # Get image/video from input url\n\n url = request.form['url_link']\n filename, filepath = download(url)\n\n filetype = file_type(filename)\n\n elif 'upload-button' in request.form:\n # Get uploaded file\n\n f = request.files['file']\n ori_file_name = secure_filename(f.filename)\n _, ext = os.path.splitext(ori_file_name)\n\n filetype = file_type(ori_file_name)\n\n if filetype == 'image':\n # Get cache name by hashing image\n data = f.read()\n filename = hashlib.sha256(data).hexdigest() + f'{ext}'\n\n # Save file to /static/uploads\n filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n np_img = np.fromstring(data, np.uint8)\n img = cv2.imdecode(np_img, cv2.IMREAD_COLOR)\n cv2.imwrite(filepath, img)\n\n elif filetype == 'video':\n temp_filepath = os.path.join(\n app.config['UPLOAD_FOLDER'], ori_file_name)\n f.save(temp_filepath)\n filename = hash_video(temp_filepath)\n filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n os.rename(temp_filepath, filepath)\n\n # Get all inputs in form\n iou = request.form.get('threshold-range')\n confidence = request.form.get('confidence-range')\n model_types = request.form.get('model-types')\n enhanced = request.form.get('enhanced')\n ensemble = request.form.get('ensemble')\n ensemble = True if ensemble == 'on' else False\n enhanced = True if enhanced == 'on' else False\n model_types = str.lower(model_types)\n min_conf = float(confidence)/100\n min_iou = float(iou)/100\n\n if filetype == 'image':\n # Get filename of detected image\n\n out_name = \"Image Result\"\n output_path = os.path.join(\n app.config['DETECTION_FOLDER'], filename)\n\n filename = get_prediction(\n filepath,\n output_path,\n model_name=model_types,\n ensemble=ensemble,\n min_conf=min_conf,\n min_iou=min_iou,\n enhance_labels=enhanced)\n\n elif filetype == 'video':\n # Get filename of detected video\n\n out_name = \"Video Result\"\n output_path = os.path.join(\n app.config['DETECTION_FOLDER'], filename)\n\n filename = get_video_prediction(\n filepath,\n output_path,\n model_name=model_types,\n min_conf=min_conf,\n min_iou=min_iou,\n enhance_labels=enhanced)\n else:\n error_msg = \"Invalid input url!!!\"\n return render_template('detect-input-url.html', error_msg=error_msg)\n\n filename = os.path.basename(filename)\n csv_name, _ = os.path.splitext(filename)\n\n csv_name1 = os.path.join(\n app.config['CSV_FOLDER'], csv_name + '_info.csv')\n csv_name2 = os.path.join(\n app.config['CSV_FOLDER'], csv_name + '_info2.csv')\n\n if 'url-button' in request.form:\n return render_template('detect-input-url.html', out_name=out_name, fname=filename, filetype=filetype, csv_name=csv_name1, csv_name2=csv_name2)\n\n elif 'webcam-button' in request.form:\n return render_template('detect-webcam-capture.html', out_name=out_name, fname=filename, filetype=filetype, csv_name=csv_name1, csv_name2=csv_name2)\n\n return render_template('detect-upload-file.html', out_name=out_name, fname=filename, filetype=filetype, csv_name=csv_name1, csv_name2=csv_name2)\n\n return redirect('/')\n\n\[email protected]('/api', methods=['POST'])\ndef api_call():\n if request.method == 'POST':\n response = {}\n if not request.json or 'url' not in request.json:\n response['code'] = 404\n return jsonify(response)\n else:\n # get the base64 encoded string\n url = request.json['url']\n filename, filepath = download(url)\n\n model_types = request.json['model_types']\n ensemble = request.json['ensemble']\n min_conf = request.json['min_conf']\n min_iou = request.json['min_iou']\n enhanced = request.json['enhanced']\n\n output_path = os.path.join(\n app.config['DETECTION_FOLDER'], filename)\n\n get_prediction(\n filepath,\n output_path,\n model_name=model_types,\n ensemble=ensemble,\n min_conf=min_conf,\n min_iou=min_iou,\n enhance_labels=enhanced)\n\n with open(output_path, \"rb\") as f:\n res_im_bytes = f.read()\n res_im_b64 = base64.b64encode(res_im_bytes).decode(\"utf8\")\n response['res_image'] = res_im_b64\n response['filename'] = filename\n response['code'] = 200\n return jsonify(response)\n\n return jsonify({\"code\": 400})\n\n\[email protected]_request\ndef add_header(response):\n # Include cookie for every request\n response.headers.add('Access-Control-Allow-Credentials', True)\n\n # Prevent the client from caching the response\n if 'Cache-Control' not in response.headers:\n response.headers['Cache-Control'] = 'public, no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'\n response.headers['Pragma'] = 'no-cache'\n response.headers['Expires'] = '-1'\n return response\n\n\nif __name__ == '__main__':\n if not os.path.exists(UPLOAD_FOLDER):\n os.makedirs(UPLOAD_FOLDER, exist_ok=True)\n if not os.path.exists(DETECTION_FOLDER):\n os.makedirs(DETECTION_FOLDER, exist_ok=True)\n if not os.path.exists(VIDEO_FOLDER):\n os.makedirs(VIDEO_FOLDER, exist_ok=True)\n if not os.path.exists(CSV_FOLDER):\n os.makedirs(CSV_FOLDER, exist_ok=True)\n if not os.path.exists(METADATA_FOLDER):\n os.makedirs(METADATA_FOLDER, exist_ok=True)\n\n args = parser.parse_args()\n\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\n if args.ngrok:\n run_with_ngrok(app)\n app.run()\n else:\n hostname = str.split(args.host, ':')\n if len(hostname) == 1:\n port = 4000\n else:\n port = hostname[1]\n host = hostname[0]\n\n app.run(host=host, port=port, debug=args.debug, use_reloader=False,\n ssl_context='adhoc')\n\n# Run: python app.py --host localhost:8000\n",
"import torch\nimport torch.nn as nn\nimport torchvision\nimport numpy as np\nimport math\nimport webcolors\nimport cv2\nimport gdown\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom torch.nn.init import _calculate_fan_in_and_fan_out, _no_grad_normal_\n\nSTANDARD_COLORS = [\n 'LawnGreen', 'LightBlue' , 'Crimson', 'Gold', 'Azure', 'BlanchedAlmond', 'Bisque',\n 'Aquamarine', 'BlueViolet', 'BurlyWood', 'CadetBlue', 'AntiqueWhite',\n 'Chocolate', 'Coral', 'CornflowerBlue', 'Cornsilk', 'Crimson', 'Cyan',\n 'DarkCyan', 'DarkGoldenRod', 'DarkGrey', 'DarkKhaki', 'DarkOrange',\n 'DarkOrchid', 'DarkSalmon', 'DarkSeaGreen', 'DarkTurquoise', 'DarkViolet',\n 'DeepPink', 'DeepSkyBlue', 'DodgerBlue', 'FireBrick', 'FloralWhite',\n 'ForestGreen', 'Fuchsia', 'Gainsboro', 'GhostWhite', 'Gold', 'GoldenRod',\n 'Salmon', 'Tan', 'HoneyDew', 'HotPink', 'IndianRed', 'Ivory', 'Khaki',\n 'Lavender', 'LavenderBlush', 'AliceBlue', 'LemonChiffon', 'LightBlue',\n 'LightCoral', 'LightCyan', 'LightGoldenRodYellow', 'LightGray', 'LightGrey',\n 'LightGreen', 'LightPink', 'LightSalmon', 'LightSeaGreen', 'LightSkyBlue',\n 'LightSlateGray', 'LightSlateGrey', 'LightSteelBlue', 'LightYellow', 'Lime',\n 'LimeGreen', 'Linen', 'Magenta', 'MediumAquaMarine', 'MediumOrchid',\n 'MediumPurple', 'MediumSeaGreen', 'MediumSlateBlue', 'MediumSpringGreen',\n 'MediumTurquoise', 'MediumVioletRed', 'MintCream', 'MistyRose', 'Moccasin',\n 'NavajoWhite', 'OldLace', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed',\n 'Orchid', 'PaleGoldenRod', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed',\n 'PapayaWhip', 'PeachPuff', 'Peru', 'Pink', 'Plum', 'PowderBlue', 'Purple',\n 'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Green', 'SandyBrown',\n 'SeaGreen', 'SeaShell', 'Sienna', 'Silver', 'SkyBlue', 'SlateBlue',\n 'SlateGray', 'SlateGrey', 'Snow', 'SpringGreen', 'SteelBlue', 'GreenYellow',\n 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'White',\n 'WhiteSmoke', 'Yellow', 'YellowGreen'\n]\n\ndef from_colorname_to_bgr(color):\n rgb_color = webcolors.name_to_rgb(color)\n result = (rgb_color.blue, rgb_color.green, rgb_color.red)\n return result\n\ndef standard_to_bgr(list_color_name):\n standard = []\n for i in range(len(list_color_name) - 36): # -36 used to match the len(obj_list)\n standard.append(from_colorname_to_bgr(list_color_name[i]))\n return standard\n\ncolor_list = standard_to_bgr(STANDARD_COLORS)\n\ndef draw_boxes_v2(img_name, img, boxes, label_ids, scores, label_names=None, obj_list=None, figsize=(15,15)):\n \"\"\"\n Visualize an image with its bouding boxes\n rgn image + xywh box\n \"\"\"\n def plot_one_box(img, box, key=None, value=None, color=None, line_thickness=None):\n tl = line_thickness or int(round(0.001 * max(img.shape[0:2]))) # line thickness\n\n coord = [box[0], box[1], box[0]+box[2], box[1]+box[3]]\n c1, c2 = (int(coord[0]), int(coord[1])), (int(coord[2]), int(coord[3]))\n cv2.rectangle(img, c1, c2, color, thickness=tl*2)\n if key is not None and value is not None:\n header = f'{key}: {value}'\n tf = max(tl - 2, 1) # font thickness\n s_size = cv2.getTextSize(f' {value}', 0, fontScale=float(tl) / 3, thickness=tf)[0]\n t_size = cv2.getTextSize(f'{key}:', 0, fontScale=float(tl) / 3, thickness=tf)[0]\n c2 = c1[0] + t_size[0] + s_size[0] + 15, c1[1] - t_size[1] - 3\n cv2.rectangle(img, c1, c2, color, -1) # filled\n cv2.putText(img, header, (c1[0], c1[1] - 2), 0, float(tl) / 3, [0, 0, 0],\n thickness=tf, lineType=cv2.FONT_HERSHEY_SIMPLEX)\n \n # boxes input is xywh\n boxes = boxes.astype(np.int)\n img_bgr = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n\n for idx, (box, label_id, score) in enumerate(zip(boxes, label_ids, scores)):\n if label_names is not None:\n label = label_names[idx]\n if obj_list is not None:\n label = obj_list[label_id]\n \n plot_one_box(\n img_bgr, \n box, \n key = label,\n value = '{:.0%}'.format(float(score)),\n color=color_list[int(label_id)])\n\n cv2.imwrite(img_name, img_bgr)\n\ndef draw_pred_gt_boxes(image_outname, img, boxes, labels, scores, image_name=None, figsize=(10,10)):\n \"\"\"\n Visualize an image with its bouding boxes\n \"\"\"\n plt.close('all')\n fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=figsize)\n # if image_name is not None:\n # fig.suptitle(image_name)\n # fig.tight_layout(rect=[0, 0.03, 1, 0.95])\n if isinstance(img, torch.Tensor):\n img = img.numpy().squeeze().transpose((1,2,0))\n # Display the image\n ax1.imshow(img)\n ax2.imshow(img)\n \n ax1.set_title('Prediction')\n ax2.set_title('Ground Truth')\n\n # Split prediction and ground truth\n pred_boxes, pred_labels, pred_scores = boxes[0], labels[0], scores\n gt_boxes, gt_labels = boxes[1], labels[1]\n\n # Plot prediction boxes\n for box, label, score in zip(pred_boxes, pred_labels, pred_scores):\n label = int(label)\n color = STANDARD_COLORS[label]\n x,y,w,h = box\n rect = patches.Rectangle((x,y),w,h,linewidth=1.5,edgecolor = color,facecolor='none')\n score = np.round(score, 3)\n text = '{}: {}'.format(label, str(score))\n ax1.text(x, y-3,text, color = color, fontsize=15)\n # Add the patch to the Axes\n ax1.add_patch(rect)\n\n # Plot ground truth boxes\n for box, label in zip(gt_boxes, gt_labels):\n label = int(label)\n if label <0:\n continue\n color = STANDARD_COLORS[label]\n x,y,w,h = box\n rect = patches.Rectangle((x,y),w,h,linewidth=1.5,edgecolor = color,facecolor='none')\n score = np.round(score, 3)\n text = '{}'.format(label)\n ax2.text(x, y-3,text, color = color, fontsize=15)\n # Add the patch to the Axes\n ax2.add_patch(rect)\n\n plt.axis('off')\n fig = ax1.get_figure()\n fig.tight_layout()\n fig.subplots_adjust(top=0.95)\n\n fig = ax2.get_figure()\n fig.tight_layout()\n fig.subplots_adjust(top=0.95)\n\n plt.savefig(image_outname,bbox_inches='tight')\n return fig\n\n # plt.close()\n\ndef write_to_video(img, boxes, labels, scores, imshow=True, outvid = None, obj_list=None):\n \n def plot_one_box(img, box, key=None, value=None, color=None, line_thickness=None):\n tl = line_thickness or int(round(0.001 * max(img.shape[0:2]))) # line thickness\n\n coord = [box[0], box[1], box[0]+box[2], box[1]+box[3]]\n c1, c2 = (int(coord[0]), int(coord[1])), (int(coord[2]), int(coord[3]))\n cv2.rectangle(img, c1, c2, color, thickness=tl*2)\n if key is not None and value is not None:\n header = f'{key} || {value}'\n tf = max(tl - 2, 1) # font thickness\n s_size = cv2.getTextSize(f'| {value}', 0, fontScale=float(tl) / 3, thickness=tf)[0]\n t_size = cv2.getTextSize(f'{key} |', 0, fontScale=float(tl) / 3, thickness=tf)[0]\n c2 = c1[0] + t_size[0] + s_size[0] + 15, c1[1] - t_size[1] - 3\n cv2.rectangle(img, c1, c2, color, -1) # filled\n cv2.putText(img, header, (c1[0], c1[1] - 2), 0, float(tl) / 3, [0, 0, 0],\n thickness=tf, lineType=cv2.FONT_HERSHEY_SIMPLEX)\n\n # boxes input is xywh\n boxes = boxes.astype(np.int)\n\n for idx, (box, label, score) in enumerate(zip(boxes, labels, scores)):\n plot_one_box(\n img, \n box, \n key = obj_list[int(label)],\n value = '{:.0%}'.format(float(score)),\n color=color_list[int(label)])\n\n if imshow:\n cv2.namedWindow('img',cv2.WINDOW_NORMAL)\n cv2.resizeWindow('image', 600,600)\n cv2.imshow('img', img)\n cv2.waitKey(1)\n\n if outvid is not None:\n outvid.write(img)\n\ndef download_weights(id_or_url, cached=None, md5=None, quiet=False):\n if id_or_url.startswith('http'):\n url = id_or_url\n else:\n url = 'https://drive.google.com/uc?id={}'.format(id_or_url)\n\n return gdown.cached_download(url=url, path=cached, md5=md5, quiet=quiet)\n\n\nweight_url = {\n \"yolov5s\": \"1-4XEt2xLtoTDF0RYEh-WlbQWi-HouJxR\" ,\n \"yolov5m\": \"1-9ra0DEo5AjXmopm2cAkI_eqlD1DVwrF\" ,\n \"yolov5l\": \"1-Bsl9DayZtKx-POlhZM2dN7PBo1dmbHJ\",\n \"yolov5x\": \"1-HTVvUR88cXixngUbtScCSK42hlcNm1g\",\n \"se_resnet\": \"1SjWV-tZ980n7t0K68Lfpu5j9sw5-E2Gs\"\n}\n\ndef download_pretrained_weights(name, cached=None):\n return download_weights(weight_url[name], cached)\n "
] |
[
[
"numpy.fromstring"
],
[
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.round",
"matplotlib.pyplot.close",
"matplotlib.pyplot.axis"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
koconnor4/hstphot
|
[
"04ec83fc6dce056bd6153e407446e1be4dff3923"
] |
[
"hstfakestar.py"
] |
[
"__author__ = 'rodney'\n\nfrom hstphot import radec2xy\nfrom astropy.io import fits as pyfits\nimport numpy as np\nfrom PythonPhot.photfunctions import rdpsfmodel\nfrom PythonPhot.photfunctions import addtoimarray\n\ndef addtofits(fitsin, fitsout, psfmodelfile, position, fluxscale,\n coordsys='xy', verbose=False):\n \"\"\" Create a psf, add it into the given fits image at the\n\n :param fitsin: fits file name for the target image\n :param psfmodelfile: fits file holding the psf model\n :param position: Scalar or array, giving the psf center positions\n :param fluxscale: Scalar or array, giving the psf flux scaling factors\n :param coordsys: Either 'radec' or 'xy'\n :return:\n \"\"\"\n\n if not np.iterable(fluxscale):\n fluxscale = np.array([fluxscale])\n position = np.array([position])\n\n if coordsys == 'radec':\n ra = position[:, 0]\n dec = position[:, 1]\n position = radec2xy(fitsin, ra, dec, ext=0)\n\n image = pyfits.open(fitsin, mode='readonly')\n imagedat = image[0].data\n\n psfmodel = rdpsfmodel(psfmodelfile)\n\n for i in range(len(fluxscale)):\n imagedat = addtoimarray(imagedat, psfmodel, position[i], fluxscale[i])\n image[0].data = imagedat\n\n image.writeto(fitsout, clobber=True)\n if verbose:\n print(\"Wrote updated image to %s\" % fitsout)\n return\n"
] |
[
[
"numpy.iterable",
"numpy.array"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
int-brain-lab/spikes
|
[
"bc557fa5024e8eedc60b7369dba12121df56d3be",
"bc557fa5024e8eedc60b7369dba12121df56d3be"
] |
[
"localization_pipeline/denoiser.py",
"localization_pipeline/localizer_with_residuals.py"
] |
[
"\nimport numpy as np\nimport os\nimport torch\nfrom torch import nn, optim\nimport torch.utils.data as Data\nfrom torch.nn import functional as F\nfrom torch import distributions\n\n\nclass Denoise(nn.Module):\n def __init__(self, n_filters, filter_sizes, spike_size):\n\n super(Denoise, self).__init__()\n \n feat1, feat2, feat3 = n_filters\n size1, size2, size3 = filter_sizes\n \n self.conv1 = nn.Sequential( # input shape (1, 28, 28)\n nn.Conv1d(\n in_channels=1, # input height\n out_channels=feat1, # n_filters\n kernel_size=size1, # filter size\n stride=1, # filter movement/step\n padding=0, # if want same width and length of this image after Conv2d, padding=(kernel_size-1)/2 if stride=1\n ), # output shape (16, 28, 28)\n nn.ReLU(), # activation\n )\n\n self.conv2 = nn.Sequential( # input shape (16, 14, 14)\n nn.Conv1d(feat1, feat2, size2, 1, 0), # output shape (32, 14, 14)\n nn.ReLU(), # activation\n )\n\n self.conv3 = nn.Sequential( # input shape (16, 14, 14)\n nn.Conv1d(feat2, feat3, size3, 1, 0), # output shape (32, 14, 14)\n nn.ReLU(), # activation\n )\n\n #n_input_feat = feat3*(61-size1-size2-size3+3)\n n_input_feat = feat2*(spike_size-size1-size2+2)\n self.out = nn.Linear(n_input_feat, spike_size)\n \n #self.counter=0\n \n def forward(self, x):\n x = x[:, None]\n x = self.conv1(x)\n x = self.conv2(x)\n #x = self.conv3(x)\n x = x.view(x.shape[0], -1)\n #print (x.shape)\n #print (self.out(x).shape)\n #np.save('/home/cat/temp/'+str(self.counter)+'.npy', x.cpu().data.numpy())\n output = self.out(x)\n #self.counter+=1\n return output, x # return x for visualization\n\n def train(self, fname_save, DenoTD, n_train=50000, n_test=500, EPOCH=2000, BATCH_SIZE=512, LR=0.0001):\n\n print('Training NN denoiser')\n\n if os.path.exists(fname_save):\n return\n\n optimizer = torch.optim.Adam(self.parameters(), lr=LR) # optimize all cnn parameters\n loss_func = nn.MSELoss() # the target label is not one-hotted\n\n wf_col_train, wf_clean_train = DenoTD.make_training_data(n_train)\n train = Data.TensorDataset(torch.FloatTensor(wf_col_train), torch.FloatTensor(wf_clean_train))\n train_loader = Data.DataLoader(train, batch_size=BATCH_SIZE, shuffle=True)\n\n wf_col_test, wf_clean_test = DenoTD.make_training_data(n_test)\n\n # training and testing\n for epoch in range(EPOCH):\n for step, (b_x, b_y) in enumerate(train_loader): # gives batch data, normalize x when iterate train_loader\n est = self(b_x.cuda())[0]\n loss = loss_func(est, b_y.cuda()) # cross entropy loss\n optimizer.zero_grad() # clear gradients for this training step\n loss.backward() # backpropagation, compute gradients\n optimizer.step() # apply gradients\n\n if step % 100 == 0:\n est_test = self(torch.FloatTensor(wf_col_test).cuda())[0]\n l2_loss = np.mean(np.square(est_test.cpu().data.numpy() - wf_clean_test))\n print('Epoch: ', epoch, '| train loss: %.4f' % loss.cpu().data.numpy(), '| test accuracy: %.4f' % l2_loss)\n \n # save model\n torch.save(self.state_dict(), fname_save)\n \n def load(self, fname_model):\n checkpoint = torch.load(fname_model,\n map_location=lambda storage,\n loc: storage)\n self.load_state_dict(checkpoint)\n del checkpoint\n torch.cuda.empty_cache()",
"import os\nimport numpy as np\nfrom tqdm import tqdm\nfrom localization_pipeline.denoiser import Denoise\nimport scipy.optimize as optim_ls\nimport torch\nimport torch.multiprocessing as mp\n\n\nclass LOCALIZER(object):\n \n def __init__(self, bin_file, residual_file, dtype, spike_train_path, templates_path, geom_path, denoiser_weights, denoiser_min,\n n_filters = [16, 8, 4], filter_sizes = [5, 11, 21], sampling_rate = 30000,\n multi_processing = 1, n_processors = 5, spike_size = 121, n_channels_loc = 10):\n self.bin_file = bin_file\n self.residual_file = residual_file\n self.dtype = np.dtype(dtype)\n self.spike_train = np.load(spike_train_path)\n self.spike_train = self.spike_train[self.spike_train[:, 0].argsort()]\n self.multi_processing = multi_processing\n self.n_processors = n_processors\n self.spike_size = spike_size\n self.geom_array = np.load(geom_path)\n self.sampling_rate = sampling_rate\n self.n_channels = self.geom_array.shape[0]\n self.denoiser_weights = denoiser_weights\n self.denoiser_min = denoiser_min\n self.n_filters = n_filters,\n self.filter_sizes = filter_sizes,\n self.n_channels_loc = n_channels_loc # Number of channels used for localizing -> Change for spatial radius / depend on geometry array\n \n def read_waveforms(self, spike_times, n_times=None, channels=None):\n '''\n read waveforms from recording\n n_times : waveform temporal length \n channels : channels to read from \n '''\n\n if n_times is None:\n n_times = self.spike_size\n\n # n_times needs to be odd\n if n_times % 2 == 0:\n n_times += 1\n\n # read all channels\n if channels is None:\n channels = np.arange(self.geom_array.shape[0])\n\n # ***** LOAD RAW RECORDING *****\n wfs = np.zeros((len(spike_times), n_times, len(channels)),\n 'float32')\n\n skipped_idx = []\n total_size = n_times*self.n_channels\n # spike_times are the centers of waveforms\n spike_times_shifted = spike_times - n_times//2\n offsets = spike_times_shifted.astype('int64')*self.dtype.itemsize*self.n_channels\n with open(self.residual_file, \"rb\") as fin:\n for ctr, spike in enumerate(spike_times_shifted):\n try:\n fin.seek(offsets[ctr], os.SEEK_SET)\n wf = np.fromfile(fin,\n dtype=self.dtype,\n count=total_size)\n wfs[ctr] = wf.reshape(\n n_times, self.n_channels)[:,channels]\n except:\n skipped_idx.append(ctr)\n wfs=np.delete(wfs, skipped_idx, axis=0)\n fin.close()\n\n return wfs, skipped_idx\n \n def load_denoiser(self):\n if torch.cuda.is_available():\n self.device = \"cuda:0\"\n else:\n self.device = \"cpu\"\n# torch.cuda.set_device(CONFIG.resources.gpu_id)\n\n self.denoiser = Denoise(self.n_filters[0],\n self.filter_sizes[0],\n self.spike_size)\n self.denoiser.load(self.denoiser_weights)\n self.denoiser = self.denoiser.cuda()\n \n def denoise_wf_nn_tmp(self, wf):\n denoiser = self.denoiser.to(self.device)\n n_data, n_times, n_chans = wf.shape\n if wf.shape[0]>0:\n wf_reshaped = wf.transpose(0, 2, 1).reshape(-1, n_times)\n wf_torch = torch.FloatTensor(wf_reshaped).to(self.device)\n denoised_wf = denoiser(wf_torch)[0].data\n denoised_wf = denoised_wf.reshape(\n n_data, n_chans, n_times)\n denoised_wf = denoised_wf.cpu().data.numpy().transpose(0, 2, 1)\n\n del wf_torch\n else:\n denoised_wf = np.zeros((wf.shape[0], wf.shape[1]*wf.shape[2]),'float32')\n\n return denoised_wf\n\n\n \n def subsample(self, num_obs, events, units):\n events_sampled = -10*np.ones(events.shape)\n units_sampled = -10*np.ones(units.shape)\n for unit in np.unique(units):\n spike_times_unit = np.where(units == unit)[0]\n idx = np.random.choice(np.arange(0, spike_times_unit.shape[0]), size=min(num_obs, spike_times_unit.shape[0]), replace=False)\n spike_times_unit = spike_times_unit[idx]\n events_sampled[spike_times_unit] = events[spike_times_unit].copy()\n units_sampled[spike_times_unit] = units[spike_times_unit].copy()\n for unit in [-1, -2]:\n spike_times_unit = np.where(units == unit)[0]\n idx = np.random.choice(np.arange(0, spike_times_unit.shape[0]), size=min(num_obs, spike_times_unit.shape[0]), replace=False)\n spike_times_unit = spike_times_unit[idx]\n events_sampled[spike_times_unit] = events[spike_times_unit].copy()\n units_sampled[spike_times_unit] = units[spike_times_unit].copy()\n return events_sampled[events_sampled >= -5], units_sampled[units_sampled >= -5]\n \n def get_templates(self):\n if self.templates is None:\n units = np.unique(self.spike_train[:, 1])\n self.templates = np.zeros((units.max()+1, 121, 384))\n for unit in tqdm(units):\n spike_times, spike_units = self.subsample(250, self.spike_train[self.spike_train[:, 1]==unit][:, 0], self.spike_train[self.spike_train[:, 1]==unit][:, 1])\n wfs = self.read_waveforms(spike_times)[0]\n mc = wfs.mean(0).ptp(0).argmax()\n # wfs = shift_chans(wfs, align_get_shifts_with_ref(wfs[:,:,mc], nshifts = 25))\n if wfs.shape[0]>0:\n self.templates[unit] = wfs.mean(0)\n\n def get_offsets(self):\n self.offsets = np.zeros(self.templates.shape[0])\n for unit in range(self.templates.shape[0]):\n self.offsets[unit] = self.templates[unit][:, self.templates[unit].ptp(0).argmax()].argmin() - self.denoiser_min\n\n def compute_aligned_templates(self):\n units = np.unique(self.spike_train[:, 1])\n self.templates_aligned = np.zeros((units.max()+1, 121, 384))\n self.get_offsets()\n for unit in tqdm(units):\n spike_times, spike_units = self.subsample(250, self.spike_train[self.spike_train[:, 1]==unit][:, 0], self.spike_train[self.spike_train[:, 1]==unit][:, 1])\n spike_times += int(self.offsets[unit])\n wfs = self.read_waveforms(spike_times)[0]\n mc = wfs.mean(0).ptp(0).argmax()\n# wfs = shift_chans(wfs, align_get_shifts_with_ref(wfs[:,:,mc], nshifts = 25))\n if wfs.shape[0]>0:\n self.templates_aligned[unit] = wfs.mean(0)\n\n def minimize_ls(self, vec, wfs_0, z_initial, channels):\n return wfs_0.ptp(1)-vec[3]/(((self.geom_array[channels] - [vec[0], z_initial+vec[1]])**2).sum(1) + vec[2]**2)**0.5 # vec[0]\n\n\n def get_estimate(self, batch_id, threshold = 6, output_directory = 'position_results_files'):\n \n spike_times_batch = self.spike_train[np.logical_and(self.spike_train[:, 0] >= batch_id*self.sampling_rate, self.spike_train[:, 0] < (batch_id+1)*self.sampling_rate), 0]\n spike_units_batch = self.spike_train[np.logical_and(self.spike_train[:, 0] >= batch_id*self.sampling_rate, self.spike_train[:, 0] < (batch_id+1)*self.sampling_rate), 1]\n\n time_width = np.zeros(spike_times_batch.shape[0])\n results_x = np.zeros(spike_times_batch.shape[0])\n results_x_mean = np.zeros(spike_times_batch.shape[0])\n results_alpha = np.zeros(spike_times_batch.shape[0])\n results_y = np.zeros(spike_times_batch.shape[0])\n results_spread = np.zeros(spike_times_batch.shape[0])\n results_max_ptp = np.zeros(spike_times_batch.shape[0])\n results_z = np.zeros(spike_times_batch.shape[0])\n max_channels = np.zeros(spike_times_batch.shape[0])\n results_z_mean = np.zeros(spike_times_batch.shape[0])\n results_times = np.zeros(spike_times_batch.shape[0])\n\n for i in (range(spike_times_batch.shape[0])):\n unit = spike_units_batch[i]\n channels = np.arange(0, self.n_channels)\n wfs_0, skipped_idx = self.read_waveforms(np.asarray([int(spike_times_batch[i] + self.offsets[unit])])) \n if len(skipped_idx) == 0:\n wfs_0 += self.templates_aligned[int(spike_units_batch[i])].reshape((1, 121, 384))\n wfs_0 = self.denoise_wf_nn_tmp(wfs_0)[0]\n mc = wfs_0.ptp(0).argmax()\n\n if wfs_0.ptp(0).max() > threshold:\n time_width[i] = np.abs(wfs_0[:, mc].argmax() - wfs_0[:, mc].argmin())\n max_channels[i] = channels[mc]\n if mc <= self.n_channels_loc//2:\n channels_wfs = np.arange(0, self.n_channels_loc)\n elif mc >= self.n_channels - self.n_channels_loc//2:\n channels_wfs = np.arange(self.n_channels - self.n_channels_loc, self.n_channels)\n else:\n channels_wfs = np.arange(mc - self.n_channels_loc//2, mc + self.n_channels_loc//2)\n results_z_mean[i] = (wfs_0.ptp(0)[channels_wfs]*self.geom_array[channels[channels_wfs], 1]).sum()/wfs_0.ptp(0)[channels_wfs].sum()\n x_init = (wfs_0.ptp(0)[channels_wfs]*self.geom_array[channels[channels_wfs], 0]).sum()/wfs_0.ptp(0)[channels_wfs].sum()\n results_x_mean[i] = x_init\n\n results_max_ptp[i] = wfs_0.ptp(0).max()\n\n output = optim_ls.least_squares(self.minimize_ls, x0=[results_x_mean[i], 0, 21, 1000], bounds = ([-100, -100, 0, 0], [132, 100, 250, 10000]), args=(wfs_0[:, channels_wfs].T, results_z_mean[i], channels[channels_wfs]))['x']\n\n results_x[i] = output[0]\n results_z[i] = results_z_mean[i] + output[1] \n results_alpha[i] = output[3]\n results_y[i] = np.abs(output[2]) #max(25, (output[2]/wfs_0.ptp(0)[channels_wfs].max() - ((CONFIG.geom[channels[mc]] - [output[0] , CONFIG.geom[channels[mc], 1] + output[1]])**2).sum()).mean())\n results_spread[i] = (wfs_0.ptp(0)[channels_wfs]*((self.geom_array[channels[channels_wfs]] - [results_x[i], results_z[i]])**2).sum(1)).sum()/wfs_0.ptp(0)[channels_wfs].sum()\n results_times[i] = 1\n\n fname_time_width = os.path.join(output_directory, 'results_width_{}.npy'.format(str(batch_id).zfill(6)))\n fname_z = os.path.join(output_directory, 'results_z_{}.npy'.format(str(batch_id).zfill(6))) \n fname_x = os.path.join(output_directory, 'results_x_{}.npy'.format(str(batch_id).zfill(6)))\n fname_z_mean = os.path.join(output_directory, 'results_z_mean_{}.npy'.format(str(batch_id).zfill(6))) \n fname_x_mean = os.path.join(output_directory, 'results_x_mean_{}.npy'.format(str(batch_id).zfill(6)))\n fname_spread = os.path.join(output_directory, 'results_spread_{}.npy'.format(str(batch_id).zfill(6)))\n fname_max_ptp = os.path.join(output_directory, 'results_max_ptp_{}.npy'.format(str(batch_id).zfill(6)))\n fname_y = os.path.join(output_directory, 'results_y_{}.npy'.format(str(batch_id).zfill(6)))\n fname_alpha = os.path.join(output_directory, 'results_alpha_{}.npy'.format(str(batch_id).zfill(6)))\n fname_max_channels = os.path.join(output_directory, 'results_max_channels_{}.npy'.format(str(batch_id).zfill(6)))\n fname_times_read = os.path.join(output_directory, 'times_read_{}.npy'.format(str(batch_id).zfill(6)))\n \n np.save(fname_z, results_z)\n np.save(fname_x, results_x)\n np.save(fname_z_mean, results_z_mean)\n np.save(fname_x_mean, results_x_mean)\n np.save(fname_time_width, time_width)\n np.save(fname_max_channels, max_channels)\n np.save(fname_max_ptp, results_max_ptp)\n np.save(fname_spread, results_spread)\n np.save(fname_alpha, results_alpha)\n np.save(fname_y, results_y)\n np.save(fname_times_read, results_times)\n\n\n"
] |
[
[
"torch.load",
"torch.utils.data.DataLoader",
"torch.cuda.empty_cache",
"torch.nn.Linear",
"torch.FloatTensor",
"torch.nn.Conv1d",
"torch.nn.ReLU",
"torch.nn.MSELoss"
],
[
"numpy.fromfile",
"numpy.abs",
"numpy.unique",
"scipy.optimize.least_squares",
"numpy.arange",
"numpy.dtype",
"numpy.save",
"numpy.ones",
"numpy.delete",
"torch.FloatTensor",
"torch.cuda.is_available",
"numpy.load",
"numpy.logical_and",
"numpy.zeros",
"numpy.where"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
tig/datapane
|
[
"defae6776e73b07191c0a5804a50b284ec3c9a63"
] |
[
"tests/client/e2e/test_reports.py"
] |
[
"import json\nfrom datetime import date, datetime, timedelta, timezone\nfrom pathlib import Path\n\nimport altair as alt\nimport pandas as pd\nimport pytest\nimport requests\nfrom furl import furl\n\nimport datapane as dp\nfrom datapane.client import config as c\n\nfrom ..local.test_api import gen_report_complex_with_files, gen_report_simple\nfrom .common import check_name, deletable, gen_description, gen_df, gen_name\n\npytestmark = pytest.mark.usefixtures(\"dp_login\")\n\n\ndef test_report_simple():\n report = gen_report_simple()\n report.publish(name=\"TEST\", description=\"DESCRIPTION\")\n with deletable(report):\n ...\n\n\[email protected]\ndef test_report_simple_permissions():\n report = gen_report_simple()\n report.publish(name=\"TEST\", description=\"DESCRIPTION\", visibility=dp.Visibility.PRIVATE)\n with deletable(report):\n # check we can't access api & web urls\n r = requests.get(url=report.url)\n assert r.status_code == 403\n r = requests.get(url=report.web_url)\n assert r.history[0].status_code == 302 # redirect to login\n assert r.status_code == 200\n # check we can't embed a private report\n f = furl(origin=c.config.server, path=\"api/oembed/\", args=dict(url=report.web_url))\n r = requests.get(url=str(f))\n assert r.status_code in [400, 401]\n\n\ndef test_report_with_single_file(datadir: Path):\n report = gen_report_complex_with_files(datadir, single_file=True, local_report=True)\n # Test we can save then publish\n report.save(str(datadir / \"test_report.html\"))\n report.publish(name=\"TEST\", description=\"DESCRIPTION\")\n with deletable(report):\n ...\n\n\ndef test_report_with_files(datadir: Path):\n report = gen_report_complex_with_files(datadir)\n report.publish(name=\"TEST\", description=\"DESCRIPTION\")\n with deletable(report):\n ...\n\n\ndef test_full_report(tmp_path: Path):\n df = gen_df()\n name = gen_name()\n description = gen_description()\n source_url = \"https://github.com/datapane/datapane\"\n # create a basic report\n m = dp.Text(\"hello world!!\")\n\n # Asset tests\n lis = [1, 2, 3]\n json_list: str = json.dumps(lis)\n plot = alt.Chart(df).mark_line().encode(x=\"x\", y=\"y\")\n\n # create the DP\n fn = tmp_path / \"json_list.json\"\n fn.write_text(data=json_list)\n file_asset = dp.File(file=fn)\n json_asset = dp.File(data=json_list, is_json=True)\n plot_asset = dp.Plot(data=plot)\n list_asset = dp.File(data=lis, is_json=True)\n df_asset = dp.DataTable(df=df, caption=\"Our Dataframe\")\n dp_report = dp.Report(m, file_asset, df_asset, json_asset, plot_asset, list_asset)\n dp_report.publish(name=name, description=description, source_url=source_url)\n\n with deletable(dp_report):\n # are the fields ok\n check_name(dp_report, name)\n assert dp_report.description == description\n assert dp_report.source_url == source_url\n assert len(dp_report.pages[0].blocks[0].blocks) == 6\n\n # NOTE - Asset objects no longer exists - thus below tests can't be supported\n # we do store `id` on the object, that can be used to pull out from the XML report\n # but currently unsupported\n\n # # --- FILE ASSET --- #\n # # [1, 2, 3] uploaded via a JSON file\n #\n # fn = tmpdir / \"tmp1.json\"\n # file_asset.download_file(fn)\n # asset1 = fn.read_text()\n # assert asset1 == json_list\n #\n # # check the file asset via download_obj\n # loaded_file = file_asset.download_obj()\n # assert loaded_file == lis\n #\n # # --- JSON ASSET --- #\n # # [1, 2, 3] uploaded as a JSON string\n #\n # # check the json asset via download_file\n # with temp_fname(\".json\") as fn:\n # fn = Path(fn)\n # json_asset.download_file(fn)\n # assert fn.read_text() == json_list\n #\n # # check the json asset via download_obj\n # loaded_json = json_asset.download_obj()\n # assert loaded_json == lis\n #\n # # --- LIST ASSET --- #\n # # [1, 2, 3] uploaded as a native Python list\n #\n # # check the list asset via download_file\n # with temp_fname(\".json\") as fn:\n # fn = Path(fn)\n # list_asset.download_file(fn)\n # assert fn.read_text() == json_list\n #\n # # check the list asset via download_obj\n # loaded_list = list_asset.download_obj()\n # assert loaded_list == lis\n #\n # # --- PLOT ASSET --- #\n #\n # # check the plot asset via download_file\n # with temp_fname(\".json\") as fn:\n # fn = Path(fn)\n # plot_asset.download_file(fn)\n # assert json.loads(fn.read_text()) == plot.to_dict()\n #\n # # check the plot asset via download_obj\n # loaded_obj = plot_asset.download_obj()\n # assert loaded_obj == plot.to_dict()\n #\n # # --- DF ASSET --- #\n #\n # # check the df asset\n # df1 = df_asset.download_df()\n # check_df_equal(df1, df)\n\n\ndef test_complex_df_report():\n \"\"\"Test our dataframe importing with types of DFs user's upload\"\"\"\n tz_df = pd.DataFrame(\n dict(\n duration_col=[timedelta(seconds=x) for x in range(30)],\n date_col=[date.today() for _ in range(30)],\n datetime_col=[datetime.utcnow() for _ in range(30)],\n datetimez_col=[datetime.now(timezone.utc) for _ in range(30)],\n )\n )\n\n raw_data = {\n \"first_name\": [\"Jason\", \"Molly\", \"Tina\", \"Jake\", \"Amy\"],\n \"last_name\": [\"Miller\", \"Jacobson\", \"Ali\", \"Milner\", \"Cooze\"],\n \"age\": [42, 52, 36, 24, 73],\n \"preTestScore\": [4, 24, 31, 2, 3],\n \"postTestScore\": [25, 94, 57, 62, 70],\n }\n index_df = pd.DataFrame(raw_data, columns=[\"first_name\", \"last_name\", \"age\", \"preTestScore\", \"postTestScore\"])\n df_desc = index_df.describe()\n df_desc_2 = df_desc.reset_index()\n\n tz_t = dp.DataTable(tz_df)\n index_t = dp.DataTable(index_df)\n df_desc_t = dp.DataTable(df_desc)\n df_desc_2_t = dp.DataTable(df_desc_2)\n\n with deletable(dp.Report(tz_t, index_t, df_desc_t, df_desc_2_t)) as dp_report:\n dp_report.publish(name=gen_name())\n\n # NOTE - as above, downloading embedded assets from a report currently not supported in API\n # check_df_equal(tz_df, tz_t.download_df())\n # check_df_equal(index_df, index_t.download_df())\n # check_df_equal(df_desc, df_desc_t.download_df())\n # check_df_equal(df_desc_2, df_desc_2_t.download_df())\n\n\[email protected]\ndef test_report_group():\n report = gen_report_simple()\n report.publish(name=\"test_report_group\")\n # check if the group name is default\n with deletable(report):\n assert report.group == \"default\"\n\n # test adding report to a group that doesn't exist\n report2 = gen_report_simple()\n try:\n report2.publish(name=\"test_wrong_group\", group=\"wrong-group\")\n except requests.HTTPError as e:\n assert e.response.status_code == 400\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": []
}
] |
Shahaf-Yamin/Vlocano_erruption_time_predication
|
[
"2cb7c9476c6929b85ce6ea05d513c82b1bf0d1e3"
] |
[
"losses/losses.py"
] |
[
"import tensorflow as tf\nfrom tensorflow.keras.losses import SparseCategoricalCrossentropy\nfrom backend.loss_metric_utils import nan_mask, identity\n\n\nclass ClassificationLoss(tf.keras.losses.Loss):\n\n def __init__(self, config, name='classification_loss', **kwargs):\n super().__init__(name=name, **kwargs)\n self.loss_fn = SparseCategoricalCrossentropy()\n\n self.weight_fn = nan_mask\n\n self.target_fn = identity\n\n self.pred_fn = identity\n\n\n def call(self, targets, prediction, sample_weight=None):\n targets = tf.cast(tf.reshape(targets, [-1, 1]), tf.float32)\n prediction = tf.cast(tf.reshape(prediction, [-1, prediction.shape[-1]]), tf.float32)\n\n tar = self.target_fn(targets)\n pred = self.pred_fn(prediction)\n weights = self.weight_fn(targets)\n loss = self.loss_fn(tar, pred, sample_weight=weights)\n\n return loss\n"
] |
[
[
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.reshape"
]
] |
[
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.