repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
possible_versions
list
dahem/coffe-images
[ "2af526c57c08317829e0b99af83b11c9fb9182da" ]
[ "coffee-maturation/src/models/non_maximum.py" ]
[ "import numpy as np\r\n\r\ndef non_max_suppression_fast(boxes, overlapThresh):\r\n\r\n\t# if there are no boxes, return an empty list\r\n\t\r\n\tif len(boxes) == 0:\r\n\t\treturn []\r\n\t\t\r\n\t# if the boxes are integers, convert them to floats (due to divisions)\r\n\t\r\n\tif boxes.dtype.kind == \"i\":\r\n\t\tboxes = boxes.astype(\"float\")\r\n\t\t\r\n\t# initialize the list of picked indexes\r\n\t\r\n\tpick = []\r\n\t\r\n\t# grab the coordinates of the bounding boxes\r\n\t\r\n\tx1 = boxes[:,0]\r\n\ty1 = boxes[:,1]\r\n\tx2 = boxes[:,2]\r\n\ty2 = boxes[:,3]\r\n\tscores = boxes[:,4]\r\n\t\r\n\t# compute the area of the boxes and sort the boxes by their score\r\n\t\r\n\tarea = (x2 - x1 + 1) * (y2 - y1 + 1)\r\n\t\r\n\tidxs = np.argsort(scores)[::-1]\r\n\t\r\n\t# keep looking while some indexes still remain in the indexes list\r\n\t\r\n\twhile len(idxs) > 0:\r\n\t\r\n\t\t# grab the last index in the indexes list and add its value to the list of picked indexes\r\n\t\t\r\n\t\tlast = len(idxs) - 1\r\n\t\t\r\n\t\ti = idxs[last]\r\n\t\t\r\n\t\tpick.append(i)\r\n\t\t\r\n\t\t# find the largest coordinates for the start of the overlap area and the smallest coordinates for the end\r\n\t\t\r\n\t\txx1 = np.maximum(x1[i], x1[idxs[:last]])\r\n\t\tyy1 = np.maximum(y1[i], y1[idxs[:last]])\r\n\t\txx2 = np.minimum(x2[i], x2[idxs[:last]])\r\n\t\tyy2 = np.minimum(y2[i], y2[idxs[:last]])\r\n\t\t\r\n\t\t# compute the width and height of the overlap\r\n\t\t\r\n\t\tw = np.maximum(0, xx2 - xx1 + 1)\r\n\t\th = np.maximum(0, yy2 - yy1 + 1)\r\n\t\t\r\n\t\t# compute the ratio of overlap\r\n\t\t\r\n\t\toverlap = (w * h) / area[idxs[:last]]\r\n\t\t\r\n\t\t# delete all indexes from the list that have an overlap over the threshold\r\n\t\t\r\n\t\tidxs = np.delete(idxs, np.concatenate(([last],\r\n\t\t\tnp.where(overlap > overlapThresh)[0])))\r\n\t\t\r\n\t# return only the boxes that were picked\r\n\t\t\r\n\treturn boxes[pick].astype(\"float\")\r\n\t\t\r\n\t\t\r\n\t\t" ]
[ [ "numpy.argsort", "numpy.where", "numpy.maximum", "numpy.minimum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mdrio/slaid
[ "67c85f0d1702bced1c089bfb3c20ba1cfbc9c225" ]
[ "slaid/renderers.py" ]
[ "import abc\nimport json\nimport logging\nimport os\nfrom typing import Any, Tuple, Union\n\nimport numpy as np\nimport tifffile\nimport tiledb\nimport zarr\n\nfrom slaid.commons import Mask, BasicSlide\nfrom slaid.commons.base import Polygon\nfrom slaid.commons.ecvl import BasicSlide as EcvlSlide\n\nlogger = logging.getLogger(__file__)\n\n\nclass Renderer(abc.ABC):\n @abc.abstractmethod\n def render(\n self,\n array: np.ndarray,\n filename: str,\n ):\n pass\n\n\nclass TiffRenderer(Renderer):\n def __init__(self,\n tile_size: Tuple[int, int] = (256, 256),\n rgb: bool = True,\n bigtiff=True):\n self.tile_size = tile_size\n self.channels = 4 if rgb else 2\n self.rgb = rgb\n self.bigtiff = bigtiff\n\n def _tiles(self, data: np.ndarray) -> np.ndarray:\n for y in range(0, data.shape[0], self.tile_size[0]):\n for x in range(0, data.shape[1], self.tile_size[1]):\n tile = data[y:y + self.tile_size[0], x:x + self.tile_size[1]]\n if tile.shape[:2] != self.tile_size:\n pad = (\n (0, self.tile_size[0] - tile.shape[0]),\n (0, self.tile_size[1] - tile.shape[1]),\n )\n tile = np.pad(tile, pad, 'constant')\n final_tile = np.zeros(\n (tile.shape[0], tile.shape[1], self.channels),\n dtype='uint8')\n\n final_tile[:, :, 0] = tile * 255\n final_tile[final_tile[:, :, 0] > 255 / 10,\n self.channels - 1] = 255\n yield final_tile\n\n def render(self, array: np.ndarray, filename: str):\n with tifffile.TiffWriter(filename, bigtiff=self.bigtiff) as tif:\n tif.save(self._tiles(array),\n dtype='uint8',\n shape=(array.shape[0], array.shape[1], self.channels),\n tile=self.tile_size,\n photometric='rgb' if self.rgb else 'minisblack',\n extrasamples=('ASSOCALPHA', ))\n\n\nclass BaseJSONEncoder(abc.ABC):\n @abc.abstractproperty\n def target(self):\n pass\n\n def encode(self, obj: Any):\n pass\n\n\nclass NumpyArrayJSONEncoder(BaseJSONEncoder):\n @property\n def target(self):\n return np.ndarray\n\n def encode(self, array: np.ndarray):\n return array.tolist()\n\n\nclass PolygonJSONEncoder(BaseJSONEncoder):\n @property\n def target(self):\n return Polygon\n\n def encode(self, obj: Polygon):\n return obj.coords\n\n\nclass Int64JSONEncoder(BaseJSONEncoder):\n @property\n def target(self):\n return np.int64\n\n def encode(self, int_: np.int64):\n return int(int_)\n\n\n# from https://github.com/hmallen/numpyencoder\ndef convert_numpy_types(obj):\n if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32,\n np.int64, np.uint8, np.uint16, np.uint32, np.uint64)):\n\n return int(obj)\n\n elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):\n return float(obj)\n\n elif isinstance(obj, (np.complex_, np.complex64, np.complex128)):\n return {'real': obj.real, 'imag': obj.imag}\n\n elif isinstance(obj, (np.ndarray, )):\n return obj.tolist()\n\n elif isinstance(obj, (np.bool_)):\n return bool(obj)\n\n elif isinstance(obj, (np.void)):\n return None\n return obj\n\n\nclass JSONEncoder(json.JSONEncoder):\n encoders = [NumpyArrayJSONEncoder(), PolygonJSONEncoder()]\n\n def default(self, obj):\n encoded = None\n for encoder in self.encoders:\n if isinstance(obj, encoder.target):\n encoded = encoder.encode(obj)\n break\n if encoded is None:\n encoded = super().default(obj)\n return encoded\n\n\nclass VectorialRenderer(Renderer):\n def render(self,\n slide: BasicSlide,\n filename: str,\n one_file_per_patch: bool = False):\n if one_file_per_patch:\n raise NotImplementedError()\n with open(filename, 'w') as json_file:\n json.dump(slide.patches, json_file, cls=JSONEncoder)\n\n\ndef to_json(obj: Any, filename: str = None) -> Union[str, None]:\n if filename is not None:\n with open(filename, 'w') as f:\n json.dump(obj, f, cls=JSONEncoder)\n else:\n return json.dumps(obj, cls=JSONEncoder)\n" ]
[ [ "numpy.zeros", "numpy.pad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ManuelaS/lifelines
[ "e48983550254625ab7e8a3747dd02b646a1bf7ad", "e48983550254625ab7e8a3747dd02b646a1bf7ad" ]
[ "perf_tests/cp_perf_test.py", "lifelines/fitters/aalen_additive_fitter.py" ]
[ "# -*- coding: utf-8 -*-\n# cox regression\n\n\nif __name__ == \"__main__\":\n import pandas as pd\n import time\n import numpy as np\n\n from lifelines import CoxPHFitter\n from lifelines.datasets import load_rossi, load_regression_dataset\n\n reps = 1\n df = load_rossi()\n df = pd.concat([df] * reps)\n cp_breslow = CoxPHFitter(penalizer=0.01, l1_ratio=0.0, baseline_estimation_method=\"breslow\")\n start_time = time.time()\n cp_breslow.fit(df, duration_col=\"week\", event_col=\"arrest\", show_progress=True)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n cp_breslow.print_summary(2)\n print(cp_breslow.score(df))\n print(cp_breslow.score(df, scoring_method=\"concordance_index\"))\n", "# -*- coding: utf-8 -*-\nimport warnings\nfrom datetime import datetime\nimport time\n\nimport numpy as np\nimport pandas as pd\nfrom numpy.linalg import LinAlgError\nfrom scipy.integrate import trapz\n\nfrom lifelines.fitters import RegressionFitter\nfrom lifelines.utils.printer import Printer\nfrom lifelines.utils import (\n _get_index,\n inv_normal_cdf,\n epanechnikov_kernel,\n ridge_regression as lr,\n qth_survival_times,\n check_for_numeric_dtypes_or_raise,\n concordance_index,\n check_nans_or_infs,\n ConvergenceWarning,\n normalize,\n string_justify,\n _to_list,\n format_floats,\n format_p_value,\n format_exp_floats,\n survival_table_from_events,\n StatisticalWarning,\n CensoringType,\n)\n\n\nclass AalenAdditiveFitter(RegressionFitter):\n\n r\"\"\"\n This class fits the regression model:\n\n .. math:: h(t|x) = b_0(t) + b_1(t) x_1 + ... + b_N(t) x_N\n\n that is, the hazard rate is a linear function of the covariates with time-varying coefficients.\n This implementation assumes non-time-varying covariates, see ``TODO: name``\n\n Note\n -----\n\n This class was rewritten in lifelines 0.17.0 to focus solely on static datasets.\n There is no guarantee of backwards compatibility.\n\n Parameters\n -----------\n fit_intercept: bool, optional (default: True)\n If False, do not attach an intercept (column of ones) to the covariate matrix. The\n intercept, :math:`b_0(t)` acts as a baseline hazard.\n alpha: float, optional (default=0.05)\n the level in the confidence intervals.\n coef_penalizer: float, optional (default: 0)\n Attach a L2 penalizer to the size of the coefficients during regression. This improves\n stability of the estimates and controls for high correlation between covariates.\n For example, this shrinks the magnitude of :math:`c_{i,t}`.\n smoothing_penalizer: float, optional (default: 0)\n Attach a L2 penalizer to difference between adjacent (over time) coefficients. For\n example, this shrinks the magnitude of :math:`c_{i,t} - c_{i,t+1}`.\n\n Attributes\n ----------\n cumulative_hazards_ : DataFrame\n The estimated cumulative hazard\n hazards_ : DataFrame\n The estimated hazards\n confidence_intervals_ : DataFrame\n The lower and upper confidence intervals for the cumulative hazard\n durations: array\n The durations provided\n event_observed: array\n The event_observed variable provided\n weights: array\n The event_observed variable provided\n \"\"\"\n _KNOWN_MODEL = True\n\n def __init__(self, fit_intercept=True, alpha=0.05, coef_penalizer=0.0, smoothing_penalizer=0.0):\n super(AalenAdditiveFitter, self).__init__(alpha=alpha)\n self.fit_intercept = fit_intercept\n self.alpha = alpha\n self.coef_penalizer = coef_penalizer\n self.smoothing_penalizer = smoothing_penalizer\n\n if not (0 < alpha <= 1.0):\n raise ValueError(\"alpha parameter must be between 0 and 1.\")\n if coef_penalizer < 0 or smoothing_penalizer < 0:\n raise ValueError(\"penalizer parameters must be >= 0.\")\n\n @CensoringType.right_censoring\n def fit(self, df, duration_col, event_col=None, weights_col=None, show_progress=False):\n \"\"\"\n Parameters\n ----------\n Fit the Aalen Additive model to a dataset.\n\n Parameters\n ----------\n df: DataFrame\n a Pandas DataFrame with necessary columns `duration_col` and\n `event_col` (see below), covariates columns, and special columns (weights).\n `duration_col` refers to\n the lifetimes of the subjects. `event_col` refers to whether\n the 'death' events was observed: 1 if observed, 0 else (censored).\n\n duration_col: string\n the name of the column in DataFrame that contains the subjects'\n lifetimes.\n\n event_col: string, optional\n the name of the column in DataFrame that contains the subjects' death\n observation. If left as None, assume all individuals are uncensored.\n\n weights_col: string, optional\n an optional column in the DataFrame, df, that denotes the weight per subject.\n This column is expelled and not used as a covariate, but as a weight in the\n final regression. Default weight is 1.\n This can be used for case-weights. For example, a weight of 2 means there were two subjects with\n identical observations.\n This can be used for sampling weights.\n\n show_progress: bool, optional (default=False)\n Since the fitter is iterative, show iteration number.\n\n\n Returns\n -------\n self: AalenAdditiveFitter\n self with additional new properties: ``cumulative_hazards_``, etc.\n\n Examples\n --------\n >>> from lifelines import AalenAdditiveFitter\n >>>\n >>> df = pd.DataFrame({\n >>> 'T': [5, 3, 9, 8, 7, 4, 4, 3, 2, 5, 6, 7],\n >>> 'E': [1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0],\n >>> 'var': [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2],\n >>> 'age': [4, 3, 9, 8, 7, 4, 4, 3, 2, 5, 6, 7],\n >>> })\n >>>\n >>> aaf = AalenAdditiveFitter()\n >>> aaf.fit(df, 'T', 'E')\n >>> aaf.predict_median(df)\n >>> aaf.print_summary()\n\n \"\"\"\n self._time_fit_was_called = datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\") + \" UTC\"\n\n df = df.copy()\n\n self.duration_col = duration_col\n self.event_col = event_col\n self.weights_col = weights_col\n\n self._n_examples = df.shape[0]\n\n X, T, E, weights = self._preprocess_dataframe(df)\n\n self.durations = T.copy()\n self.event_observed = E.copy()\n self.weights = weights.copy()\n\n self._norm_std = X.std(0)\n\n # if we included an intercept, we need to fix not divide by zero.\n if self.fit_intercept:\n self._norm_std[\"_intercept\"] = 1.0\n else:\n # a _intercept was provided\n self._norm_std[self._norm_std < 1e-8] = 1.0\n\n self.hazards_, self.cumulative_hazards_, self.cumulative_variance_ = self._fit_model(\n normalize(X, 0, self._norm_std), T, E, weights, show_progress\n )\n self.hazards_ /= self._norm_std\n self.cumulative_hazards_ /= self._norm_std\n self.cumulative_variance_ /= self._norm_std\n self.confidence_intervals_ = self._compute_confidence_intervals()\n\n self._index = self.hazards_.index\n\n self._predicted_hazards_ = self.predict_cumulative_hazard(X).iloc[-1].values.ravel()\n return self\n\n def _fit_model(self, X, T, E, weights, show_progress):\n\n columns = X.columns\n index = np.sort(np.unique(T[E]))\n\n hazards_, variance_hazards_, stop = self._fit_model_to_data_batch(\n X.values, T.values, E.values, weights.values, show_progress\n )\n\n hazards = pd.DataFrame(hazards_, columns=columns, index=index).iloc[:stop]\n cumulative_hazards_ = hazards.cumsum()\n cumulative_variance_hazards_ = (\n pd.DataFrame(variance_hazards_, columns=columns, index=index).iloc[:stop].cumsum()\n )\n\n return hazards, cumulative_hazards_, cumulative_variance_hazards_\n\n def _fit_model_to_data_batch(self, X, T, E, weights, show_progress):\n\n n, d = X.shape\n\n # we are mutating values of X, so copy it.\n X = X.copy()\n\n # iterate over all the unique death times\n unique_death_times = np.sort(np.unique(T[E]))\n n_deaths = unique_death_times.shape[0]\n total_observed_exits = 0\n\n hazards_ = np.zeros((n_deaths, d))\n variance_hazards_ = np.zeros((n_deaths, d))\n v = np.zeros(d)\n start = time.time()\n\n W = np.sqrt(weights)\n X = W[:, None] * X\n\n for i, t in enumerate(unique_death_times):\n\n exits = T == t\n deaths = exits & E\n try:\n v, V = lr(X, W * deaths, c1=self.coef_penalizer, c2=self.smoothing_penalizer, offset=v, ix=deaths)\n except LinAlgError:\n warnings.warn(\n \"Linear regression error at index=%d, time=%.3f. Try increasing the coef_penalizer value.\" % (i, t),\n ConvergenceWarning,\n )\n v = np.zeros_like(v)\n V = np.zeros_like(V)\n\n hazards_[i, :] = v\n\n variance_hazards_[i, :] = (V ** 2).sum(1)\n\n X[exits, :] = 0\n\n if show_progress and i % int((n_deaths / 10)) == 0:\n print(\"\\rIteration %d/%d, seconds_since_start = %.2f\" % (i + 1, n_deaths, time.time() - start), end=\"\")\n\n last_iteration = i + 1\n # terminate early when there are less than (3 * d) subjects left, where d does not include the intercept.\n # the value 3 if from R survival lib.\n if (3 * (d - 1)) >= n - total_observed_exits:\n if show_progress:\n print(\"Terminating early due to too few subjects remaining. This is expected behaviour.\")\n break\n\n total_observed_exits += exits.sum()\n\n if show_progress:\n print(\"Convergence completed.\")\n return hazards_, variance_hazards_, last_iteration\n\n def _preprocess_dataframe(self, df):\n n, _ = df.shape\n\n df = df.sort_values(by=self.duration_col)\n\n # Extract time and event\n T = df.pop(self.duration_col)\n E = df.pop(self.event_col) if (self.event_col is not None) else pd.Series(np.ones(n), index=df.index, name=\"E\")\n W = (\n df.pop(self.weights_col)\n if (self.weights_col is not None)\n else pd.Series(np.ones((n,)), index=df.index, name=\"weights\")\n )\n\n # check to make sure their weights are okay\n if self.weights_col:\n if (W.astype(int) != W).any():\n warnings.warn(\n \"\"\"It appears your weights are not integers, possibly propensity or sampling scores then?\nIt's important to know that the naive variance estimates of the coefficients are biased.\"\n\"\"\",\n StatisticalWarning,\n )\n if (W <= 0).any():\n raise ValueError(\"values in weight column %s must be positive.\" % self.weights_col)\n\n X = df.astype(float)\n T = T.astype(float)\n\n check_nans_or_infs(E)\n E = E.astype(bool)\n\n self._check_values(df, T, E)\n\n if self.fit_intercept:\n assert (\n \"_intercept\" not in df.columns\n ), \"_intercept is an internal lifelines column, please rename your column first.\"\n X[\"_intercept\"] = 1.0\n\n return X, T, E, W\n\n def predict_cumulative_hazard(self, X):\n \"\"\"\n Returns the hazard rates for the individuals\n\n Parameters\n ----------\n X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns\n can be in any order. If a numpy array, columns must be in the\n same order as the training data.\n\n \"\"\"\n n = X.shape[0]\n X = X.astype(float)\n\n cols = _get_index(X)\n if isinstance(X, pd.DataFrame):\n order = self.cumulative_hazards_.columns\n order = order.drop(\"_intercept\") if self.fit_intercept else order\n X_ = X[order].values\n elif isinstance(X, pd.Series):\n return self.predict_cumulative_hazard(X.to_frame().T)\n else:\n X_ = X\n\n X_ = X_ if not self.fit_intercept else np.c_[X_, np.ones((n, 1))]\n\n timeline = self._index\n individual_cumulative_hazards_ = pd.DataFrame(\n np.dot(self.cumulative_hazards_, X_.T), index=timeline, columns=cols\n )\n\n return individual_cumulative_hazards_\n\n def _check_values(self, X, T, E):\n check_for_numeric_dtypes_or_raise(X)\n check_nans_or_infs(T)\n check_nans_or_infs(X)\n\n def predict_survival_function(self, X, times=None):\n \"\"\"\n Returns the survival functions for the individuals\n\n Parameters\n ----------\n X: a (n,d) covariate numpy array or DataFrame\n If a DataFrame, columns\n can be in any order. If a numpy array, columns must be in the\n same order as the training data.\n times:\n Not implemented yet\n\n \"\"\"\n return np.exp(-self.predict_cumulative_hazard(X))\n\n def predict_percentile(self, X, p=0.5) -> pd.Series:\n \"\"\"\n Returns the median lifetimes for the individuals.\n http://stats.stackexchange.com/questions/102986/percentile-loss-functions\n\n Parameters\n ----------\n X: a (n,d) covariate numpy array or DataFrame\n If a DataFrame, columns\n can be in any order. If a numpy array, columns must be in the\n same order as the training data.\n p: float\n default: 0.5\n\n \"\"\"\n index = _get_index(X)\n return qth_survival_times(p, self.predict_survival_function(X)[index]).T.squeeze()\n\n def predict_median(self, X) -> pd.Series:\n \"\"\"\n\n Parameters\n ----------\n X: a (n,d) covariate numpy array or DataFrame\n If a DataFrame, columns\n can be in any order. If a numpy array, columns must be in the\n same order as the training data.\n\n Returns the median lifetimes for the individuals\n \"\"\"\n return self.predict_percentile(X, 0.5)\n\n def predict_expectation(self, X) -> pd.Series:\n \"\"\"\n Compute the expected lifetime, E[T], using covariates X.\n\n Parameters\n ----------\n X: a (n,d) covariate numpy array or DataFrame\n If a DataFrame, columns\n can be in any order. If a numpy array, columns must be in the\n same order as the training data.\n\n Returns the expected lifetimes for the individuals\n \"\"\"\n index = _get_index(X)\n t = self._index\n return pd.Series(trapz(self.predict_survival_function(X)[index].values.T, t), index=index)\n\n def _compute_confidence_intervals(self):\n ci = 100 * (1 - self.alpha)\n z = inv_normal_cdf(1 - self.alpha / 2)\n std_error = np.sqrt(self.cumulative_variance_)\n return pd.concat(\n {\n \"%g%% lower-bound\" % ci: self.cumulative_hazards_ - z * std_error,\n \"%g%% upper-bound\" % ci: self.cumulative_hazards_ + z * std_error,\n }\n )\n\n def plot(self, columns=None, loc=None, iloc=None, ax=None, **kwargs):\n \"\"\"\"\n A wrapper around plotting. Matplotlib plot arguments can be passed in, plus:\n\n Parameters\n -----------\n columns: string or list-like, optional\n If not empty, plot a subset of columns from the ``cumulative_hazards_``. Default all.\n loc:\n\n iloc: slice, optional\n specify a location-based subsection of the curves to plot, ex:\n ``.plot(iloc=slice(0,10))`` will plot the first 10 time points.\n \"\"\"\n from matplotlib import pyplot as plt\n\n assert loc is None or iloc is None, \"Cannot set both loc and iloc in call to .plot\"\n\n def shaded_plot(ax, x, y, y_upper, y_lower, **kwargs):\n (base_line,) = ax.plot(x, y, drawstyle=\"steps-post\", **kwargs)\n ax.fill_between(x, y_lower, y2=y_upper, alpha=0.25, color=base_line.get_color(), linewidth=1.0, step=\"post\")\n\n def create_df_slicer(loc, iloc):\n get_method = \"loc\" if loc is not None else \"iloc\"\n\n if iloc is None and loc is None:\n user_submitted_ix = slice(0, None)\n else:\n user_submitted_ix = loc if loc is not None else iloc\n\n return lambda df: getattr(df, get_method)[user_submitted_ix]\n\n subset_df = create_df_slicer(loc, iloc)\n\n if not columns:\n columns = self.cumulative_hazards_.columns\n else:\n columns = _to_list(columns)\n\n if ax is None:\n ax = plt.gca()\n\n x = subset_df(self.cumulative_hazards_).index.values.astype(float)\n\n for column in columns:\n ci = (1 - self.alpha) * 100\n y = subset_df(self.cumulative_hazards_[column]).values\n index = subset_df(self.cumulative_hazards_[column]).index\n y_upper = subset_df(self.confidence_intervals_[column].loc[\"%g%% upper-bound\" % ci]).values\n y_lower = subset_df(self.confidence_intervals_[column].loc[\"%g%% lower-bound\" % ci]).values\n shaded_plot(ax, x, y, y_upper, y_lower, label=column, **kwargs)\n\n plt.hlines(0, index.min() - 1, index.max(), color=\"k\", linestyles=\"--\", alpha=0.5)\n\n ax.legend()\n return ax\n\n def smoothed_hazards_(self, bandwidth=1):\n \"\"\"\n Using the epanechnikov kernel to smooth the hazard function, with sigma/bandwidth\n\n \"\"\"\n timeline = self._index.values\n return pd.DataFrame(\n np.dot(epanechnikov_kernel(timeline[:, None], timeline, bandwidth), self.hazards_.values),\n columns=self.hazards_.columns,\n index=timeline,\n )\n\n @property\n def score_(self):\n \"\"\"\n The concordance score (also known as the c-index) of the fit. The c-index is a generalization of the ROC AUC\n to survival data, including censorships.\n\n For this purpose, the ``score_`` is a measure of the predictive accuracy of the fitted model\n onto the training dataset. It's analogous to the R^2 in linear models.\n\n \"\"\"\n # pylint: disable=access-member-before-definition\n if hasattr(self, \"_predicted_hazards_\"):\n self._concordance_score_ = concordance_index(self.durations, -self._predicted_hazards_, self.event_observed)\n del self._predicted_hazards_\n return self._concordance_score_\n return self._concordance_score_\n\n def _compute_slopes(self):\n def _univariate_linear_regression_without_intercept(X, Y, weights):\n # normally (weights * X).dot(Y) / X.dot(weights * X), but we have a slightly different form here.\n beta = X.dot(Y) / X.dot(weights * X)\n errors = Y.values - np.outer(X, beta)\n var = (errors ** 2).sum(0) / (Y.shape[0] - 2) / X.dot(weights * X)\n return beta, np.sqrt(var)\n\n weights = survival_table_from_events(self.durations, self.event_observed).loc[self._index, \"at_risk\"].values\n y = (weights[:, None] * self.hazards_).cumsum()\n X = self._index.values\n betas, se = _univariate_linear_regression_without_intercept(X, y, weights)\n return pd.Series(betas, index=y.columns), pd.Series(se, index=y.columns)\n\n @property\n def summary(self):\n \"\"\"Summary statistics describing the fit.\n\n Returns\n -------\n df : DataFrame\n \"\"\"\n df = pd.DataFrame(index=self.cumulative_hazards_.columns)\n\n betas, se = self._compute_slopes()\n df[\"slope(coef)\"] = betas\n df[\"se(slope(coef))\"] = se\n return df\n\n def print_summary(self, decimals=2, style=None, **kwargs):\n \"\"\"\n Print summary statistics describing the fit, the coefficients, and the error bounds.\n\n Parameters\n -----------\n decimals: int, optional (default=2)\n specify the number of decimal places to show\n style: string\n {html, ascii, latex}\n kwargs:\n print additional meta data in the output (useful to provide model names, dataset names, etc.) when comparing\n multiple outputs.\n\n \"\"\"\n justify = string_justify(25)\n\n headers = []\n headers.append((\"duration col\", \"'%s'\" % self.duration_col))\n\n if self.event_col:\n headers.append((\"event col\", \"'%s'\" % self.event_col))\n if self.weights_col:\n headers.append((\"weights col\", \"'%s'\" % self.weights_col))\n if self.coef_penalizer > 0:\n headers.append((\"coef penalizer\", self.coef_penalizer))\n if self.smoothing_penalizer > 0:\n headers.append((\"smoothing penalizer\", self.smoothing_penalizer))\n\n headers.extend(\n [\n (\"number of subjects\", self._n_examples),\n (\"number of events observed\", self.event_observed.sum()),\n (\"time fit was run\", self._time_fit_was_called),\n ]\n )\n\n p = Printer(self, headers, justify, decimals, kwargs)\n\n p.print(style=style)\n\n def score(self, df: pd.DataFrame, scoring_method: str = \"log_likelihood\") -> float:\n \"\"\"\n Score the data in df on the fitted model. With default scoring method, returns\n the *average partial log-likelihood*.\n\n Parameters\n ----------\n df: DataFrame\n the dataframe with duration col, event col, etc.\n scoring_method: str\n one of {'log_likelihood', 'concordance_index'}\n log_likelihood: returns the average unpenalized partial log-likelihood.\n concordance_index: returns the concordance-index\n \"\"\"\n if scoring_method == \"log_likelihood\":\n raise NotImplementedError(\"Only concordance_index is available\")\n\n T = df.pop(self.duration_col).astype(float)\n E = df.pop(self.event_col).astype(bool)\n\n predictions = self.predict_median(df)\n return concordance_index(T, predictions, event_observed=E)\n" ]
[ [ "pandas.concat" ], [ "numpy.dot", "pandas.concat", "matplotlib.pyplot.gca", "numpy.sqrt", "pandas.Series", "numpy.unique", "pandas.DataFrame", "numpy.ones", "numpy.zeros_like", "numpy.outer", "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": [] }, { "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": [] } ]
GCrispino/vi-pddlgym
[ "2401cdbb1590cd0ebab5a3d75549c63aa130ee24" ]
[ "mdp.py" ]
[ "import numpy as np\nfrom pddlgym.core import get_successor_states, InvalidAction\nfrom pddlgym.inference import check_goal\n\n\ndef get_all_reachable(s, A, env, reach=None):\n reach = {} if not reach else reach\n\n reach[s] = {}\n for a in A:\n try:\n succ = get_successor_states(s,\n a,\n env.domain,\n raise_error_on_invalid_action=True,\n return_probs=True)\n except InvalidAction:\n succ = {s: 1.0}\n reach[s][a] = {s_: prob for s_, prob in succ.items()}\n for s_ in succ:\n if s_ not in reach:\n reach.update(get_all_reachable(s_, A, env, reach))\n return reach\n\n\ndef vi(S, succ_states, A, V_i, G_i, goal, env, gamma, epsilon):\n\n V = np.zeros(len(V_i))\n P = np.zeros(len(V_i))\n pi = np.full(len(V_i), None)\n print(len(S), len(V_i), len(G_i), len(P))\n print(G_i)\n P[G_i] = 1\n\n i = 0\n diff = np.inf\n while True:\n print('Iteration', i, diff)\n V_ = np.copy(V)\n P_ = np.copy(P)\n\n for s in S:\n if check_goal(s, goal):\n continue\n Q = np.zeros(len(A))\n Q_p = np.zeros(len(A))\n cost = 1\n for i_a, a in enumerate(A):\n succ = succ_states[s, a]\n\n probs = np.fromiter(iter(succ.values()), dtype=float)\n succ_i = [V_i[succ_s] for succ_s in succ_states[s, a]]\n Q[i_a] = cost + np.dot(probs, gamma * V_[succ_i])\n Q_p[i_a] = np.dot(probs, P_[succ_i])\n V[V_i[s]] = np.min(Q)\n P[V_i[s]] = np.max(Q_p)\n pi[V_i[s]] = A[np.argmin(Q)]\n\n diff = np.linalg.norm(V_ - V, np.inf)\n if diff < epsilon:\n break\n i += 1\n return V, pi\n" ]
[ [ "numpy.dot", "numpy.min", "numpy.linalg.norm", "numpy.max", "numpy.copy", "numpy.argmin" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hanghu/AutoChemCluster
[ "2ab4ae996b300a90637b124707905201c89d74d8" ]
[ "deepchembed/dce.py" ]
[ "\"\"\"\nDeepChEmbed (DCE) Models\n\"\"\"\nfrom dimreducer import DeepAutoEncoder\nfrom cluster import KMeansLayer\nfrom cluster import KMeans\nfrom keras import Model\nfrom keras import optimizers\nfrom keras.utils import normalize\nimport numpy as np\n\nclass DCE():\n \"\"\"\n The class to build a deep chemical embedding model.\n\n Attributes:\n autoencoder_dims: a list of dimensions for encoder, the first\n element as input dimension, and the last one as\n hidden layer dimension.\n n_clusters: int, number of clusters for clustering layer.\n alpha: float, parameters for soft label assigning.\n update_interval: int, indicating every number of epoches, the harhened\n labels will be upadated and/or convergence cretia will\n be examed.\n max_iteration: int, maximum iteration for the combined training\n clustering_tol: float, convergence cretia for clustering layer\n model: keras Model variable\n HARDENING_FUNCS: smoothsetp hardening functions for unsupervised DCE\n training, up to 9th order\n \"\"\"\n\n HARDENING_FUNCS = {\n 1: lambda x: x,\n 3: lambda x: (-2*x + 3) * x**2,\n 5: lambda x: ((6*x - 15)*x + 10) * x**3,\n 7: lambda x: (((-20*x + 70)*x - 84)*x + 35) * x**4,\n 9: lambda x: ((((70*x - 315)*x + 540)*x -420)*x + 126) * x**5}\n\n def __init__(self, autoencoder_dims, n_clusters, update_interval=50,\n max_iteration=1e4, clustering_tol=1e-4, alpha=1.0):\n \"\"\"Construtor of DCE. \"\"\"\n self.autoencoder_dims = autoencoder_dims\n self.n_clusters = n_clusters\n self.alpha = alpha\n self.update_interval = update_interval\n self.max_iteration = max_iteration\n self.clustering_tol = clustering_tol\n self.model = None\n\n return\n\n def build_model(self, norm=True, act='relu'):\n \"\"\"Build DCE using the initialized attributes\n\n Args:\n norm: boolean, wheher to add a normalization layer at the begining\n of the autoencoder\n act: string, keras activation function name for autoencoder\n \"\"\"\n autoencoder = DeepAutoEncoder(self.autoencoder_dims, act)\n autoencoder.build_model(norm=norm)\n embeding = autoencoder.model.get_layer(name='embedding_layer').output\n clustering = KMeansLayer(self.n_clusters, alpha=self.alpha,\n name='clustering')(embeding)\n self.model = Model(inputs=autoencoder.model.input,\n outputs=[clustering,autoencoder.model.output])\n\n return\n\n def train_model(self, data_train,\n labels_train=None, data_test=None, labels_test=None,\n verbose=1,\n compiled=False, clustering_loss='kld',\n decoder_loss='mse',clustering_loss_weight=0.5,\n hardening_order=1, hardening_strength=2.0,\n compiled=False,\n optimizer='adam', lr=0.001, decay=0.0):\n \"\"\"Train DCE Model:\n\n If labels_train are not present, train DCE model in a unsupervised\n learning process; otherwise, train DCE model in a supervised learning\n process.\n\n Args:\n data_train: input training data\n labels_train: true labels of traning data\n data_test: input test data\n labels_test: true lables of testing data\n verbose: 0, turn off the screen prints\n clustering_loss: string, clustering layer loss function\n decoder_loss:, string, decoder loss function\n clustering_loss_weight: float in [0,1], w_c,\n harderning_order: odd int, the order of hardening function\n harderning_strength: float >=1.0, the streng of the harderning\n compiled: boolean, indicating if the model is compiled or not\n optmizer: string, keras optimizers\n lr: learning rate\n dacay: learning rate dacay\n\n Returns:\n train_loss: training loss\n test_loss: only if data_test and labels_test are not None in\n supervised learning process\n \"\"\"\n if (not compiled):\n assert clustering_loss_weight <= 1 and clustering_loss_weight >= 0\n\n if optimizer == 'adam':\n dce_optimizer = optimizers.Adam(lr=lr,decay=decay)\n elif optimizer == 'sgd':\n dce_optimizer = optimizers.sgd(lr=lr,decay=decay)\n else:\n raise Exception('Input optimizer was not found')\n\n self.model.compile(loss={'clustering': clustering_loss,\n 'decoder_output': decoder_loss},\n loss_weights=[clustering_loss_weight,\n 1 - clustering_loss_weight],\n optimizer=dce_optimizer)\n\n if (labels_train is not None):\n supervised_learning = True\n if verbose >= 1: print('Starting supervised learning')\n else:\n supervised_learning = False\n if verbose >= 1: print('Starting unsupervised learning')\n\n # initializing model by using sklean-Kmeans as guess\n kmeans_init = KMeans(n_clusters=self.n_clusters)\n kmeans_init.build_model()\n encoder = Model(inputs=self.model.input,\n outputs=self.model.get_layer(\\\n name='embedding_layer').output)\n kmeans_init.model.fit(encoder.predict(data_train))\n y_pred_last = kmeans_init.model.labels_\n self.model.get_layer(name='clustering').\\\n set_weights([kmeans_init.model.cluster_centers_])\n\n # Prepare training: p disctribution methods\n if not supervised_learning:\n # Unsupervised Learning\n assert hardening_order in DCE.HARDENING_FUNCS.keys()\n assert hardening_strength >= 1.0\n h_func = DCE.HARDENING_FUNCS[hardening_order]\n else:\n # Supervised Learning\n assert len(labels_train) == len(data_train)\n assert len(np.unique(labels_train)) == self.n_clusters\n p = np.zeros(shape=(len(labels_train), self.n_clusters))\n for i in range(len(labels_train)):\n p[i][labels_train[i]] = 1.0\n\n if data_test is not None:\n assert len(labels_test) == len(data_test)\n assert len(np.unique(labels_test)) == self.n_clusters\n p_test = np.zeros(shape=(len(labels_test), self.n_clusters))\n for i in range(len(labels_test)):\n p_test[i][labels_test[i]] = 1.0\n\n validation_loss = []\n\n # training start:\n loss = []\n\n for iteration in range(int(self.max_iteration)):\n\n if iteration % self.update_interval == 0:\n # updating p for unsupervised learning process\n q, _ = self.model.predict(data_train)\n if not supervised_learning:\n p = DCE.hardening(q, h_func, hardening_strength)\n\n # get label change i\n y_pred = q.argmax(1)\n delta_label_i = np.sum(y_pred != y_pred_last).\\\n astype(np.float32) / y_pred.shape[0]\n y_pred_last = y_pred\n\n # exam convergence\n if iteration > 0 and delta_label_i < self.clustering_tol:\n print(str(delta_label_i) +' < ' + str(self.clustering_tol))\n print('Reached tolerance threshold. Stopping training.')\n break\n\n loss.append(self.model.train_on_batch(x=data_train,\n y=[p,data_train]))\n if supervised_learning and data_test is not None:\n validation_loss.append(self.model.test_on_batch(\n x=data_test, y=[p_test,data_test]))\n\n if verbose > 0 and iteration % self.update_interval == 0:\n print('Epoch: ' + str(iteration))\n if verbose == 1:\n print(' Total_loss = ' + str(loss[iteration][0]) +\n ';Delta_label = ' + str(delta_label_i))\n print(' Clustering_loss = ' + str(loss[iteration][1]) +\n '; Decoder_loss = ' + str(loss[iteration][2]))\n\n if iteration == self.max_iteration - 1:\n print('Reached maximum iteration. Stopping training.')\n\n if data_test is None:\n return np.array(loss).T\n else:\n return [np.array(loss).T, np.array(validation_loss).T]\n\n @staticmethod\n def hardening(q, h_func, stength):\n \"\"\"hardening distribution P and return Q\n\n Args:\n q: input distributions.\n h_func: input harderning function.\n strength: hardening strength.\n\n returns:\n p: hardened and normatlized distributions.\n\n \"\"\"\n q = h_func(q)\n weight = q ** stength / q.sum(0)\n return (weight.T / weight.sum(1)).T\n" ]
[ [ "numpy.array", "numpy.sum", "numpy.unique" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zivaharoni/capacity-rl
[ "20ed628b3bc9f3b08996f289e7855121f3addf71" ]
[ "result_buffer.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport csv\nimport os\nimport scipy.io as mat4py\nimport logging\n\nlogger = logging.getLogger(\"logger\")\n\nclass ResultBuffer(object):\n def __init__(self, log_path, episode_types):\n self.log_path = log_path\n self.current_episode = None\n\n self.episodes = {e_type: list() for e_type in episode_types}\n\n self.average_reward = 0.0\n self.initial_reward = 0.0\n self.average_reward_counter = 0\n self.n_cluster = 0\n\n for episode_type in self.episodes.keys():\n with open(os.path.join(self.log_path,'{}.csv'.format(episode_type)), mode='w') as result_file:\n writer = csv.writer(result_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(self.title_csv())\n\n def update_episode(self, **kwargs):\n if self.current_episode is None:\n raise ValueError(\"There is no initiated episodes object\")\n\n self.current_episode.add(**kwargs)\n\n def add_episode(self, episode_type, lr, noise_std, buffer_size):\n if episode_type in self.episodes.keys():\n idx = len(self.episodes[episode_type])\n episode_name = \"{}_{:03d}\".format(episode_type,idx)\n self.episodes[episode_type].append(Episode(episode_name, lr, noise_std, buffer_size, self.average_reward))\n self.current_episode = self.episodes[episode_type][-1]\n else:\n raise ValueError(\"Invalid episode type added to result buffer\")\n\n def finalize_episode(self, update_average_reward=None):\n self.current_episode.summarize()\n\n if update_average_reward is not None:\n new_average = self.current_episode.final_stats['online_rewards']\n if np.abs(new_average-self.initial_reward) > 0.05:\n self.initial_reward = new_average\n self.average_reward_counter = 0\n self.average_reward = (self.average_reward_counter * self.average_reward + new_average) / (self.average_reward_counter + 1)\n self.average_reward_counter += 1\n\n logger.info(self.current_episode)\n self.write_all()\n\n def write_all(self):\n for episode_type in self.episodes.keys():\n with open(os.path.join(self.log_path,'{}.csv'.format(episode_type)), mode='a') as result_file:\n writer = csv.writer(result_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n for i, episode in enumerate(self.episodes[episode_type]):\n if episode is not None:\n if \"eval\" in episode.name:\n try:\n episode.save(self.log_path)\n except:\n logger.info(\"Saving state evolution failed\")\n\n writer.writerow(episode.csv())\n self.episodes[episode_type][i] = None\n\n @staticmethod\n def title():\n text = list()\n text.append('{:^20}'.format('Epi'))\n text.append('{:^10}'.format('time'))\n text.append('{:^9}'.format('lr'))\n text.append('{:^9}'.format('noise'))\n text.append('{:^12}'.format('buffer size'))\n text.append('{:^9}'.format('#of updates'))\n text.append('{:^20}'.format('average_reward'))\n text.append('{:^20}'.format('actor grad norm'))\n text.append('{:^20}'.format('critic grad norm'))\n text.append('{:^9}'.format('q_loss'))\n text.append('{:^6}'.format('rewards'))\n\n return \" | \".join(text)\n\n @staticmethod\n def title_csv():\n text = list()\n text.append('{}'.format('Epi'))\n text.append('{}'.format('time'))\n text.append('{}'.format('lr'))\n text.append('{}'.format('noise'))\n text.append('{}'.format('buffer size'))\n text.append('{}'.format('#of updates'))\n text.append('{}'.format('average_reward'))\n text.append('{}'.format('actor grad norm'))\n text.append('{}'.format('critic grad norm'))\n text.append('{}'.format('q_loss'))\n text.append('{}'.format('rewards'))\n\n return text\n\n\nclass Episode(object):\n def __init__(self, name, lr, noise_std, buffer_size, average_reward):\n # general stats\n self.name = name\n self.average_reward = average_reward\n self.lr = lr\n self.noise_std = noise_std\n self.buffer_size = buffer_size\n self.total_time = time.time()\n\n # training stats\n self.stats = dict()\n\n self.final_stats = dict()\n\n\n def add(self, **kwargs):\n for key,val in kwargs.items():\n if key not in self.stats.keys():\n self.stats[key] = list()\n self.stats[key].append(val)\n\n def summarize(self):\n # updates counter\n if 'global_step_critic' in self.stats.keys():\n self.final_stats['global_step'] = self.stats['global_step_critic']\n\n # average rewards\n if 'online_rewards' in self.stats.keys():\n self.stats['online_rewards'] = np.array(self.stats['online_rewards'])\n self.stats['online_rewards'] = np.reshape(self.stats['online_rewards'], [self.stats['online_rewards'].shape[1], -1])\n self.final_stats['online_rewards'] = np.mean(self.stats['online_rewards'][:,10:])\n\n # value function error\n if 'q_loss' in self.stats.keys():\n self.final_stats['q_loss'] = np.mean(self.stats['q_loss'])\n\n # state/action/disturbance evolution\n if 'states' in self.stats.keys():\n self.final_stats['states'] = np.transpose(np.squeeze(np.array(self.stats['states'])))\n if 'actions' in self.stats.keys():\n self.final_stats['actions'] = np.swapaxes(np.array(self.stats['actions']), 0, 1)\n if 'disturbance' in self.stats.keys():\n self.final_stats['disturbance'] = np.transpose(np.array(self.stats['disturbance']))\n\n # gradient stats\n if 'g_norm_critic' in self.stats.keys():\n self.final_stats['g_norm_critic'] = (np.mean(np.squeeze(np.array(self.stats['g_norm_critic']))),\n np.min(np.squeeze(np.array(self.stats['g_norm_critic']))),\n np.max(np.squeeze(np.array(self.stats['g_norm_critic']))))\n\n if 'g_norm_actor' in self.stats.keys():\n self.final_stats['g_norm_actor'] = (np.mean(np.squeeze(np.array(self.stats['g_norm_actor']))),\n np.min(np.squeeze(np.array(self.stats['g_norm_actor']))),\n np.max(np.squeeze(np.array(self.stats['g_norm_actor']))))\n\n if 'global_step_actor' in self.stats.keys():\n self.final_stats['global_step'] = self.stats['global_step_actor'][-1]\n\n self.total_time = time.time() - self.total_time\n\n del self.stats\n\n def save(self, path):\n mat4py.savemat(os.path.join(path, \"states\", 'states_evol.mat'), {'states': self.final_stats['states']})\n mat4py.savemat(os.path.join(path, \"states\", 'actions_evol.mat'), {'actions': self.final_stats['actions']})\n mat4py.savemat(os.path.join(path, \"states\", 'outputs_evol.mat'), {'disturbance': self.final_stats['disturbance']})\n\n def csv(self):\n text = list()\n text.append('{}'.format(self.name))\n text.append('{:.1f}'.format(self.total_time))\n if \"eval\" not in self.name:\n text.append('{:.2e}'.format(self.lr))\n text.append('{:.2e}'.format(self.noise_std))\n text.append('{}'.format(self.buffer_size))\n text.append('{}'.format(self.final_stats['global_step']))\n\n text.append('{:^20}'.format(self.average_reward))\n if \"eval\" not in self.name:\n text.append('{}'.format(self.final_stats['g_norm_actor']))\n text.append('{}'.format(self.final_stats['g_norm_critic']))\n text.append('{:.2e}'.format(self.final_stats['q_loss']))\n text.append('{:.5f}'.format(self.final_stats['online_rewards']))\n\n return text\n\n def __repr__(self):\n text = list()\n text.append('{:^20}'.format(self.name))\n text.append('{:^10.1f}'.format(self.total_time))\n if \"eval\" not in self.name:\n text.append('{:^9.2e}'.format(self.lr))\n text.append('{:^9.2e}'.format(self.noise_std))\n text.append('{:^d}'.format(self.buffer_size))\n text.append('{}'.format(self.final_stats['global_step']))\n\n text.append('{:^20}'.format(self.average_reward))\n if \"eval\" not in self.name:\n mi, ma, mea = self.final_stats['g_norm_actor']\n text.append('{:5.2e},{:5.2e},{:5.2e}'.format(mi, ma, mea))\n mi, ma, mea = self.final_stats['g_norm_critic']\n text.append('{:5.2e},{:5.2e},{:5.2e}'.format(mi, ma, mea))\n text.append('{:^10.2e}'.format(self.final_stats['q_loss']))\n\n if \"pol\" in self.name:\n mi, ma, mea = self.final_stats['g_norm_critic']\n text.append('{:5.2e},{:5.2e},{:5.2e}'.format(mi, ma, mea))\n text.append('{:^10.2e}'.format(self.final_stats['q_loss']))\n if len(self.final_stats.keys()) > 0 :\n text.append('{:^6.5f}'.format(self.final_stats['online_rewards']))\n\n return \" | \".join(text)\n\n\nclass Figure(object):\n def __init__(self, name, log_path, y_data, x_data=None, options = None, labels = None):\n self.fig = plt.figure()\n self.fig.set_size_inches(18.5, 10.5)\n\n for y in y_data:\n plt.plot(x_data, y)\n\n plt.legend(labels)\n plt.title(\" \".join(name.split(\"_\")))\n\n self.fig.savefig(os.path.join(log_path, \"plots\", name))\n plt.close()\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.abs", "numpy.reshape", "matplotlib.pyplot.plot", "numpy.mean", "matplotlib.pyplot.close", "numpy.array", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kmunve/APS
[ "4c2f254ede83a3a311cbedc90c76db9ee367a000" ]
[ "aps/load_region.py" ]
[ "import os\nimport numpy as np\nfrom netCDF4 import Dataset\n\n\ndef load_region(region_id, local=False, return_regions=False):\n\n if local:\n _vr = Dataset(\n os.path.join(os.path.dirname(os.path.abspath(__file__)), r\"data/terrain_parameters/VarslingsOmr_2017.nc\"),\n \"r\")\n # flip up-down because Meps data is upside down\n #_regions = np.flipud(_vr.variables[\"LokalOmr_2018\"][:])\n _regions = _vr.variables[\"LokalOmr_2018\"][:]\n else:\n _vr = Dataset(\n os.path.join(os.path.dirname(os.path.abspath(__file__)), r\"data/terrain_parameters/VarslingsOmr_2019.nc\"),\n \"r\")\n # flip up-down because Meps data is upside down\n #_regions = np.flipud(_vr.variables[\"skredomr19_km\"][:])\n _regions = _vr.variables[\"skredomr19_km\"][:]\n print(\"Missing value: {mv}\".format(mv=_vr.variables[\"skredomr19_km\"].missing_value))\n\n _region_bounds = np.where(_regions == region_id) # just to get the bounding box\n\n # get the lower left and upper right corner of a rectangle around the region\n y_min, y_max, x_min, x_max = min(_region_bounds[0].flatten()), max(_region_bounds[0].flatten()), \\\n min(_region_bounds[1].flatten()), max(_region_bounds[1].flatten())\n\n #reg_mask = np.ma.masked_where(_regions[y_min:y_max, x_min:x_max] == region_id, _regions[y_min:y_max, x_min:x_max]).mask\n #reg_mask = np.where(_regions[y_min:y_max, x_min:x_max] == region_id, _regions[y_min:y_max, x_min:x_max], np.nan)\n reg_mask = np.where(_regions[y_min:y_max, x_min:x_max] == region_id, 1., np.nan)\n #reg_mask = np.ma.masked_where(_reg_mask == region_id).mask\n _vr.close()\n\n if return_regions:\n return _regions, reg_mask, y_min, y_max, x_min, x_max\n else:\n return reg_mask, y_min, y_max, x_min, x_max\n\n\ndef clip_region(nc_variable, region_mask, t_index, y_min, y_max, x_min, x_max):\n s = len(nc_variable.shape)\n\n if s == 2:\n #return np.flipud(region_mask * nc_variable[y_min:y_max, x_min:x_max])\n return (region_mask * nc_variable[y_min:y_max, x_min:x_max])\n elif s == 3:\n #return np.flipud(region_mask * nc_variable[t_index, y_min:y_max, x_min:x_max])\n return (region_mask * nc_variable[t_index, y_min:y_max, x_min:x_max])\n elif s == 4:\n #return np.flipud(region_mask * nc_variable[t_index, 0, y_min:y_max, x_min:x_max])\n return (region_mask * nc_variable[t_index, 0, y_min:y_max, x_min:x_max])\n else:\n print('Input array needs to have 2- to 4-dimensions: {0} were given.'.format(s))\n\n\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n\n regions, region_mask, y_min, y_max, x_min, x_max = load_region(3013, return_regions=True)\n print(region_mask, type(region_mask), np.unique(region_mask))\n clp = clip_region(regions, region_mask, 0, y_min, y_max, x_min, x_max)\n plt.imshow(clp)\n plt.show()\n\n k = 'm'" ]
[ [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.show", "numpy.where", "numpy.unique" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Wowol/Piano-Bot
[ "feab884daa4bbe947bf6d95d816664eb7e46cc48" ]
[ "model.py" ]
[ "from tensorflow.keras.callbacks import LambdaCallback\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Activation, LSTM\nfrom tensorflow.keras.layers import Dropout, TimeDistributed\ntry:\n from tensorflow.python.keras.layers import CuDNNLSTM as lstm\nexcept:\n from tensorflow.keras.layers import Dense, Activation, LSTM as lstm\nfrom tensorflow.keras.layers import Dropout\nfrom tensorflow.keras.optimizers import RMSprop\nfrom tensorflow.keras.models import load_model as lm\n\nimport numpy as np\nimport random\nimport sys\nimport io\nfrom midi import Midi\n\n\nclass Model:\n def create(self, size, unique_notes, optimizer=None, hidden_size=128):\n self.model = Sequential()\n self.model.add(lstm(hidden_size, input_shape=(\n size, unique_notes), return_sequences=True))\n self.model.add(lstm(hidden_size))\n self.model.add(Dropout(0.2))\n self.model.add(Dense(unique_notes))\n self.model.add(Activation('softmax'))\n self.model.compile(loss='categorical_crossentropy', optimizer=RMSprop(\n lr=0.01) if optimizer == None else optimizer)\n\n def load_from_file(self, name=\"model.h5\"):\n self.model = lm(name)\n\n def save_to_file(self, name=\"model.h5\"):\n self.model.save(name)\n\n def learn(self, inputs, outputs, batch_size=256, epochs=185):\n self.model.fit(inputs, outputs,\n batch_size=batch_size,\n epochs=epochs, verbose=True)\n\n def predict(self, arr):\n return self.model.predict(arr)\n" ]
[ [ "tensorflow.keras.models.load_model", "tensorflow.keras.layers.Activation", "tensorflow.keras.layers.Dense", "tensorflow.keras.optimizers.RMSprop", "tensorflow.keras.layers.LSTM", "tensorflow.keras.layers.Dropout", "tensorflow.keras.models.Sequential" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] } ]
leonardbj/AIMS
[ "7f8f484ab829f15366cb04ab37f799ad88edd29a" ]
[ "src/ML_Algorithms/ExpectationMaximization/m_step_gaussian_mixture.py" ]
[ "\"\"\" converted from Matlab code\nsource: http://www.robots.ox.ac.uk/~fwood/teaching/AIMS_CDT_ML_2015/homework/HW_2_em/\n\"\"\"\n\nimport numpy as np\n\ndef m_step_gaussian_mixture(data, gamma):\n \"\"\"% Performs the M-step of the EM algorithm for gaussain mixture model.\n %\n % @param data : n x d matrix with rows as d dimensional data points\n % @param gamma : n x k matrix of resposibilities\n %\n % @return pi : k x 1 array\n % @return mu : k x d matrix of maximized cluster centers\n % @return sigma : cell array of maximized \n %\n \"\"\"\n \n n = np.shape(data)[0]\n d = np.shape(data)[1]\n k = np.shape(gamma)[1]\n \n pi = np.zeros(k)\n mu = np.zeros((k, d))\n sigma = np.zeros((k, d, d))\n \n for kk in range(k):\n Nkk = np.sum(gamma[:, kk])\n pi[kk] = Nkk / n\n for dd in range(d):\n mu[kk, dd] = np.sum(gamma[:, kk] * data[:, dd], axis=0) / Nkk\n \n for kk in range(k):\n Nkk = np.sum(gamma[:, kk])\n centered_data = data - mu[kk, :]\n for nn in range(n):\n sigma[kk] += gamma[nn, kk] * np.dot(centered_data[nn, None].T, centered_data[nn, None])\n sigma[kk] /= Nkk\n \n return [mu, sigma, pi]\n" ]
[ [ "numpy.shape", "numpy.dot", "numpy.zeros", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
linrio/WhetherOrNotMe
[ "239a6d3be82fecb58eb3ade4cf2966d5d294ce10" ]
[ "trainCNN.py" ]
[ "import tensorflow as tf\r\nimport cv2\r\nimport numpy as np\r\nimport os\r\nfrom sklearn.model_selection import train_test_split\r\nimport random\r\nimport sys\r\n\r\nmy_image_path = 'my_face'\r\nothers_image_path = 'other_people'\r\n\r\nimage_data = []\r\nlabel_data = []\r\n\r\ndef get_padding_size(image):\r\n#def get_padding_size(image):\r\n h, w, _ = image.shape #长,宽和通道数\r\n longest_edge = max(h, w)\r\n top, bottom, left, right = (0, 0, 0, 0)\r\n if h <= longest_edge:\r\n dh = longest_edge - h\r\n top = dh // 2\r\n bottom = dh - top\r\n elif w <= longest_edge:\r\n dw = longest_edge - w\r\n left = dw // 2\r\n right = dw - left\r\n else:\r\n pass\r\n return top, bottom, left, right #(0,0,0,0)\r\n\r\n\r\n#os.listdir(path):path 要获得内容目录的路径。获得当前目录的所有内容。\r\ndef read_data(img_path, image_h=64, image_w=64):\r\n for filename in os.listdir(img_path):\r\n if filename.endswith('.jpg'):\r\n filepath = os.path.join(img_path, filename)\r\n image = cv2.imread(filepath)\r\n\r\n top, bottom, left, right = get_padding_size(image)\r\n image_pad = cv2.copyMakeBorder(image, top , bottom, left, right, cv2.BORDER_CONSTANT, value=[0, 0, 0])\r\n image = cv2.resize(image_pad, (image_h, image_w))\r\n\r\n image_data.append(image)\r\n label_data.append(img_path)\r\n\r\nread_data(others_image_path)\r\nread_data(my_image_path)\r\n\r\nimage_data = np.array(image_data)\r\nlabel_data = np.array([[0,1] if label == 'my_faces' else [1,0] for label in label_data])\r\n\r\n#功能是从样本中随机的按比例选取train data和test data, test_size是样本占比。如果是整数的话就是样本的数量。random_state是随机数的种子。\r\ntrain_x, test_x, train_y, test_y = train_test_split(image_data, label_data, test_size=0.05, random_state=random.randint(0, 100))\r\n\r\n# image (height=64 width=64 channel=3)\r\ntrain_x = train_x.reshape(train_x.shape[0], 64, 64, 3)\r\ntest_x = test_x.reshape(test_x.shape[0], 64, 64, 3)\r\n\r\n# nomalize\r\ntrain_x = train_x.astype('float32') / 255.0\r\ntest_x = test_x.astype('float32') / 255.0\r\n\r\nprint(len(train_x), len(train_y))\r\nprint(len(test_x), len(test_y))\r\n\r\n#############################################################\r\n#batch_size = 128\r\nbatch_size = 64\r\nnum_batch = len(train_x) // batch_size\r\n\r\n#tf.placeholder() 占位符,传递一个tensor到session.run()中。\r\nX = tf.placeholder(tf.float32, [None, 64, 64, 3]) # 图片大小64x64 channel=3\r\nY = tf.placeholder(tf.float32, [None, 2])\r\n\r\nkeep_prob_5 = tf.placeholder(tf.float32)\r\nkeep_prob_75 = tf.placeholder(tf.float32)\r\n\r\ndef panda_joke_cnn():\r\n\r\n W_c1 = tf.Variable(tf.random_normal([3, 3, 3, 32], stddev=0.01))\r\n b_c1 = tf.Variable(tf.random_normal([32]))\r\n conv1 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(X, W_c1, strides=[1, 1, 1, 1], padding='SAME'), b_c1))\r\n conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\n conv1 = tf.nn.dropout(conv1, keep_prob_5)\r\n #先W*X,再W*X+b,再Relu,再max_pool, 再,dropout\r\n #Dropout是指在模型训练时随机让网络某些隐含层节点的权重不工作,不工作的那些节点可以暂时认为不是网络结构的一部分,但是它的权重得保留下来(只是暂时不更新而已),因为下次样本输入时它可能又得工作了\r\n\r\n W_c2 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01))\r\n b_c2 = tf.Variable(tf.random_normal([64]))\r\n conv2 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv1, W_c2, strides=[1, 1, 1, 1], padding='SAME'), b_c2))\r\n conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\n conv2 = tf.nn.dropout(conv2, keep_prob_5)\r\n\r\n W_c3 = tf.Variable(tf.random_normal([3, 3, 64, 64], stddev=0.01))\r\n b_c3 = tf.Variable(tf.random_normal([64]))\r\n conv3 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv2, W_c3, strides=[1, 1, 1, 1], padding='SAME'), b_c3))\r\n conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\n conv3 = tf.nn.dropout(conv3, keep_prob_5)\r\n\r\n W_c31 = tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.01))\r\n b_c31 = tf.Variable(tf.random_normal([128]))\r\n conv31 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv3, W_c31, strides=[1, 1, 1, 1], padding='SAME'), b_c31))\r\n conv31 = tf.nn.max_pool(conv31, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\n conv31 = tf.nn.dropout(conv31, keep_prob_5)\r\n\r\n W_c32 = tf.Variable(tf.random_normal([3, 3, 128, 128], stddev=0.01))\r\n b_c32 = tf.Variable(tf.random_normal([128]))\r\n conv32 = tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(conv31, W_c32, strides=[1, 1, 1, 1], padding='SAME'), b_c32))\r\n conv32 = tf.nn.max_pool(conv32, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\r\n conv32 = tf.nn.dropout(conv32, keep_prob_5)\r\n\r\n # Fully connected layer\r\n #W_d = tf.Variable(tf.random_normal([8*16*32, 512], stddev=0.01))\r\n W_d = tf.Variable(tf.random_normal([128*128, 512], stddev=0.01))\r\n b_d = tf.Variable(tf.random_normal([512]))\r\n dense = tf.reshape(conv32, [-1, W_d.get_shape().as_list()[0]])\r\n dense = tf.nn.relu(tf.add(tf.matmul(dense, W_d), b_d))\r\n dense = tf.nn.dropout(dense, keep_prob_75)\r\n\r\n W_out = tf.Variable(tf.random_normal([512, 2], stddev=0.01))\r\n b_out = tf.Variable(tf.random_normal([2]))\r\n out = tf.add(tf.matmul(dense, W_out), b_out)\r\n return out\r\n\r\n#learning_rate = 0.001\r\ndef train_cnn():\r\n output = panda_joke_cnn()\r\n\r\n #softmax_cross_entropy_with_logits():一步是先对网络最后一层的输出做一个softmax.\r\n #第二步是softmax的输出向量[Y1,Y2,Y3...]和样本的实际标签做一个交叉熵.最后求一个平均,得到我们想要的loss.\r\n #这个函数的返回值并不是一个数,而是一个向量.\r\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=output))\r\n optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)\r\n #optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\r\n accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(output, 1), tf.argmax(Y, 1)), tf.float32))\r\n\r\n tf.summary.scalar(\"loss\", loss)\r\n tf.summary.scalar(\"accuracy\", accuracy)\r\n merged_summary_op = tf.summary.merge_all()\r\n\r\n saver = tf.train.Saver()\r\n with tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n\r\n summary_writer = tf.summary.FileWriter('./log', graph=tf.get_default_graph())\r\n\r\n for e in range(50):\r\n for i in range(num_batch):\r\n batch_x = train_x[i*batch_size : (i+1)*batch_size]\r\n batch_y = train_y[i*batch_size : (i+1)*batch_size]\r\n _, loss_, summary = sess.run([optimizer, loss, merged_summary_op], feed_dict={X: batch_x, Y: batch_y, keep_prob_5:0.5, keep_prob_75: 0.75})\r\n\r\n summary_writer.add_summary(summary, e*num_batch+i)\r\n print(e*num_batch+i, \"loss= \", loss_)\r\n\r\n if (e*num_batch+i) % 100 == 0:\r\n acc = accuracy.eval({X: test_x, Y: test_y, keep_prob_5:1.0, keep_prob_75: 1.0})\r\n print(e*num_batch+i,\"acc= \", +acc)\r\n # save model\r\n if acc > 0.99:\r\n saver.save(sess, \"G:/codes/tensorflow2/WhetherOrNotMe/models/whether_orNot_me.model\", global_step=e*num_batch+i)\r\n if e*num_batch+i > 0:\r\n sys.exit(0)\r\n\r\ntrain_cnn()\r\noutput = panda_joke_cnn()\r\npredict = tf.argmax(output, 1)\r\n\r\nsaver = tf.train.Saver()\r\nsess = tf.Session()\r\nsaver.restore(sess, tf.train.latest_checkpoint('.'))\r\n\r\ndef is_my_face(image):\r\n res = sess.run(predict, feed_dict={X: [image/255.0], keep_prob_5:1.0, keep_prob_75: 1.0})\r\n if res[0] == 1:\r\n return True\r\n else:\r\n return False\r\n\r\nface_haar = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\r\nface_haar.load('D:/Program Files (x86)/Miniconda3/Library/etc/haarcascades/haarcascade_frontalface_default.xml')\r\ncam = cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n _, img = cam.read()\r\n gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n faces = face_haar.detectMultiScale(gray_image, 1.3, 5)\r\n for face_x,face_y,face_w,face_h in faces:\r\n face = img[face_y:face_y+face_h, face_x:face_x+face_w]\r\n\r\n face = cv2.resize(face, (64, 64))\r\n\r\n print(\"my face:\"+is_my_face(face))\r\n\r\n cv2.imshow('img', face)\r\n key = cv2.waitKey(30) & 0xff\r\n if key == 27:\r\n sys.exit(0)\r\n\r\nsess.close()" ]
[ [ "tensorflow.matmul", "tensorflow.nn.softmax_cross_entropy_with_logits", "tensorflow.train.latest_checkpoint", "tensorflow.nn.conv2d", "tensorflow.nn.max_pool", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.random_normal", "tensorflow.summary.merge_all", "tensorflow.Session", "tensorflow.train.AdamOptimizer", "tensorflow.train.Saver", "tensorflow.get_default_graph", "tensorflow.argmax", "numpy.array", "tensorflow.summary.scalar", "tensorflow.nn.dropout" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
stanfordmlgroup/seamseg
[ "574e89a4e5e99b0aca90071a0c37c31e57c5449e" ]
[ "seamseg/data/dataset.py" ]
[ "import glob\nfrom itertools import chain\nfrom os import path\n\nimport numpy as np\nimport torch.utils.data as data\nimport umsgpack\nfrom PIL import Image\n\n\nclass ISSDataset(data.Dataset):\n \"\"\"Instance segmentation dataset\n\n This assumes the dataset to be formatted as defined in:\n https://github.com/mapillary/seamseg/wiki/Dataset-format\n\n Parameters\n ----------\n root_dir : str\n Path to the root directory of the dataset\n split_name : str\n Name of the split to load: this must correspond to one of the files in `root_dir/lst`\n transform : callable\n Transformer function applied to the loaded entries to prepare them for pytorch. This should be callable as\n `transform(img, msk, cat, cls)`, where:\n - `img` is a PIL.Image with `mode=\"RGB\"`, containing the RGB data\n - `msk` is a list of PIL.Image with `mode=\"L\"`, containing the instance segmentation masks\n - `cat` is a list containing the instance id to class id mapping\n - `cls` is an integer specifying a requested class for class-uniform sampling, or None\n\n \"\"\"\n _IMG_DIR = \"img\"\n _MSK_DIR = \"msk\"\n _LST_DIR = \"lst\"\n _METADATA_FILE = \"metadata.bin\"\n\n def __init__(self, root_dir, split_name, transform):\n super(ISSDataset, self).__init__()\n self.root_dir = root_dir\n self.split_name = split_name\n self.transform = transform\n\n # Folders\n self._img_dir = path.join(root_dir, ISSDataset._IMG_DIR)\n self._msk_dir = path.join(root_dir, ISSDataset._MSK_DIR)\n self._lst_dir = path.join(root_dir, ISSDataset._LST_DIR)\n for d in self._img_dir, self._msk_dir, self._lst_dir:\n if not path.isdir(d):\n raise IOError(\"Dataset sub-folder {} does not exist\".format(d))\n\n # Load meta-data and split\n self._meta, self._images = self._load_split()\n\n def _load_split(self):\n with open(path.join(self.root_dir, ISSDataset._METADATA_FILE), \"rb\") as fid:\n metadata = umsgpack.unpack(fid, encoding=\"utf-8\")\n\n with open(path.join(self._lst_dir, self.split_name + \".txt\"), \"r\") as fid:\n lst = fid.readlines()\n lst = set(line.strip() for line in lst)\n\n meta = metadata[\"meta\"]\n images = [img_desc for img_desc in metadata[\"images\"] if img_desc[\"id\"] in lst]\n\n return meta, images\n\n def _load_item(self, item):\n img_desc = self._images[item]\n\n img_file = path.join(self._img_dir, img_desc[\"id\"])\n if path.exists(img_file + \".png\"):\n img_file = img_file + \".png\"\n elif path.exists(img_file + \".jpg\"):\n img_file = img_file + \".jpg\"\n else:\n raise IOError(\"Cannot find any image for id {} in {}\".format(img_desc[\"id\"], self._img_dir))\n img = Image.open(img_file).convert(mode=\"RGB\")\n\n # Load all masks\n msk_file = path.join(self._msk_dir, img_desc[\"id\"] + \".png\")\n msk = [Image.open(msk_file)]\n i = 1\n while path.exists(\"{}.{}\".format(msk_file, i)):\n msk.append(Image.open(\"{}.{}\".format(msk_file, i)))\n i += 1\n\n cat = img_desc[\"cat\"]\n iscrowd = img_desc[\"iscrowd\"]\n return img, msk, cat, iscrowd, img_desc[\"id\"]\n\n @property\n def categories(self):\n \"\"\"Category names\"\"\"\n return self._meta[\"categories\"]\n\n @property\n def num_categories(self):\n \"\"\"Number of categories\"\"\"\n return len(self.categories)\n\n @property\n def num_stuff(self):\n \"\"\"Number of \"stuff\" categories\"\"\"\n return self._meta[\"num_stuff\"]\n\n @property\n def num_thing(self):\n \"\"\"Number of \"thing\" categories\"\"\"\n return self.num_categories - self.num_stuff\n\n @property\n def original_ids(self):\n \"\"\"Original class id of each category\"\"\"\n return self._meta[\"original_ids\"]\n\n @property\n def palette(self):\n \"\"\"Default palette to be used when color-coding semantic labels\"\"\"\n return np.array(self._meta[\"palette\"], dtype=np.uint8)\n\n @property\n def img_sizes(self):\n \"\"\"Size of each image of the dataset\"\"\"\n return [img_desc[\"size\"] for img_desc in self._images]\n\n @property\n def img_categories(self):\n \"\"\"Categories present in each image of the dataset\"\"\"\n return [img_desc[\"cat\"] for img_desc in self._images]\n\n def __len__(self):\n return len(self._images)\n\n def __getitem__(self, item):\n img, msk, cat, iscrowd, idx = self._load_item(item)\n rec = self.transform(img, msk, cat, iscrowd)\n size = (img.size[1], img.size[0])\n\n img.close()\n for m in msk:\n m.close()\n\n rec[\"idx\"] = idx\n rec[\"size\"] = size\n return rec\n\n def get_raw_image(self, idx):\n \"\"\"Load a single, unmodified image with given id from the dataset\"\"\"\n img_file = path.join(self._img_dir, idx)\n if path.exists(img_file + \".png\"):\n img_file = img_file + \".png\"\n elif path.exists(img_file + \".jpg\"):\n img_file = img_file + \".jpg\"\n else:\n raise IOError(\"Cannot find any image for id {} in {}\".format(idx, self._img_dir))\n\n return Image.open(img_file)\n\n def get_image_desc(self, idx):\n \"\"\"Look up an image descriptor given the id\"\"\"\n matching = [img_desc for img_desc in self._images if img_desc[\"id\"] == idx]\n if len(matching) == 1:\n return matching[0]\n else:\n raise ValueError(\"No image found with id %s\" % idx)\n\n\nclass ISSTestDataset(data.Dataset):\n _EXTENSIONS = [\"*.jpg\", \"*.jpeg\", \"*.png\"]\n\n def __init__(self, in_dir, transform):\n super(ISSTestDataset, self).__init__()\n self.in_dir = in_dir\n self.transform = transform\n\n # Find all images\n self._images = []\n for img_path in chain(\n *(glob.iglob(path.join(self.in_dir, '**', ext), recursive=True) for ext in ISSTestDataset._EXTENSIONS)):\n _, name_with_ext = path.split(img_path)\n idx, _ = path.splitext(name_with_ext)\n\n with Image.open(img_path) as img_raw:\n size = (img_raw.size[1], img_raw.size[0])\n\n self._images.append({\n \"idx\": idx,\n \"path\": img_path,\n \"size\": size,\n })\n\n @property\n def img_sizes(self):\n \"\"\"Size of each image of the dataset\"\"\"\n return [img_desc[\"size\"] for img_desc in self._images]\n\n def __len__(self):\n return len(self._images)\n\n def __getitem__(self, item):\n # Load image\n with Image.open(self._images[item][\"path\"]) as img_raw:\n size = (img_raw.size[1], img_raw.size[0])\n img = self.transform(img_raw.convert(mode=\"RGB\"))\n\n return {\n \"img\": img,\n \"idx\": self._images[item][\"idx\"],\n \"size\": size,\n \"abs_path\": self._images[item][\"path\"],\n \"rel_path\": path.relpath(self._images[item][\"path\"], self.in_dir),\n }\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lanl/pymplot
[ "093769a06051c6b41be76ce1431e6a6e64477e5a", "093769a06051c6b41be76ce1431e6a6e64477e5a" ]
[ "src/module_tick.py", "src/showwiggle.py" ]
[ "'''\n Module:\n Set regular or irregular axis ticks for a plot.\n'''\nfrom module_utility import *\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# ticks : contains irregular ticks locations\n# tickbeg : regular major ticks begin location\n# tickend : regular major ticks end location\n# tickd : regular major ticks interval\n# mtick : number of minor tick intervals betwen two major ticks\n# xbeg : axis begin location\n# xend : axis end location\n# ns : number of points to plot\n# d : interval between two points\n# axislen : apparent axis length\ndef define_tick(ticks, tickbeg, tickend, tickd, mtick, xbeg, xend, ns, d, axislen, format, extend=False):\n\n # regular ticks\n if ticks is None:\n\n # major tick interval\n if tickd is None:\n tick_interval = nice((xend - xbeg) / 5.0)\n if tick_interval == 0:\n tick_interval = 1.0e10\n else:\n tick_interval = float(tickd)\n\n # tick begin location\n if tickbeg is None:\n tick_beg = nice(xbeg)\n base = 0.5\n nb = 0\n if tick_interval > 0:\n while nb <= 10 and tick_beg > xbeg + tick_interval:\n base = base / 10.0\n tick_beg = nice(xbeg, base)\n nb = nb + 1\n else:\n while nb <= 10 and tick_beg < xbeg + tick_interval:\n base = base / 10.0\n tick_beg = nice(xbeg, base)\n nb = nb + 1\n else:\n tick_beg = float(tickbeg)\n\n # tick end location\n if tickend is None:\n tick_end = tick_beg + (round((xend - xbeg) / tick_interval) + 2) * tick_interval\n if tick_interval > 0:\n while tick_end < xend:\n tick_end = tick_end + abs(tick_interval)\n else:\n while tick_end > xend:\n tick_end = tick_end - abs(tick_interval)\n else:\n tick_end = float(tickend)\n\n # regular major and minor tick locations\n tick = np.arange(tick_beg, tick_end + 0.1 * abs(tick_interval), tick_interval)\n minor_tick_interval = tick_interval / (mtick + 1.0)\n minor_tick = np.arange(tick_beg, tick_end + 0.1 * abs(minor_tick_interval), minor_tick_interval)\n\n # some ticks might out of axis range, therefore remove them if strict\n if not extend:\n if d > 0:\n tick = np.asarray([i for i in tick if i >= xbeg and i <= xend])\n minor_tick = np.asarray(\n [i for i in minor_tick if i >= xbeg and i <= xend and (not i in tick)])\n if d < 0:\n tick = np.asarray([i for i in tick if i <= xbeg and i >= xend])\n minor_tick = np.asarray(\n [i for i in minor_tick if i <= xbeg and i >= xend and (not i in tick)])\n\n # linearly scale the ticks to figure canvas\n if ns == 1:\n # if only one sample point, then tick location is 0.5\n tick_location = np.asarray([0.5])\n ntick = 1\n else:\n # if multiple sample points, then scale to apparent axis length\n tick_location = [(i - xbeg + 0.5 * d) / ((ns - 1) * d) * axislen for i in tick]\n minor_tick_location = [(i - xbeg + 0.5 * d) / ((ns - 1) * d) * axislen for i in minor_tick]\n t = tick_location\n\n # set major tick location and labels, note some major ticks might be out of axis range\n tl = []\n tick_label = []\n for i in range(0, len(tick)):\n if extend or ((not extend) and tick_location[i] >= 0 and tick_location[i] <= axislen + 1.0e-10):\n tl.append(tick_location[i])\n if format == 'sci' or format == 'plain':\n tick_label.append(('%f' % tick[i]).rstrip('0').rstrip('.'))\n else:\n tick_label.append((format % tick[i]))\n tick_location = tl\n\n # irregular ticks\n else:\n \n # get contents from user-specified ticks\n ticks = ticks[0].split(',')\n location = [0 for i in range(0, len(ticks))]\n label = ['' for i in range(0, len(ticks))]\n \n # set tick locations\n for i in range(0, len(ticks)):\n t = ticks[i].split(':')\n location[i] = (float(t[0]) + 0.5 * d) / ((ns - 1) * d) * axislen\n label[i] = t[1]\n\n # sort according to tick location\n yx = list(zip(location, label))\n yx.sort()\n tick_location = [location for location, label in yx]\n tick_label = [label for location, label in yx]\n\n # minor ticks\n if mtick != 0:\n mtick = mtick + 1\n minor_tick_location = np.linspace(tick_location[0], tick_location[1], mtick + 1)\n minor_tick_location = minor_tick_location[1:mtick]\n for i in range(1, len(tick_location) - 1):\n t = np.linspace(tick_location[i], tick_location[i + 1], mtick + 1)\n minor_tick_location = np.append(minor_tick_location, t[1:mtick])\n else:\n minor_tick_location = []\n\n # return major tick location, major tick label and minor tick location\n return tick_location, tick_label, minor_tick_location\n\n\ndef set_tick(args,\n font,\n x1beg,\n x1end,\n n1beg,\n n1end,\n d1,\n axis1len,\n x2beg,\n x2end,\n n2beg,\n n2end,\n d2,\n axis2len,\n extend=False):\n\n ax = plt.gca()\n\n label_1_size = float(args.label1size)\n label_2_size = float(args.label2size)\n\n xlabel = ax.set_xlabel(args.label2, fontsize=label_2_size, labelpad=float(args.label2pad)*72*2)\n ylabel = ax.set_ylabel(args.label1, fontsize=label_1_size, labelpad=float(args.label1pad)*72*2)\n\n l = ax.yaxis.get_label()\n l.set_fontproperties(font)\n l.set_fontsize(label_1_size)\n l = ax.xaxis.get_label()\n l.set_fontproperties(font)\n l.set_fontsize(label_2_size)\n\n if args.label2loc is not None:\n ax.xaxis.set_label_position(args.label2loc)\n else:\n \tif args.ticktop:\n \t\tax.xaxis.set_label_position('top')\n \telse:\n \t\tax.xaxis.set_label_position('bottom')\n if args.label1loc is not None:\n \tax.yaxis.set_label_position(args.label1loc)\n else:\n \tif args.tickleft:\n \t\tax.yaxis.set_label_position('left')\n \telse:\n \t\tax.yaxis.set_label_position('right')\n \t\tylabel.set_rotation(270)\n\n # ticks on/off\n ax.get_yaxis().set_tick_params(which='both', direction='out')\n ax.get_xaxis().set_tick_params(which='both', direction='out')\n plt.tick_params(\n axis='x', # changes apply to the x1-axis\n which='both', # both major and minor ticks are affected\n bottom=args.tickbottom, # ticks along the bottom axis\n top=args.ticktop, # ticks along the top axis\n labelbottom=args.tickbottom, # labels along the bottom axis\n labeltop=args.ticktop) # labels along the top axis\n plt.tick_params(\n axis='y', # changes apply to the x2-axis\n which='both', # both major and minor ticks are affected\n left=args.tickleft, # ticks along the left axis\n right=args.tickright, # ticks along the right axis\n labelleft=args.tickleft, # labels along the left axis\n labelright=args.tickright) # labels along the right axis\n\n # if tick font size and family not speciefied, then inherit from axis labels\n if args.tick1size is None:\n tick_1_font_size = label_1_size - 2\n else:\n tick_1_font_size = float(args.tick1size)\n\n if args.tick2size is None:\n tick_2_font_size = label_2_size - 2\n else:\n tick_2_font_size = float(args.tick2size)\n\n # axis 1\n tick_1_location, tick_1_label, tick_1_minor = define_tick(args.ticks1, args.tick1beg, args.tick1end,\n args.tick1d, args.mtick1, x1beg, x1end,\n n1end - n1beg + 1, d1, axis1len,\n args.tick1format, extend)\n plt.yticks(tick_1_location, tick_1_label, fontsize=tick_1_font_size, rotation=float(args.tick1rot))\n if not args.tick1label:\n ax.yaxis.set_ticklabels([])\n\n # axis 2\n tick_2_location, tick_2_label, tick_2_minor = define_tick(args.ticks2, args.tick2beg, args.tick2end,\n args.tick2d, args.mtick2, x2beg, x2end,\n n2end - n2beg + 1, d2, axis2len,\n args.tick2format, extend)\n plt.xticks(tick_2_location, tick_2_label, fontsize=tick_2_font_size, rotation=float(args.tick2rot))\n if not args.tick2label:\n ax.xaxis.set_ticklabels([])\n\n # major and minor ticks sytle\n ax.tick_params('both', length=float(args.tickmajorlen), width=float(args.tickmajorwid), which='major')\n\n # minor tick positions\n ax.set_yticks(tick_1_minor, minor=True)\n ax.set_xticks(tick_2_minor, minor=True)\n\n # minor ticks style\n if args.tickminorlen is None:\n tick_minor_length = 0.5 * float(args.tickmajorlen)\n else:\n tick_minor_length = float(args.tickminorlen)\n\n if args.tickminorwid is None:\n tick_minor_width = 0.75 * float(args.tickmajorwid)\n else:\n tick_minor_width = float(args.tickminorwid)\n\n ax.tick_params('both', length=tick_minor_length, width=tick_minor_width, which='minor')\n\n for l in ax.yaxis.get_ticklabels():\n l.set_fontproperties(font)\n l.set_fontsize(tick_1_font_size)\n for l in ax.xaxis.get_ticklabels():\n l.set_fontproperties(font)\n l.set_fontsize(tick_2_font_size)\n\n\n# make tick labels rigid\ndef rigid_tick_label(tick_label):\n\n ndec = 0\n for i in tick_label:\n dec = i.split('.')\n if len(dec) == 2:\n ll = len(dec[1])\n if ll > ndec:\n ndec = ll\n\n for i in range(0, len(tick_label)):\n dec = tick_label[i].split('.')\n if len(dec) == 2:\n ll = len(dec[1])\n if ll < ndec:\n for k in range(0, ndec - ll):\n tick_label[i] = tick_label[i] + '0'\n if len(dec) == 1 and ndec != 0:\n tick_label[i] = tick_label[i] + '.'\n for k in range(0, ndec):\n tick_label[i] = tick_label[i] + '0'\n\n return tick_label\n", "#!/usr/bin/python3\n\n## dependencies\nfrom pylab import *\nimport matplotlib as mplt\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport math\nimport argparse\nfrom module_getarg import getarg\nfrom argparse import RawTextHelpFormatter\n\n# this is to ignore warnings\nimport warnings\n\nwarnings.filterwarnings(\"ignore\", module=\"matplotlib\")\n\n# tag\nprogram = 'wiggle'\nprint()\n\n## read arguments\nparser = argparse.ArgumentParser(description='''\n purpose:\n Plot a 2D array as wiggles along the 1st or the 2nd dimenison.\n ''',\n formatter_class=RawTextHelpFormatter)\nparser = getarg(parser, program)\nargs = parser.parse_args()\n\n## input data\ninfile = args.infile[0].split(',')\nnf = len(infile)\n\nfor i in range(0, nf):\n if not os.path.exists(infile[i]):\n print('input file', infile[i], 'does not exists')\n print()\n exit()\n\nfsize = os.path.getsize(infile[0])\ndatatype = args.datatype\nif datatype == 'double':\n fsize = fsize / 8\nif datatype == 'float':\n fsize = fsize / 4\nif datatype == 'int':\n fsize = fsize / 2\n\nn1 = args.n1\nif args.n2 is None:\n n2 = int(fsize * 1.0 / n1)\nelse:\n n2 = args.n2\n\nd1 = float(args.d1)\nd2 = float(args.d2)\n\n# if wiggle locations are read from a file\nif args.wiggleloc is not None:\n \n # from ASCII file\n wloc = np.loadtxt(args.wiggleloc, ndmin=2)\n [i for i in wloc if i]\n wloc = np.array(wloc)\n shape = shape(wloc)\n if args.along == 1 and n2 != shape[0]:\n print(\" Error: n2 = \", n2, ' != size(wiggleloc) = ', shape[0])\n exit()\n if args.along == 2 and n1 != shape[0]:\n print(\" Error: n1 = \", n1, ' != size(wiggleloc) = ', shape[0])\n exit()\n \n # n, o, d\n if args.along == 1:\n n2 = shape[0]\n f2 = wloc[0][0]\n d2 = (wloc.max() - wloc.min()) / (n2 - 1.0)\n\n n1 = n1\n f1 = float(args.o1)\n d1 = d1\n else:\n n1 = shape[0]\n f1 = wloc[0][0]\n d1 = (wloc.max() - wloc.min()) / (n1 - 1.0)\n\n n2 = n2\n f2 = float(args.o2)\n d2 = d2\n\nelse:\n f1 = float(args.o1)\n f2 = float(args.o2)\n\n## limit of axis\nfrom module_range import *\n\nsp1beg, sp1end, x1beg, x1end, n1beg, n1end = set_range(f1, n1, d1, args.x1beg, args.x1end)\nsp2beg, sp2end, x2beg, x2end, n2beg, n2end = set_range(f2, n2, d2, args.x2beg, args.x2end)\n\n## plot\nprint()\nfor i in range(0, nf):\n print('input << ', infile[i])\n\n# data type\nfrom module_datatype import *\n\ndt = set_datatype(args)\n\nadata = np.empty([nf, n1end - n1beg, n2end - n2beg])\nfor i in range(0, nf):\n\n # read binary data\n data = fromfile(infile[i], dtype=dt, count=n1 * n2)\n if not args.transpose:\n data = data.reshape((n2, n1))\n data = data.transpose()\n else:\n data = data.reshape(n1, n2)\n\n if i == 0:\n print('shape ', data.shape)\n\n # print value range of input files\n if isnan(sum(data)) == True:\n udata = data[~isnan(data)]\n if udata.shape == (0, ):\n print('error: input dataset is nan')\n exit()\n else:\n dmin = udata.min()\n dmax = udata.max()\n else:\n dmin = data.min()\n dmax = data.max()\n print('value range ', dmin, ' -- ', dmax)\n\n # crop data\n data = data[n1beg:n1end, n2beg:n2end]\n\n # assign to whole data\n adata[i, :, :] = data\n\n# read background data\nif args.background is not None:\n\n # check if background file exists\n if not os.path.exists(args.background):\n print()\n print('input file', args.background, 'does not exists')\n print()\n exit()\n\n # input\n backdata = np.empty([n1, n2])\n backdata = fromfile(args.background, dtype=dt, count=n1 * n2)\n\n # transpose\n if not args.transpose:\n backdata = backdata.reshape((n2, n1))\n backdata = backdata.transpose()\n else:\n backdata = backdata.reshape(n1, n2)\n\n # crop\n backdata = backdata[n1beg:n1end, n2beg:n2end]\n\n## set clip\nfrom module_clip import *\n\ncmin, cmax = set_clip(args, adata, 'fore', dmin, dmax)\nif args.background is not None:\n backcmin, backcmax = set_clip(args, backdata, 'back')\n\n## figure size\nfrom module_size import *\n\nfigheight, figwidth = set_size(args, n1beg, n1end, n2beg, n2end)\n\n## begin plot\nfig = plt.figure(figsize=(figwidth, figheight))\nax = fig.add_axes([0, 0, 1, 1])\n\n## set frame\nfrom module_frame import *\n\nset_frame(args)\n\n## plot image\n# show image if necessary\nif nf == 1 and args.overlay and args.background is None:\n\n # show data by imshow\n im = ax.imshow(adata[0, :, :]) #,alpha=float(args.alpha))\n\n # set colormap\n from module_colormap import set_colormap\n colormap = set_colormap(args)\n im.set_cmap(colormap)\n\n # set clip\n im.set_clim(cmin, cmax)\n\n # set interpolation\n im.set_interpolation(args.interp)\n\n #alpha = float(args.alpha)\n\n# plot background image if necessary\nif not args.overlay and args.background is not None:\n\n # beg plot\n im = ax.imshow(backdata) #,alpha=float(args.backalpha))\n\n # set colormap\n from module_colormap import set_colormap\n colormap = set_colormap(args, 'background')\n im.set_cmap(colormap)\n\n # set clip\n im.set_clim(backcmin, backcmax)\n\n # set interpolation\n im.set_interpolation(args.interp)\n\n## set font\nfrom module_font import *\n\nfont, fontbold = set_font(args)\n\n## set tick\nfrom module_tick import *\n\nset_tick(args,\n font,\n x1beg,\n x1end,\n n1beg,\n n1end,\n d1,\n figheight,\n x2beg,\n x2end,\n n2beg,\n n2end,\n d2,\n figwidth,\n extend=True)\n\n## set grid line\nfrom module_gridline import *\n\nset_gridline(args)\n\n## set title\nfrom module_title import *\n\nset_title(args, fontbold)\n\n## set annotation\nfrom module_annotation import *\n\nset_annotation(args, font, x1beg, n1end - n1beg, d1, figheight, x2beg, n2end - n2beg, d2, figwidth)\n\n## plot wiggles\nax = plt.gca()\n\n# scaling factors\nif args.wiggleloc is not None and args.along == 2:\n scale1 = wloc.max() - wloc.min() + d1\n scale1 = scale1 / figheight\nelse:\n scale1 = (n1end - n1beg) * d1 / figheight\nif scale1 == 0:\n scale1 = 1.0\n\nif args.wiggleloc is not None and args.along == 1:\n scale2 = wloc.max() - wloc.min() + d2\n scale2 = scale2 / figwidth\nelse:\n scale2 = (n2end - n2beg) * d2 / figwidth\nif scale2 == 0:\n scale2 = 1.0\n\n# setup line colors, if given number of colors < number of files, then cycle append colors\nfrom itertools import cycle\n# defaultcolor=cycle('brgykcp')\ndefaultcolor = cycle(['blue', 'red', 'green', 'yellow', 'black', 'cyan', 'magenta'])\ncolor = args.wigglecolor[0].split(',')\n\nnc = len(color)\nif nc < nf:\n ic = 0\n for i in cycle(defaultcolor):\n color.append(i)\n ic = ic + 1\n if ic >= nf:\n break\n\nwmin = 1.0e10\nwmax = 0.0\n\nfrom module_annotation import set_default\n\nlinewidth = set_default(args.wigglewidth, ',', nf, 1.0, 'float')\nlinestyle = set_default(args.wigglestyle, ',', nf, '-')\n\n# plot labels if necessary\nif args.plotlabel is not None:\n plotlabel = args.plotlabel[0].split(',')\n if len(plotlabel) < nf:\n l = len(plotlabel)\n aplotlabel = ['Set ' + str(i) for i in range(l, nf)]\n plotlabel.extend(aplotlabel)\nelse:\n plotlabel = ['Set ' + str(i) for i in range(0, nf)]\n\nlocdict = {\n 'upper_right': 1,\n 'upper_left': 2,\n 'lower_left': 3,\n 'lower_right': 4,\n 'right': 5,\n 'center_left': 6,\n 'center_right': 7,\n 'lower_center': 8,\n 'upper_center': 9,\n 'center': 10\n}\nif args.plotlabelloc in list(locdict.keys()):\n labelloc = locdict[args.plotlabelloc]\nelse:\n labelloc = 2\n\n# start wiggle plot\nfrom scipy.interpolate import InterpolatedUnivariateSpline\n\nif args.along == 1:\n\n if x1beg == x1end:\n print()\n print(' Error: Wiggles are along axis 1, but have only one sample. ')\n print()\n exit()\n\n traceinterval = int(args.every) * abs(d2) / scale2\n adata = adata / (cmax - cmin) * traceinterval\n traces = np.arange(0, n2end - n2beg, int(args.every))\n y = (np.arange(0, n1end - n1beg) * d1) / scale1\n\n if args.interp1 is not None:\n yy = np.linspace(y.min(), y.max(), int((n1end - n1beg) * float(args.interp1) + 1))\n else:\n yy = y\n\n for i in traces:\n\n if args.wiggleloc is not None:\n offset = (wloc[i][0] - wloc[0][0] + 0.5 * d2) / scale2\n else:\n offset = (i * d2 + 0.5 * d2) / scale2\n\n # iterate through all datasets\n for j in range(0, nf):\n\n # select data\n data = adata[j, :, :]\n\n # plot data\n x = data[:, i] + offset\n\n if args.interp1 is not None:\n spl = InterpolatedUnivariateSpline(y, x, k=3)\n xx = spl(yy)\n else:\n xx = x\n\n xx[where(xx >= offset + traceinterval)] = offset + traceinterval\n xx[where(xx <= offset - traceinterval)] = offset - traceinterval\n\n # wiggles\n if i != traces[-1]:\n plt.plot(xx,\n yy,\n color=color[j],\n linewidth=linewidth[j],\n linestyle=linestyle[j],\n antialiased=True)\n else:\n plt.plot(xx,\n yy,\n color=color[j],\n linewidth=linewidth[j],\n linestyle=linestyle[j],\n antialiased=True,\n label=plotlabel[j])\n\n # fill positive/negative polarity if necessary\n if args.fill == 1:\n ax.fill_betweenx(yy,\n offset,\n xx,\n interpolate=True,\n antialiased=True,\n lw=0,\n where=(xx > offset),\n color=color[j],\n edgecolor='none')\n if args.fill == -1:\n ax.fill_betweenx(yy,\n offset,\n xx,\n interpolate=True,\n antialiased=True,\n lw=0,\n where=(xx < offset),\n color=color[j],\n edgecolor='none')\n\n if i == traces[0]:\n wmin = min(wmin, xx.min())\n if i == traces[-1]:\n wmax = max(wmax, xx.max())\n\n # to ensure correct image show range\n omin = (traces[0] * d2) / scale2\n omax = (traces[-1] * d2 + d2) / scale2\n\n # invert y axis for make zero at the top\n if args.reverse1 == 0:\n ax.invert_yaxis()\n\nif args.along == 2:\n\n if x2beg == x2end:\n print()\n print(' Error: Wiggles are along axis 2, but have only one sample. ')\n print()\n exit()\n\n traceinterval = int(args.every) * abs(d1) / scale1\n adata = adata / (cmax - cmin) * traceinterval\n traces = np.arange(0, n1end - n1beg, int(args.every))\n y = (np.arange(0, n2end - n2beg) * d2) / scale2\n\n if args.interp2 is not None:\n yy = np.linspace(y.min(), y.max(), int((n2end - n2beg) * float(args.interp2) + 1))\n else:\n yy = y\n\n for i in traces:\n\n if args.wiggleloc is not None:\n offset = (wloc[i][0] - wloc[0][0] + 0.5 * d1) / scale1\n else:\n offset = (i * d1 + 0.5 * d1) / scale1\n\n # iterate through all datasets\n for j in range(0, nf):\n\n # select data\n data = adata[j, :, :]\n\n # plot data\n x = data[i, :] + offset\n\n if args.interp2 is not None:\n spl = InterpolatedUnivariateSpline(y, x, k=3)\n xx = spl(yy)\n else:\n xx = x\n\n xx[where(xx >= offset + traceinterval)] = offset + traceinterval\n xx[where(xx <= offset - traceinterval)] = offset - traceinterval\n\n # wiggles\n if i != traces[-1]:\n plt.plot(yy,\n xx,\n color=color[j],\n linewidth=linewidth[j],\n linestyle=linestyle[j],\n antialiased=True)\n else:\n plt.plot(yy,\n xx,\n color=color[j],\n linewidth=linewidth[j],\n linestyle=linestyle[j],\n antialiased=True,\n label=plotlabel[j])\n\n # fill positive/negative polarity if necessary\n if args.fill == 1:\n ax.fill_between(yy,\n offset,\n xx,\n interpolate=True,\n antialiased=True,\n lw=0,\n where=(xx > offset),\n facecolor=color[j],\n edgecolor='none')\n if args.fill == -1:\n ax.fill_between(yy,\n offset,\n xx,\n interpolate=True,\n antialiased=True,\n lw=0,\n where=(xx < offset),\n facecolor=color[j],\n edgecolor='none')\n\n if i == traces[0]:\n wmin = min(wmin, xx.min())\n if i == traces[-1]:\n wmax = max(wmax, xx.max())\n\n # to ensure correct image show range\n omin = (traces[0] * d1) / scale1\n omax = (traces[-1] * d1 + d1) / scale1\n\n# add plot labels\nif args.plotlabel is not None:\n if args.plotlabelloc in list(locdict.keys()):\n lg = plt.legend(loc=labelloc)\n else:\n lg = plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0)\n lg.set_zorder(10)\n lg.get_frame().set_alpha(1)\n leg = ax.get_legend()\n ltext = leg.get_texts()\n plt.setp(ltext, fontproperties=font)\n plt.setp(ltext, fontsize=float(args.plotlabelsize))\n\n## reset figure sizes\nif (nf == 1 and args.overlay and args.background is None) or (not args.overlay\n and args.background is not None):\n if args.along == 1:\n im.set_extent([omin, omax, figheight, 0])\n else:\n im.set_extent([0, figwidth, omax, omin])\n\napad = float(args.axispad)\n\nif args.along == 1:\n wmin = wmin - apad\n wmax = wmax + apad\n if args.wx2beg is not None:\n wmin = (float(args.wx2beg) - wloc[0][0] + 0.5 * d2) / scale2\n if args.wx2end is not None:\n wmax = (float(args.wx2end) - wloc[0][0] + 0.5 * d2) / scale2\n ax.set_xlim([wmin, wmax])\n ax.set_ylim([figheight, 0])\n ax.set_aspect('auto')\nif args.along == 2:\n wmin = wmin - apad\n wmax = wmax + apad\n if args.wx1beg is not None:\n wmin = (float(args.wx1beg) - wloc[0][0] + 0.5 * d1) / scale1\n if args.wx1end is not None:\n wmax = (float(args.wx1end) - wloc[0][0] + 0.5 * d1) / scale1\n ax.set_xlim([0, figwidth])\n if args.reverse1 == 0:\n ax.set_ylim([wmin, wmax])\n else:\n ax.set_ylim([wmax, wmin])\n ax.set_aspect('auto')\n\n## axis invert\nif args.reverse1 == 1:\n ax.invert_yaxis()\nif args.reverse2 == 1:\n ax.invert_xaxis()\n\n## set colorbar\nif nf == 1 and args.overlay and args.legend:\n from module_colorbar import set_colorbar\n set_colorbar(args, im, font, cmin, cmax, figheight, figwidth, fig)\n\n## output\nfrom module_io import *\n\noutput(args)\n" ]
[ [ "matplotlib.pyplot.gca", "numpy.linspace", "numpy.asarray", "numpy.append", "matplotlib.pyplot.tick_params" ], [ "matplotlib.pyplot.gca", "matplotlib.pyplot.legend", "scipy.interpolate.InterpolatedUnivariateSpline", "numpy.arange", "numpy.empty", "matplotlib.pyplot.plot", "matplotlib.pyplot.setp", "numpy.array", "numpy.loadtxt", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
EnricoPittini/model-selection
[ "dcd3e202773372088047056d866c12c15dba65ac" ]
[ "model_selection.py" ]
[ "\"\"\"\r\nModule for the selection of machine learning models.\r\n\r\nThere are several different functions which can perform the model selection: all of them have an intuitive interface, but\r\nare also powerful and flexible.\r\nIn addition, almost all these functions can optionally make plots, which sum up the performed selection in a visual way.\r\n\r\nThese different functions perform the model selection in different contexts, i.e. each function is specifically meant for a\r\nspecific scenario. Certain contexts are more specific, and other are more general.\r\nOn the whole, there are six different model selection functions, divided into two main groups:\r\n 1. functions that perform the model selection with respect to a **single dataset**;\r\n 2. functions that perform the model selection with respect to **multiple datasets**.\r\n\r\nThe six functions, sorted from the most specific context to the most general one, are:\r\n - *hyperparameter_validation*, *hyperparameters_validation*, *models_validation* (single dataset);\r\n - *datasets_hyperparameter_validation*, *datasets_hyperparameters_validation*, *datasets_models_validation* (multiple\r\n datasets).\r\n\r\nThis module deeply uses the **numpy** library. It is built on the top of it. In fact, the datasets are represented as np.array.\r\nMoreover, the plots are made using the **matplotlib** library. In addition, it is built on the top of the **sklearn** module:\r\n- the machine learning models are represented as sklearn models (i.e. sklearn estimators);\r\n- under the hood, the selection is performed using the grid search cross validation provided by sklearn (i.e.\r\nGridSearchCV);\r\n- several other operations are done using the functionalities provided by sklearn.\r\n\r\nThis module, besides the model selection functions, contains also some utilities:\r\n- the PolynomialRegression class;\r\n- some utility functions.\r\n\r\n\"\"\"\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom sklearn.utils import resample\r\nfrom sklearn.model_selection import train_test_split, cross_val_score, TimeSeriesSplit, GridSearchCV\r\nfrom sklearn.metrics import mean_squared_error, accuracy_score\r\nfrom sklearn.preprocessing import MinMaxScaler, PolynomialFeatures\r\nfrom sklearn.base import BaseEstimator\r\nfrom sklearn.linear_model import LinearRegression\r\n\r\n\r\n\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------\r\n# POLYNOMIAL REGRESSOR MODEL\r\n\r\nclass PolynomialRegression(BaseEstimator):\r\n \"\"\"\r\n Polynomial regression model.\r\n\r\n It's a sklearn model: it's compliant to the sklearn estimators interface.\r\n `Example <https://scikit-learn.org/stable/developers/develop.html>`_\r\n\r\n Parameters\r\n ----------\r\n degree: int\r\n Degree to apply for the polynomial transformation.\r\n\r\n Notes\r\n ----------\r\n The polynomial transformation is performed using the sklearn PolynomialFeatures.\r\n \"\"\"\r\n\r\n def __init__(self, degree=1):\r\n self.degree=degree\r\n\r\n def fit(self, X, y):\r\n self.poly_transformer = PolynomialFeatures(self.degree, include_bias=False)\r\n self.poly_transformer.fit(X)\r\n X = self.poly_transformer.transform(X)\r\n self.model = LinearRegression(fit_intercept=True)\r\n self.model.fit(X,y)\r\n return self\r\n\r\n def predict(self, X):\r\n X = self.poly_transformer.transform(X)\r\n return self.model.predict(X)\r\n\r\n def get_params(self, deep=True):\r\n return {\"degree\": self.degree}\r\n\r\n def set_params(self, **parameters):\r\n for parameter, value in parameters.items():\r\n setattr(self, parameter, value)\r\n return self\r\n\r\n\r\n\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------\r\n# UTILITY FUNCTIONS\r\n\r\n\r\ndef compute_train_val_test(X, y, model, scale=False, test_size=0.2, time_series=False, random_state=123, n_folds=5,\r\n regr=True):\r\n \"\"\"\r\n Compute the training-validation-test scores for the given model on the given dataset.\r\n\r\n The training and test scores are simply computed by splitting the dataset into the training and test sets. The validation\r\n score is performed applying the cross validation on the training set.\r\n\r\n Parameters\r\n ----------\r\n X: np.array\r\n Two-dimensional np.array, containing the explanatory features of the dataset.\r\n y: np.array\r\n Mono dimensional np.array, containing the response feature of the dataset.\r\n model: sklearn.base.BaseEstimator\r\n Model to evaluate.\r\n scale: bool\r\n Indicates whether to scale or not the features in `X`.\r\n (The scaling is performed using the sklearn MinMaxScaler).\r\n test_size: float\r\n Decimal number between 0 and 1, which indicates the proportion of the test set.\r\n time_series: bool\r\n Indicates if the given dataset is a time series dataset (i.e. datasets indexed by days).\r\n (This affects the computing of the scores).\r\n random_state: int\r\n Used in the training-test splitting of the dataset.\r\n n_folds: int\r\n Indicates how many folds are made in order to compute the k-fold cross validation.\r\n (It's used only if `time_series` is False).\r\n regr: bool\r\n Indicates if it's either a regression or a classification problem.\r\n\r\n Returns\r\n ----------\r\n train_score: float\r\n val_score: float\r\n test_score: float\r\n\r\n Notes\r\n ----------\r\n - If `regr` is True, the returned scores are errors, computed using the MSE formula (i.e. Mean Squared Error).\r\n Otherwise, the returned scores are accuracy measures.\r\n - If `time_series` is False, the training-test splitting of the dataset is made randomly. In addition, the cross\r\n validation strategy performed is the classic k-fold cross validation: the number of folds is specified by `n_folds`.\r\n Otherwise, if `time_series` is True, the training-test sets are obtained simply by splitting the dataset into two\r\n contiguous parts. In addition, the cross validation strategy performed is the sklearn TimeSeriesSplit.\r\n \"\"\"\r\n\r\n if regr:\r\n scoring=\"neg_mean_squared_error\"\r\n else:\r\n scoring=\"accuracy\"\r\n\r\n # Split into training e test.\r\n if not time_series : # Random splitting (not time series)\r\n X_train_80, X_test, y_train_80, y_test = train_test_split(X, y, test_size=test_size, random_state=random_state)\r\n else: # time series splitting\r\n train_len = int(X.shape[0]*(1-test_size))\r\n X_train_80 = X[:train_len]\r\n y_train_80 = y[:train_len]\r\n X_test = X[train_len:]\r\n y_test = y[train_len:]\r\n\r\n if(scale): # Scale the features in X\r\n scaler = MinMaxScaler()\r\n scaler.fit(X_train_80)\r\n X_train_80 = scaler.transform(X_train_80)\r\n X_test = scaler.transform(X_test)\r\n\r\n # Cross validation\r\n if not time_series: # k-fold cross validation\r\n cv = n_folds\r\n else: # cross validation for time series\r\n cv = TimeSeriesSplit(n_splits = n_folds)\r\n scores = cross_val_score(model, X_train_80, y_train_80, cv=cv, scoring=scoring)\r\n val_score = scores.mean() # validation score\r\n if regr:\r\n val_score = -val_score\r\n\r\n model.fit(X_train_80,y_train_80) # Fit the model using all the training\r\n\r\n # Compute training and test scores\r\n train_score=0\r\n test_score=0\r\n if regr:\r\n train_score = mean_squared_error(y_true=y_train_80, y_pred=model.predict(X_train_80))\r\n test_score = mean_squared_error(y_true=y_test, y_pred=model.predict(X_test))\r\n else:\r\n train_score = accuracy_score(y_true=y_train_80, y_pred=model.predict(X_train_80))\r\n test_score = accuracy_score(y_true=y_test, y_pred=model.predict(X_test))\r\n\r\n return train_score, val_score, test_score # Return a triple\r\n\r\n\r\ndef compute_bias_variance_error(X, y, model, scale=False, N_TESTS = 20, sample_size=0.67):\r\n \"\"\"\r\n Compute the bias^2-variance-error scores for the given model on the given dataset.\r\n\r\n These measures are computed in an approximate way, using `N_TESTS` random samples of size `sample_size` from the\r\n dataset.\r\n\r\n Parameters\r\n ----------\r\n X: np.array\r\n Two-dimensional np.array, containing the explanatory features of the dataset.\r\n y: np.array\r\n Mono dimensional np.array, containing the response feature of the dataset.\r\n model: sklearn.base.BaseEstimator\r\n Model to evaluate.\r\n scale: bool\r\n Indicates whether to scale or not the features in `X`.\r\n (The scaling is performed using the sklearn MinMaxScaler).\r\n N_TESTS: int\r\n Number of samples that are made in order to compute the measures.\r\n sample_size: float\r\n Decimal number between 0 and 1, which indicates the proportion of the sample.\r\n\r\n Returns\r\n ----------\r\n bias: float\r\n variance: float\r\n error: float\r\n \"\"\"\r\n\r\n # Scale the features in `X`\r\n if(scale):\r\n scaler = MinMaxScaler()\r\n scaler.fit(X)\r\n X = scaler.transform(X)\r\n\r\n # Vector 'vector_ypred': at the beginning is a list of lists (i.e. two dimensional list).\r\n # In the end it will be a matrix which has as many rows as `N_TESTS` (each row corresponds to a sample) and as many\r\n # columns as the number of instances in `X` (each column is a point of the dataset).\r\n # Row 'i' --> there are the predictions made by the model on the sample 'i' using all the dataset points.\r\n # Column 'j' --> there are the predictions made by the model on the point 'j' using all the `N_TESTS` samples.\r\n vector_ypred = []\r\n\r\n # Iterate through N_TESTS. At each iteration extract a new sample and fit the model on it.\r\n for i in range(N_TESTS):\r\n # Extract a new sample (sample 'i')\r\n Xs, ys = resample(X,y, n_samples=int(sample_size*len(y)) )\r\n\r\n # Fit the model on this sample 'i'\r\n model.fit(Xs,ys)\r\n\r\n # Add the predictions made by the model on all the dataset points\r\n vector_ypred.append(list(model.predict(X)))\r\n\r\n vector_ypred = np.array(vector_ypred) # Transform into numpy array\r\n\r\n # Vector that has as many elements as the dataset points, and for each of them it has the associated bias^2 computed on\r\n # the `N_TEST` samples.\r\n vector_bias = (y - np.mean(vector_ypred, axis=0))**2\r\n\r\n # Vector that has as many elements as the dataset points, and for each of them it has the associated variance computed on\r\n # the `N_TEST` samples.\r\n vector_variance = np.var(vector_ypred, axis=0)\r\n\r\n # Vector that has as many elements as the dataset points, and for each of them it has the associated error computed on\r\n # the `N_TEST` samples.\r\n vector_error = np.sum((vector_ypred - y)**2, axis=0)/N_TESTS\r\n\r\n bias = np.mean(vector_bias) # Total bias^2 of the model\r\n variance = np.mean(vector_variance) # Total variance of the model\r\n error = np.mean(vector_error) # Total error of the model\r\n\r\n return bias,variance,error # Return a triple\r\n\r\n\r\ndef plot_predictions(X, y, model, scale=False, test_size=0.2, plot_type=0, xvalues=None, xlabel=\"Index\",\r\n title=\"Actual vs Predicted values\", figsize=(6,6)):\r\n \"\"\"\r\n Plot the predictions made by the given model on the given dataset, versus its actual values.\r\n\r\n The dataset is split into training-test sets: the former is used to train the `model`, on the latter the predictions are\r\n made.\r\n\r\n Parameters\r\n ----------\r\n X: np.array\r\n Two-dimensional np.array, containing the explanatory features of the dataset.\r\n y: np.array\r\n Mono dimensional np.array, containing the response feature of the dataset.\r\n model: sklearn.base.BaseEstimator\r\n Model used to make the predictions.\r\n scale: bool\r\n Indicates whether to scale or not the features in `X`.\r\n (The scaling is performed using the sklearn MinMaxScaler).\r\n test_size: float\r\n Decimal number between 0 and 1, which indicates the proportion of the test set.\r\n plot_type: int\r\n Indicates the type of the plot.\r\n - 0 -> In the same plot two different curves are drawn: the first has on the x axis `xvalues` and on the y axis\r\n the actual values (i.e. `y`); the second has on the x axis `xvalues` and on the y axis the computed\r\n predicted values.\r\n - 1 -> On the x axis the actual values are put, on the y axis the predicted ones.\r\n xvalues: list (in general, iterable)\r\n Values that have to be put in the x axis of the plot.\r\n (It's used only if `plot_type` is 0).\r\n xlabel: str\r\n Label of the x axis of the plot.\r\n (It's used only if `plot_type` is 0).\r\n title: str\r\n Title of the plot.\r\n figsize: tuple\r\n Two dimensions of the plot.\r\n\r\n Returns\r\n ----------\r\n matplotlib.axes.Axes\r\n The matplotlib Axes where the plot has been made.\r\n\r\n Notes\r\n ----------\r\n The splitting of the datasets into the training-test sets is simply made by dividing the dataset into two contiguous\r\n sequences.\r\n I.e. it is the same technique used usually when the dataset is a time series dataset. (This is done in order to simplify\r\n the visualization).\r\n For this reason, typically this function is applied on time series datasets.\r\n \"\"\"\r\n\r\n train_len = int(X.shape[0]*(1-test_size))\r\n X_train_80 = X[:train_len]\r\n y_train_80 = y[:train_len]\r\n X_test = X[train_len:]\r\n y_test = y[train_len:]\r\n\r\n if(scale): # Scale the features in X\r\n scaler = MinMaxScaler()\r\n scaler.fit(X_train_80)\r\n X_train_80 = scaler.transform(X_train_80)\r\n X_test = scaler.transform(X_test)\r\n\r\n model.fit(X_train_80,y_train_80) # Fit using all the training set\r\n\r\n predictions = model.predict(X_test)\r\n\r\n fig, ax = plt.subplots(figsize=figsize)\r\n\r\n if plot_type==0:\r\n if xvalues is None:\r\n xvalues=range(len(X))\r\n ax.plot(xvalues,y, 'o:', label='actual values')\r\n ax.plot(xvalues[train_len:],predictions, 'o:', label='predicted values')\r\n ax.legend()\r\n elif plot_type==1:\r\n ax.plot(y[train_len:],predictions,'o')\r\n ax.plot([0, 1], [0, 1], 'r-',transform=ax.transAxes)\r\n xlabel=\"Actual values\"\r\n ax.set_ylabel(\"Predicted values\")\r\n\r\n ax.set_xlabel(xlabel)\r\n ax.set_title(title)\r\n ax.grid()\r\n\r\n return ax\r\n\r\n\r\ndef _plot_TrainVal_values(xvalues, train_val_scores, plot_train, xlabel, title, figsize=(6,6), bar=False):\r\n \"\"\"\r\n Plot the given list of training-validation scores.\r\n\r\n This function is an auxiliary function for the model selection functions. It's meant to be private in the\r\n module.\r\n\r\n Parameters\r\n ----------\r\n xvalues: list (in general iterable)\r\n Values to put in the x axis of the plot.\r\n train_val_scores: np.array\r\n Two dimensional np.array, containing two columns: the first contains the trainining scores, the second the validation\r\n scores.\r\n Basically, it is a list of training-validation scores.\r\n plot_train: bool\r\n Indicates whether to plot also the training scores or to plot only the validation ones.\r\n xlabel: str\r\n Label of the x axis.\r\n title: str\r\n Title of the plot.\r\n figsize: tuple\r\n Two dimensions of the plot.\r\n bar: bool\r\n Indicates whether to plot the scores using bars or using points.\r\n If `bar` it's True, `xvalues` must contain string (i.e. labels).\r\n Returns\r\n ----------\r\n matplotlib.axes.Axes\r\n The matplotlib Axes where the plot has been made.\r\n \"\"\"\r\n\r\n fig, ax = plt.subplots(figsize=figsize)\r\n\r\n if not bar: # Points\r\n if plot_train: # Plot also the training scores\r\n ax.plot(xvalues,train_val_scores[:,0], 'o:', label='Train')\r\n ax.plot(xvalues,train_val_scores[:,1], 'o:', label='Validation') # Validation scores\r\n else: # Bars\r\n if plot_train: # Plot also the training scores\r\n x = np.arange(len(xvalues)) # The label locations\r\n width = 0.35 # The width of the bars\r\n ax.bar(x-width/2,train_val_scores[:,0], width=width, label='Train')\r\n ax.bar(x+width/2,train_val_scores[:,1], width=width, label='Validation') # Validation scores\r\n ax.set_xticks(x)\r\n ax.set_xticklabels(xvalues)\r\n else:\r\n ax.bar(xvalues,train_val_scores[:,1],label='Validation')\r\n\r\n\r\n ax.set_xlabel(xlabel)\r\n ax.set_title(title)\r\n ax.grid()\r\n ax.legend()\r\n\r\n return ax\r\n\r\n\r\n\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------\r\n# FUNCTIONS THAT PERFORM THE MODEL SELECTION WITH RESPECT TO A SINGLE DATASET\r\n\r\n\r\ndef hyperparameter_validation(X, y, model, hyperparameter, hyperparameter_values, scale=False, test_size=0.2,\r\n time_series=False, random_state=123, n_folds=5, regr=True, plot=False, plot_train=False,\r\n xvalues=None, xlabel=None, title=\"Hyperparameter validation\", figsize=(6,6)):\r\n \"\"\"\r\n Select the best value for the specified hyperparameter of the specified model on the given dataset.\r\n\r\n In other words, perform the tuning of the `hyperparameter` among the values in `hyperparameter_values`.\r\n\r\n This selection is made using the validation score (i.e. the best hyperparameter value is the one with the best validation\r\n score).\r\n The validation score is computed by splitting the dataset into the training-test sets and then by applying the cross\r\n validation on the training set.\r\n Additionally, the training and test scores are also computed.\r\n\r\n Optionally, the validation scores of the `hyperparameter_values` can be plotted, making a graphical visualization of the\r\n selection.\r\n\r\n Parameters\r\n ----------\r\n X: np.array\r\n Two-dimensional np.array, containing the explanatory features of the dataset.\r\n y: np.array\r\n Mono dimensional np.array, containing the response feature of the dataset.\r\n model: sklearn.base.BaseEstimator\r\n Model which has the specified `hyperparameter`.\r\n hyperparameter: str\r\n The name of the hyperparameter that has to be validated.\r\n hyperparameter_values: list\r\n List of values for `hyperparameter` that have to be taken into account in the selection.\r\n scale: bool\r\n Indicates whether to scale or not the features in `X`.\r\n (The scaling is performed using the sklearn MinMaxScaler).\r\n test_size: float\r\n Decimal number between 0 and 1, which indicates the proportion of the test set.\r\n time_series: bool\r\n Indicates if the given dataset is a time series dataset (i.e. dataset indexed by days).\r\n (This affects the computing of the validation score).\r\n random_state: int\r\n Used in the training-test splitting of the dataset.\r\n n_folds: int\r\n Indicates how many folds are made in order to compute the k-fold cross validation.\r\n (It's used only if `time_series` is False).\r\n regr: bool\r\n Indicates if it's either a regression or a classification problem.\r\n plot: bool\r\n Indicates whether to plot or not the validation score values.\r\n plot_train: bool\r\n Indicates whether to plot also the training scores.\r\n (It's considered only if `plot` is True).\r\n xvalues: list (in general, iterable)\r\n Values that have to be put in the x axis of the plot.\r\n xlabel: str\r\n Label of the x axis of the plot.\r\n title: str\r\n Title of the plot.\r\n figsize: tuple\r\n Two dimensions of the plot.\r\n\r\n Returns\r\n ----------\r\n train_val_scores: np.array\r\n Two dimensional np.array, containing two columns: the first contains the training scores, the second the validation\r\n scores.\r\n It has as many rows as the number of values in `hyperparameter_values` (i.e. number of values to be tested).\r\n best_index: int\r\n Index of `hyperparameter_values` that indicates which is the best hyperparameter value.\r\n test_score: float\r\n Test score associated with the best hyperparameter value.\r\n ax: matplotlib.axes.Axes\r\n The matplotlib Axes where the plot has been made.\r\n If `plot` is False, then it is None.\r\n\r\n Notes\r\n ----------\r\n - If `regr` is True, the validation scores are errors (MSE, i.e. Mean Squared Errors): this means that the best\r\n hyperparameter value is the one associated with the minimum validation score.\r\n Otherwise, the validation scores are accuracies: this means that the best hyperparameter value is the one associated\r\n with the maximum validation score.\r\n - If `time_series` is False, the training-test splitting of the dataset is made randomly. In addition, the cross\r\n validation strategy performed is the classic k-fold cross validation: the number of folds is specified by `n_folds`.\r\n Otherwise, if `time_series` is True, the training-test sets are simply obtained by splitting the dataset into two\r\n contiguous parts. In addition, the cross validation strategy performed is the sklearn TimeSeriesSplit.\r\n \"\"\"\r\n\r\n param_grid = {hyperparameter:hyperparameter_values} # Create the hyperparameter grid\r\n # Call the function for the validation of an arbitrary number of hyperparameters\r\n params, train_val_scores, best_index, test_score = hyperparameters_validation(X, y, model, param_grid, scale=scale,\r\n test_size=test_size,\r\n time_series=time_series,\r\n random_state=random_state, n_folds=n_folds,\r\n regr=regr)\r\n\r\n ax = None\r\n\r\n if(plot): # Make the plot\r\n if not xvalues: # Default values on the x axis\r\n xvalues = hyperparameter_values\r\n if not xlabel: # Default label on the x axis\r\n xlabel = hyperparameter\r\n ax = _plot_TrainVal_values(xvalues, train_val_scores, plot_train, xlabel, title, figsize)\r\n\r\n return train_val_scores, best_index, test_score, ax\r\n\r\n\r\ndef hyperparameters_validation(X, y, model, param_grid, scale=False, test_size=0.2, time_series=False, random_state=123,\r\n n_folds=5, regr=True):\r\n \"\"\"\r\n Select the best combination of values for the specified hyperparameters of the specified model on the given dataset.\r\n\r\n In other words, perform the tuning of multiple hyperparameters.\r\n The parameter `param_grid` is a dictionary that indicates which are the specified hyperparameters and what are the\r\n associated values to test.\r\n\r\n All the possible combinations of values are tested, in an exhaustive way (i.e. grid search).\r\n\r\n This selection is made using the validation score (i.e. the best combination of hyperparameters values is the one with\r\n the best validation score).\r\n The validation score is computed by splitting the dataset into the training-test sets and then by applying the cross\r\n validation on the training set.\r\n Additionally, the training and test scores are also computed.\r\n\r\n Parameters\r\n ----------\r\n X: np.array\r\n Two-dimensional np.array, containing the explanatory features of the dataset.\r\n y: np.array\r\n Mono dimensional np.array, containing the response feature of the dataset.\r\n model: sklearn.base.BaseEstimator\r\n Model which has the specified hyperparameters.\r\n param_grid: dict\r\n Dictionary which has as keys the names of the specified hyperparameters and as values the associated list of\r\n values to test.\r\n scale: bool\r\n Indicates whether to scale or not the features in `X`.\r\n (The scaling is performed using the sklearn MinMaxScaler).\r\n test_size: float\r\n Decimal number between 0 and 1, which indicates the proportion of the test set.\r\n time_series: bool\r\n Indicates if the given dataset is a time series dataset (i.e. dataframe indexed by days).\r\n (This affects the computing of the validation score).\r\n random_state: int\r\n Used in the training-test splitting of the dataset.\r\n n_folds: int\r\n Indicates how many folds are made in order to compute the k-fold cross validation.\r\n (It's used only if `time_series` is False).\r\n regr: bool\r\n Indicates if it's either a regression or a classification problem.\r\n\r\n Returns\r\n ----------\r\n params: list\r\n List which enumerates all the possible combinations of hyperparameters values.\r\n It's a list of dictionaries: each dictionary represents a specific combination of hyperparameters values. (It's a\r\n dictionary which has as keys the hyperparameters names and as values the specific associated values of that combination).\r\n train_val_scores: np.array\r\n Two dimensional np.array, containing two columns: the first contains the training scores, the second the validation\r\n scores.\r\n It has as many rows as the number of possible combinations of the hyperparameters values.\r\n (It has as many rows as the elements of `params`).\r\n best_index: int\r\n Index of `params` that indicates which is the best combination of hyperparameters values.\r\n test_score: float\r\n Test score associated with the best combination of hyperparameters values.\r\n\r\n Notes\r\n ----------\r\n - If `regr` is True, the validation scores are errors (MSE, i.e. Mean Squared Errors): this means that the best\r\n combination of hyperparameters values is the one associated with the minimum validation score.\r\n Otherwise, the validation scores are accuracies: this means that the best combination of hyperparameters values is the\r\n one associated with the maximum validation score.\r\n - If `time_series` is False, the training-test splitting of the dataset is made randomly. In addition, the cross\r\n validation strategy performed is the classic k-fold cross validation: the number of folds is specified by `n_folds`.\r\n Otherwise, if `time_series` is True, the training-test sets are simply obtained by splitting the dataset into two\r\n contiguous parts. In addition, the cross validation strategy performed is the sklearn TimeSeriesSplit.\r\n \"\"\"\r\n\r\n if regr:\r\n scoring=\"neg_mean_squared_error\"\r\n else:\r\n scoring=\"accuracy\"\r\n\r\n # Split into training-test sets\r\n if not time_series : # Random splitting\r\n X_train_80, X_test, y_train_80, y_test = train_test_split(X, y, test_size=test_size, random_state=random_state)\r\n else: # Time series splitting\r\n train_len = int(X.shape[0]*(1-test_size))\r\n X_train_80 = X[:train_len]\r\n y_train_80 = y[:train_len]\r\n X_test = X[train_len:]\r\n y_test = y[train_len:]\r\n\r\n if(scale): # Scale the features in `X`\r\n scaler = MinMaxScaler()\r\n scaler.fit(X_train_80)\r\n X_train_80 = scaler.transform(X_train_80)\r\n X_test = scaler.transform(X_test)\r\n\r\n # Cross validation strategy\r\n if not time_series: # The strategy is the classic k-fold cross validation\r\n cv = n_folds\r\n else: # Time series cross validation strategy\r\n cv = TimeSeriesSplit(n_splits = n_folds)\r\n\r\n # Grid search\r\n grid_search = GridSearchCV(model,param_grid,scoring=scoring,cv=cv,return_train_score=True)\r\n grid_search.fit(X_train_80,y_train_80)\r\n\r\n params = grid_search.cv_results_[\"params\"] # List of all the possible combinations of hyperparameters values\r\n # List where for all the possible combinations of hyperparameters values there is the associated training score\r\n train_scores = grid_search.cv_results_[\"mean_train_score\"]\r\n # List where for all the possible combinations of hyperparameters values there is the associated validation score\r\n val_scores = grid_search.cv_results_[\"mean_test_score\"]\r\n # Index of `params`, corresponding to the best combination of hyperparameters values\r\n best_index = grid_search.best_index_\r\n # Model with the best combination of hyperparameters values\r\n best_model = grid_search.best_estimator_\r\n\r\n if regr: # The scores are negative: moltiply by -1\r\n train_scores = train_scores*(-1)\r\n val_scores = val_scores*(-1)\r\n train_val_scores = np.concatenate((train_scores.reshape(-1,1), val_scores.reshape(-1,1)), axis=1)\r\n\r\n # Fit the best model on all the training set\r\n best_model.fit(X_train_80,y_train_80)\r\n\r\n # Compute the test score of the best model\r\n test_score=0\r\n if regr:\r\n test_score = mean_squared_error(y_true=y_test, y_pred=best_model.predict(X_test))\r\n else:\r\n test_score = accuracy_score(y_true=y_test, y_pred=best_model.predict(X_test))\r\n\r\n return params, train_val_scores, best_index, test_score\r\n\r\n\r\ndef models_validation(X, y, model_paramGrid_list, scale_list=None, test_size=0.2, time_series=False, random_state=123,\r\n n_folds=5, regr=True, plot=False, plot_train=False, xvalues=None, xlabel=\"Models\",\r\n title=\"Models validation\", figsize=(6,6)):\r\n \"\"\"\r\n Select the best model on the given dataset.\r\n\r\n The parameter `model_paramGrid_list` is the list of the models to test. It also contains, for each model, the grid of\r\n hyperparameters that have to be tested on that model (i.e. the grid which contains the values to test for each\r\n specified hyperparameter of the model).\r\n (That grid has the same structure as the `param_grid` parameter of the function `hyperparameters_validation`. See\r\n `hyperparameters_validation`).\r\n\r\n For each specified model, the best combination of hyperparameters values is selected in an exhaustive way (i.e. grid\r\n search).\r\n Actually, the function `hyperparameters_validation` is used.\r\n (See `hyperparameters_validation`).\r\n\r\n The selection of the best model is made using the validation score (i.e. the best model is the one with the best\r\n validation score).\r\n The validation score is computed by splitting the dataset into the training-test sets and then by applying the cross\r\n validation on the training set.\r\n Additionally, the training and test scores are also computed.\r\n\r\n Optionally, the validation scores of the different models can be plotted, making a graphical visualization of the\r\n selection.\r\n\r\n Parameters\r\n ----------\r\n X: np.array\r\n Two-dimensional np.array, containing the explanatory features of the dataset.\r\n y: np.array\r\n Mono dimensional np.array, containing the response feature of the dataset.\r\n model_paramGrid_list: list\r\n List that specifies the models and the relative grids of hyperparameters to be tested.\r\n It's a list of triples (i.e. tuples), where each triple represents a model:\r\n - the first element is a string, which is a mnemonic name of that model;\r\n - the second element is the sklearn model;\r\n - the third element is the grid of hyperparameters to test for that model. It's a dictionary, with the same\r\n structure of the parameter `param_grid` of the function `hyperparameters_validation`.\r\n scale_list: list or bool\r\n List of booleans, which has as many elements as the models to test (i.e. as the elements of the\r\n `model_paramGrid_list` list).\r\n This list indicates, for each different model, if the features in `X` have to be scaled or not.\r\n `scale_list` can be None or False: in this case the `X` features aren't scaled for any model. `scale_list` can be\r\n True: in this case the `X` features are scaled for all the models.\r\n test_size: float\r\n Decimal number between 0 and 1, which indicates the proportion of the test set.\r\n time_series: bool\r\n Indicates if the given dataset is a time series dataset (i.e. dataset indexed by days).\r\n (This affects the computing of the validation score).\r\n random_state: int\r\n Used in the training-test splitting of the dataset.\r\n n_folds: int\r\n Indicates how many folds are made in order to compute the k-fold cross validation.\r\n (It's used only if `time_series` is False).\r\n regr: bool\r\n Indicates if it's either a regression or a classification problem.\r\n plot: bool\r\n Indicates whether to plot or not the validation score values.\r\n plot_train: bool\r\n Indicates whether to plot also the training scores.\r\n (It's considered only if `plot` is True).\r\n xvalues: list (in general, iterable)\r\n Values that have to be put in the x axis of the plot.\r\n xlabel: str\r\n Label of the x axis of the plot.\r\n title: str\r\n Title of the plot.\r\n figsize: tuple\r\n Two dimensions of the plot.\r\n\r\n Returns\r\n ----------\r\n models_train_val_score: np.array\r\n Two dimensional np.array, containing two columns: the first contains the training scores, the second the validation\r\n scores.\r\n It has as many rows as the number of models to test (i.e. number of elements in the `model_paramGrid_list` list).\r\n models_best_params: list\r\n List which indicates, for each model, the best combination of the hyperparameters values for that model.\r\n It has as many elements as the models to test (i.e. as the elements of the `model_paramGrid_list` list), and it\r\n contains dictionaries: each dictionary represents the best combination of the hyperparameters values for the\r\n associated model.\r\n best_index: int\r\n Index of `model_paramGrid_list` that indicates which is the best model.\r\n test_score: float\r\n Test score associated with the best model.\r\n ax: matplotlib.axes.Axes\r\n The matplotlib Axes where the plot has been made.\r\n If `plot` is False, then it is None.\r\n\r\n See also\r\n ----------\r\n hyperparameters_validation:\r\n select the best combination of values for the specified hyperparameters of the specified model on the given dataset.\r\n\r\n Notes\r\n ----------\r\n - If `regr` is True, the validation scores are errors (MSE, i.e. Mean Squared Errors): this means that the best\r\n model is the one associated with the minimum validation score.\r\n Otherwise, the validation scores are accuracies: this means that the best model is the one associated with the\r\n maximum validation score.\r\n - If `time_series` is False, the training-test splitting of the dataset is made randomly. In addition, the cross\r\n validation strategy performed is the classic k-fold cross validation: the number of folds is specified by `n_folds`.\r\n Otherwise, if `time_series` is True, the training-test sets are simply obtained by splitting the dataset into two\r\n contiguous parts. In addition, the cross validation strategy performed is the sklearn TimeSeriesSplit.\r\n \"\"\"\r\n\r\n if not scale_list: # `scale_list` is either None or False\r\n scale_list = [False]*len(model_paramGrid_list)\r\n elif scale_list is True: # `scale_list` is True\r\n scale_list = [True]*len(model_paramGrid_list)\r\n\r\n # Numpy matrix (np.array) which has as many rows as the models and which has two columns, one for the training scores and\r\n # the other for the validation scores. At the beginning it is a list of tuples.\r\n models_train_val_score = []\r\n # List which has as many elements as the models: for each model there is the dictionary of the best combination of\r\n # hyperparameters values.\r\n models_best_params = []\r\n # List which has as many elements as the models: for each model there is the test score (associated with the best\r\n # combination of hyperparameters values).\r\n models_test_score = []\r\n\r\n for i,triple in enumerate(model_paramGrid_list): # Iterate through all the cuples model-param_grid\r\n model,param_grid = triple[1:]\r\n\r\n # Apply the grid search on model-param_grid\r\n params, train_val_scores, best_index, test_score = hyperparameters_validation(X, y, model, param_grid,\r\n scale=scale_list[i],\r\n test_size=test_size,\r\n time_series=time_series,\r\n random_state=random_state,\r\n n_folds=n_folds, regr=regr)\r\n\r\n models_train_val_score.append(tuple(train_val_scores[best_index])) # Add the row for that model\r\n models_best_params.append(params[best_index]) # Add the element for that model\r\n models_test_score.append(test_score) # Add the element for that model\r\n\r\n models_train_val_score = np.array(models_train_val_score) # Transform into numpy matrix (i.e. np.array)\r\n\r\n # Find the best index (i.e. the best model)\r\n if regr:\r\n best_index = np.argmin(models_train_val_score,axis=0)[1]\r\n else:\r\n best_index = np.argmax(models_train_val_score,axis=0)[1]\r\n\r\n # Test score of the best model\r\n test_score = models_test_score[best_index]\r\n\r\n ax = None\r\n if(plot): # Make the plot\r\n if not xvalues: # Default values for the x axis\r\n xvalues = [model_paramGrid_list[i][0] for i in range(len(model_paramGrid_list))]\r\n ax = _plot_TrainVal_values(xvalues, models_train_val_score, plot_train, xlabel, title, figsize, bar=True)\r\n\r\n return models_train_val_score, models_best_params, best_index, test_score, ax\r\n\r\n\r\n\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------\r\n# FUNCTIONS THAT PERFORM THE MODEL SELECTION WITH RESPECT TO MULTIPLE DATASETS\r\n\r\n\r\ndef datasets_hyperparameter_validation(dataset_list, model, hyperparameter, hyperparameter_values, scale=False,\r\n test_size=0.2, time_series=False, random_state=123, n_folds=5, regr=True, plot=False,\r\n plot_train=False, xvalues=None, xlabel=\"Datasets\", title=\"Datasets validation\",\r\n figsize=(6,6) ,verbose=False, figsize_verbose=(6,6)):\r\n \"\"\"\r\n Select the best dataset and the best value for the specified hyperparameter of the specified model (i.e. select the best\r\n couple dataset-hyperparameter value).\r\n\r\n For each dataset in `dataset_list`, all the specified values `hyperparameter_values` are tested for the specified\r\n `hyperparameter` of `model`.\r\n In other words, on each dataset the tuning of `hyperparameter` is performed: in fact, on each dataset, the function\r\n `hyperparameter_validation` is applied. (See `hyperparameter_validation`).\r\n In the end, the best couple dataset-hyperparameter value is selected.\r\n\r\n Despite the fact that a couple dataset-hyperparameter value is selected, the main viewpoint is focused with respect to\r\n the datasets. It's a validation focused on the datasets.\r\n In fact, first of all, for each dataset the hyperparameter tuning is performed: in this way the best value is selected\r\n and its relative score is associated with the dataset (i.e. it's the score of the dataset). (In other words, on each\r\n dataset the function `hyperparameter_validation` is applied). Finally, after that, the best dataset is selected.\r\n It's a two-levels selection.\r\n\r\n This selection is made using the validation score (i.e. the best couple dataset-hyperparameter value is the one with the\r\n best validation score).\r\n The validation score is computed by splitting each dataset into the training-test sets and then by applying the cross\r\n validation on the training set.\r\n Additionally, the training and test scores are also computed.\r\n\r\n Optionally, the validation scores of the datasets can be plotted, making a graphical visualization of the dataset\r\n selection. This is the 'main' plot.\r\n Moreover, still optionally, the 'secondary' plots can be done: for each dataset, the validation scores of the\r\n `hyperparameter_values` are plotted, making a graphical visualization of the hyperparameter tuning on that dataset.\r\n (As the plot made by the `hyperparameter_validation` function).\r\n\r\n Parameters\r\n ----------\r\n dataset_list: list\r\n List of couples, where each couple is a dataset.\r\n - The first element is X, the two-dimensional np.array containing the explanatory features of the dataset.\r\n - The second element is y, the mono dimensional np.array containing the response feature of the dataset.\r\n model: sklearn.base.BaseEstimator\r\n Model which has the specified `hyperparameter`.\r\n hyperparameter: str\r\n The name of the hyperparameter that has to be validated.\r\n hyperparameter_values: list\r\n List of values for `hyperparameter` that have to be taken into account in the selection.\r\n scale: bool\r\n Indicates whether to scale or not the features in 'X' (for all the datasets).\r\n (The scaling is performed using the sklearn MinMaxScaler).\r\n test_size: float\r\n Decimal number between 0 and 1, which indicates the proportion of the test set (for each dataset).\r\n time_series: bool\r\n Indicates if the given datasets are time series dataset (i.e. datasets indexed by days).\r\n (This affects the computing of the validation scores).\r\n random_state: int\r\n Used in the training-test splitting of the datasets.\r\n n_folds: int\r\n Indicates how many folds are made in order to compute the k-fold cross validation.\r\n (It's used only if `time_series` is False).\r\n regr: bool\r\n Indicates if it's either a regression or a classification problem.\r\n plot: bool\r\n Indicates whether to plot or not the validation score values of the datasets (i.e. this is the 'main' plot).\r\n plot_train: bool\r\n Indicates whether to plot also the training scores (both in the 'main' and 'secondary' plots).\r\n xvalues: list (in general, iterable)\r\n Values that have to be put in the x axis of the 'main' plot.\r\n xlabel: str\r\n Label of the x axis of the 'main' plot.\r\n title: str\r\n Title of the 'main' plot.\r\n figsize: tuple\r\n Two dimensions of the 'main' plot.\r\n verbose: bool\r\n If True, for each dataset are plotted the validation scores of the hyperparameter tuning (these are the 'secondary'\r\n plots).\r\n (See 'hyperparameter_validation').\r\n figsize_verbose: tuple\r\n Two dimensions of the 'secondary' plots.\r\n\r\n Returns\r\n ----------\r\n datasets_train_val_score: np.array\r\n Two dimensional np.array, containing two columns: the first contains the training scores, the second the validation\r\n scores.\r\n It has as many rows as the number of datasets to test, i.e. as the number of elements in `dataset_list`.\r\n datasets_best_hyperparameter_value: list\r\n List which has as many elements as the number of the datasets (i.e. as the number of elements in `dataset_list`). For\r\n each dataset, it contains the best `hyperparameter` value on that dataset.\r\n best_index: int\r\n Index of `dataset_list` that indicates which is the best dataset.\r\n test_score: float\r\n Test score associated with the best couple dataset-hyperparameter value.\r\n axes: list\r\n List of the matplotlib Axes where the plots have been made.\r\n Firstly, the 'secondary' plots are put (if any). And, as last, the 'main' plot is put (if any).\r\n If no plot has been made, `axes` is an empty list.\r\n\r\n See also\r\n ----------\r\n hyperparameter_validation:\r\n select the best value for the specified hyperparameter of the specified model on the given dataset.\r\n\r\n Notes\r\n ----------\r\n - If `regr` is True, the validation scores are errors (MSE, i.e. Mean Squared Errors): this means that the best\r\n couple dataset-hyperparameter value is the one associated with the minimum validation score.\r\n Otherwise, the validation scores are accuracies: this means that the best couple is the one associated with the\r\n maximum validation score.\r\n - If `time_series` is False, the training-test splitting of each dataset is made randomly. In addition, the cross\r\n validation strategy performed is the classic k-fold cross validation: the number of folds is specified by `n_folds`.\r\n Otherwise, if `time_series` is True, the training-test sets are simply obtained by splitting each dataset into two\r\n contiguous parts. In addition, the cross validation strategy performed is the sklearn TimeSeriesSplit.\r\n \"\"\"\r\n\r\n # numpy matrix (i.e. np.array) which has as many rows as the datasets, and it has the training and validation scores as\r\n # columns. At the beginning it is a list.\r\n datasets_train_val_score = []\r\n # List which contains, for each dataset, the best hyperparameter value\r\n datasets_best_hyperparameter_value = []\r\n # List which contains, for each dataset, its test score (associated with the best hyperparameter value)\r\n datasets_test_score = []\r\n # List of axes\r\n axes = []\r\n\r\n for i,dataset in enumerate(dataset_list): # Iterate through all the datasets\r\n\r\n X,y = dataset\r\n\r\n # Perform the hyperparameter tuning on the current dataset\r\n train_val_scores, best_index, test_score, ax = hyperparameter_validation(X, y, model, hyperparameter,\r\n hyperparameter_values, scale=scale, test_size=test_size, time_series=time_series,\r\n random_state=random_state, n_folds=n_folds, regr=regr, plot=verbose, plot_train=plot_train,\r\n xvalues=hyperparameter_values, xlabel=hyperparameter,\r\n title=\"Dataset \"+str(i)+\" : hyperparameter validation\", figsize=figsize_verbose)\r\n\r\n datasets_train_val_score.append(tuple(train_val_scores[best_index,:])) # Add the row related to that dataset\r\n datasets_best_hyperparameter_value.append(hyperparameter_values[best_index]) # Add the element related to that dataset\r\n datasets_test_score.append(test_score) # Add the row related to that dataset\r\n if ax:\r\n axes.append(ax)\r\n\r\n datasets_train_val_score = np.array(datasets_train_val_score) # Transform into numpy\r\n\r\n # Find the best index, i.e. the best dataset (more precisely, the best couple dataset-hyperparameter value)\r\n if regr:\r\n best_index = np.argmin(datasets_train_val_score,axis=0)[1]\r\n else:\r\n best_index = np.argmax(datasets_train_val_score,axis=0)[1]\r\n\r\n # Test score of the best couple dataset-hyperparameter value\r\n test_score = datasets_test_score[best_index]\r\n\r\n if(plot): # Make the plot\r\n if not xvalues: # Default values on the x axis\r\n xvalues = range(len(dataset_list))\r\n ax = _plot_TrainVal_values(xvalues,datasets_train_val_score,plot_train,xlabel,title,figsize, bar=True)\r\n axes.append(ax)\r\n\r\n return datasets_train_val_score, datasets_best_hyperparameter_value, best_index, test_score, axes\r\n\r\n\r\ndef datasets_hyperparameters_validation(dataset_list, model, param_grid, scale=False, test_size=0.2, time_series=False,\r\n random_state=123, n_folds=5, regr=True, plot=False, plot_train=False, xvalues=None,\r\n xlabel=\"Datasets\", title=\"Datasets validation\",figsize=(6,6)):\r\n \"\"\"\r\n Select the best dataset and the best combination of values for the specified hyperparameters of the specified model (i.e.\r\n select the best couple dataset-combination of hyperparameters values).\r\n\r\n For each dataset in `dataset_list`, all the possible combinations of the hyperparameters values for `model` (specified\r\n with `param_grid`) are tested.\r\n In other words, on each dataset the tuning of the specified hyperparameters is performed in an exhaustive way: in fact,\r\n on each dataset, the function `hyperparameters_validation` is applied. (See `hyperparameters_validation`).\r\n In the end, the best couple dataset-combination of hyperparameters values is selected.\r\n\r\n Despite the fact that a couple dataset-combination of hyperparameters values is selected, the main viewpoint is focused\r\n with respect to the datasets. It's a validation focused on the datasets.\r\n In fact, first of all, for each dataset the hyperparameters tuning is performed: in this way the best combination of\r\n values is selected and its relative score is associated with the dataset (i.e. it's the score of the dataset). (In other\r\n words, on each dataset the function `hyperparameters_validation` is applied). Finally, after that, the best dataset is\r\n selected. It's a two-levels selection.\r\n\r\n This selection is made using the validation score (i.e. the best couple dataset-combination of hyperparameters values, is\r\n the one with best validation score).\r\n The validation score is computed by splitting each dataset into the training-test sets and then by applying the cross\r\n validation on the training set.\r\n Additionally, the training and test scores are also computed.\r\n\r\n Optionally, the validation scores of the datasets can be plotted, making a graphical visualization of the dataset\r\n selection.\r\n\r\n Parameters\r\n ----------\r\n dataset_list: list\r\n List of couple, where each couple is a dataset.\r\n - The first element is X, the two-dimensional np.array containing the explanatory features of the dataset.\r\n - The second element is y, the mono dimensional np.array containing the response feature of the dataset.\r\n model: sklearn.base.BaseEstimator\r\n Model which has the specified hyperparameters.\r\n param_grid: dict\r\n Dictionary which has as keys the names of the specified hyperparameters and as values the associated list of\r\n values to test.\r\n scale: bool\r\n Indicates whether to scale or not the features in 'X' (for all the datasets).\r\n (The scaling is performed using the sklearn MinMaxScaler).\r\n test_size: float\r\n Decimal number between 0 and 1, which indicates the proportion of the test set (for each dataset).\r\n time_series: bool\r\n Indicates if the given datasets are time series datasets (i.e. datasets indexed by days).\r\n (This affects the computing of the validation score).\r\n random_state: int\r\n Used in the training-test splitting of the datasets.\r\n n_folds: int\r\n Indicates how many folds are made in order to compute the k-fold cross validation.\r\n (It's used only if `time_series` is False).\r\n regr: bool\r\n Indicates if it's either a regression or a classification problem.\r\n plot: bool\r\n Indicates whether to plot or not the validation score values of the datasets.\r\n plot_train: bool\r\n Indicates whether to plot also the training scores.\r\n (It's considered only if `plot` is True).\r\n xvalues: list (in general, iterable)\r\n Values that have to be put in the x axis of the plot.\r\n xlabel: str\r\n Label of the x axis of the plot.\r\n title: str\r\n Title of the plot.\r\n figsize: tuple\r\n Two dimensions of the plot.\r\n\r\n Returns\r\n ----------\r\n datasets_train_val_score: np.array\r\n Two dimensional np.array, containing two columns: the first contains the training scores, the second the validation\r\n scores.\r\n It has as many rows as the number of datasets to test, i.e. as the number of elements in `dataset_list`.\r\n datasets_best_params: list\r\n List which has as many elements as the number of the datasets (i.e. as the number of elements in `dataset_list`). For\r\n each dataset, it contains the best combination of hyperparameters values on that dataset.\r\n Each combination is represented as a dictionary, with keys the hyperparameters names and values the associated\r\n values.\r\n best_index: int\r\n Index of `dataset_list` that indicates which is the best dataset.\r\n test_score: float\r\n Test score associated with the best couple dataset-combination of hyperparameters values.\r\n ax: matplotlib.axes.Axes\r\n The matplotlib Axes where the plot has been made.\r\n\r\n See also\r\n ----------\r\n hyperparameters_validation:\r\n select the best combination of values for the specified hyperparameters of the specified model on the given dataset.\r\n\r\n Notes\r\n ----------\r\n - If `regr` is True, the validation scores are errors (MSE, i.e. Mean Squared Errors): this means that the best\r\n couple dataset-combination of hyperparameters values is the one associated with the minimum validation score.\r\n Otherwise, the validation scores are accuracies: this means that the best couple is the one associated with the\r\n maximum validation score.\r\n - If `time_series` is False, the training-test splitting of each dataset is made randomly. In addition, the cross\r\n validation strategy performed is the classic k-fold cross validation: the number of folds is specified by `n_folds`.\r\n Otherwise, if `time_series` is True, the training-test sets are simply obtained by splitting each dataset into two\r\n contiguous parts. In addition, the cross validation strategy performed is the sklearn TimeSeriesSplit.\r\n \"\"\"\r\n\r\n # numpy matrix (i.e. np.array) which has as many rows as the datasets, and it has the training and validation scores as\r\n # columns . At the beginning it is a list.\r\n datasets_train_val_score = []\r\n # List which contains, for each dataset, the best combination of hyperparameters values (i.e. a dictionary)\r\n datasets_best_params = []\r\n # List which contains, for each dataset, its test score (associated to the best combination of hyperparameters values)\r\n datasets_test_score = []\r\n\r\n for X,y in dataset_list: # Iterate through all the datasets\r\n\r\n # Perform the exaustive hyperparameters tuning on the current dataset\r\n params, train_val_scores, best_index, test_score = hyperparameters_validation(X, y, model, param_grid, scale=scale,\r\n test_size=test_size,\r\n time_series=time_series,\r\n random_state=random_state,\r\n n_folds=n_folds, regr=regr)\r\n\r\n datasets_train_val_score.append(tuple(train_val_scores[best_index,:])) # Add the row related to that dataset\r\n datasets_best_params.append(params[best_index]) # Add the element related to that dataset\r\n datasets_test_score.append(test_score) # Add the row related to that dataset\r\n\r\n datasets_train_val_score = np.array(datasets_train_val_score) # Transform into numpy\r\n\r\n # Find the best index, i.e. the best dataset (more precisely, the best couple dataset-combination of hyperparameters\r\n # values)\r\n if regr:\r\n best_index = np.argmin(datasets_train_val_score,axis=0)[1]\r\n else:\r\n best_index = np.argmax(datasets_train_val_score,axis=0)[1]\r\n\r\n # Test score of the best couple dataset-combination of hyperparameters values\r\n test_score = datasets_test_score[best_index]\r\n\r\n ax = None\r\n if(plot): # Make the plot\r\n if not xvalues: # Default values on the x axis\r\n xvalues = range(len(dataset_list))\r\n ax = _plot_TrainVal_values(xvalues,datasets_train_val_score,plot_train,xlabel,title,figsize, bar=True)\r\n\r\n return datasets_train_val_score, datasets_best_params, best_index, test_score, ax\r\n\r\n\r\ndef datasets_models_validation(dataset_list, model_paramGrid_list, scale_list=None, test_size=0.2, time_series=False,\r\n random_state=123, n_folds=5, regr=True, plot=False, plot_train=False, xvalues=None,\r\n xlabel=\"Datasets\", title=\"Datasets validation\", figsize=(6,6) ,verbose=False,\r\n figsize_verbose=(6,6)):\r\n \"\"\"\r\n Select the best dataset and the best model (i.e. select the best couple dataset-model).\r\n\r\n For each dataset in `dataset_list`, all the models in `model_paramGrid_list` are tested: each model is tested performing\r\n an exhaustive tuning of the specified hyperparameters. In fact, `model_paramGrid_list` also contains, for each model, the\r\n grid of the hyperparameters that have to be tested on that model (i.e. the grid which contains the values to test for\r\n each specified hyperparameter of the model).\r\n In other words, on each dataset the selection of the best model is performed: in fact, on each dataset, the function\r\n `models_validation` is applied. (See `models_validation`).\r\n In the end, the best couple dataset-model is selected.\r\n\r\n Despite the fact that a couple dataset-model is selected, the main viewpoint is focused with respect to the datasets.\r\n It's a validation focused on the datasets.\r\n In fact, first of all, for each dataset the model selection is performed: in this way the best model is selected\r\n and its relative score is associated with the dataset (i.e. it's the score of the dataset). (In other words, on each\r\n dataset the function `models_validation` is applied). Finally, after that, the best dataset is selected.\r\n It's a two-levels selection.\r\n\r\n This selection is made using the validation score (i.e. the best couple dataset-model is the one with best validation\r\n score).\r\n The validation score is computed by splitting each dataset into the training-test sets and then by applying the cross\r\n validation on the training set.\r\n Additionally, the training and test scores are also computed.\r\n\r\n Optionally, the validation scores of the datasets can be plotted, making a graphical visualization of the dataset\r\n selection. This is the 'main' plot.\r\n Moreover, still optionally, the 'secondary' plots can be done: for each dataset, the validation scores of the models are\r\n plotted, making a graphical visualization of the models selection on that dataset. (As the plot made by the\r\n `models_validation` function).\r\n\r\n Parameters\r\n ----------\r\n dataset_list: list\r\n List of couples, where each couple is a dataset.\r\n - The first element is X, the two-dimensional np.array containing the explanatory features of the dataset.\r\n - The second element is y, the mono dimensional np.array containing the response feature of the dataset.\r\n model_paramGrid_list: list\r\n List that specifies the models and the relative grid of hyperparameters to be tested.\r\n It's a list of triples (i.e. tuples), where each triple represents a model:\r\n - the first element is a string, which is a mnemonic name of that model;\r\n - the second element is the sklearn model;\r\n - the third element is the grid of hyperparameters to test for that model. It's a dictionary, with the same\r\n structure of parameter `param_grid` of the function `hyperparameters_validation`.\r\n scale_list: list or bool\r\n List of booleans, which has as many elements as the number of models to test (i.e. number of elements in the\r\n `model_paramGrid_list` list).\r\n This list indicates, for each different model, if the features in 'X' have to be scaled or not (for all the datasets).\r\n `scale_list` can be None or False: in this case the 'X' features aren't scaled for any model. `scale_list` can be\r\n True: in this case the 'X' features are scaled for all the models.\r\n test_size: float\r\n Decimal number between 0 and 1, which indicates the proportion of the test set (for each dataset).\r\n time_series: bool\r\n Indicates if the given datasets are time series dataset (i.e. datasets indexed by days).\r\n (This affects the computing of the validation score).\r\n random_state: int\r\n Used in the training-test splitting of the datasets.\r\n n_folds: int\r\n Indicates how many folds are made in order to compute the k-fold cross validation.\r\n (It's used only if `time_series` is False).\r\n regr: bool\r\n Indicates if it's either a regression or a classification problem.\r\n plot: bool\r\n Indicates whether to plot or not the validation score values of the datasets (i.e. this is the 'main' plot).\r\n plot_train: bool\r\n Indicates whether to plot also the training scores (both in the 'main' and 'secondary' plots).\r\n xvalues: list (in general, iterable)\r\n Values that have to be put in the x axis of the 'main' plot.\r\n xlabel: str\r\n Label of the x axis of the 'main' plot.\r\n title: str\r\n Title of the 'main' plot.\r\n figsize: tuple\r\n Two dimensions of the 'main' plot.\r\n verbose: bool\r\n If True, for each dataset the validation scores of the models are plotted (i.e. these are the 'secondary' plots).\r\n (See 'models_validation').\r\n figsize_verbose: tuple\r\n Two dimensions of the 'secondary' plots.\r\n\r\n Returns\r\n ----------\r\n datasets_train_val_score: np.array\r\n Two dimensional np.array, containing two columns: the first contains the training scores, the second the validation\r\n scores.\r\n It has as many rows as the number of datasets to test, i.e. as the number of elements in `dataset_list`.\r\n datasets_best_model: list\r\n List which has as many elements as the number of the datasets (i.e. number of elements in `dataset_list`). For\r\n each dataset, it contains the best model for that dataset.\r\n More precisely, it is a list of triple:\r\n - the first element is the index of `model_paramGrid_list` which indicates the best model;\r\n - the second element is the mnemonic name of the best model;\r\n - the third element is the best combination of hyperparameters values on that best model (i.e. it's a dictionary\r\n which has as keys the hyperparameters names and as values their associated values).\r\n best_index: int\r\n Index of `dataset_list` that indicates which is the best dataset.\r\n test_score: float\r\n Test score associated with the best couple dataset-model.\r\n axes: list\r\n List of the matplotlib Axes where the plots have been made.\r\n Firstly, the 'secondary' plots are put (if any). And, as last, the 'main' plot is put (if any).\r\n If no plot has been made, `axes` is an empty list.\r\n\r\n See also\r\n ----------\r\n models_validation: select the best model on the given dataset.\r\n\r\n Notes\r\n ----------\r\n - If `regr` is True, the validation scores are errors (MSE, i.e. Mean Squared Errors): this means that the best\r\n couple dataset-model is the one associated with the minimum validation score.\r\n Otherwise, the validation scores are accuracies: this means that the best couple is the one associated with the\r\n maximum validation score.\r\n - If `time_series` is False, the training-test splitting of each dataset is made randomly. In addition, the cross\r\n validation strategy performed is the classic k-fold cross validation: the number of folds is specified by `n_folds`.\r\n Otherwise, if `time_series` is True, the training-test sets are simply obtained by splitting each dataset into two\r\n contiguous parts. In addition, the cross validation strategy performed is the sklearn TimeSeriesSplit.\r\n \"\"\"\r\n\r\n # numpy matrix (i.e. np.array) which has as many rows as the datasets, and it has the training and validation scores as\r\n # columns. At the beginning it is a list.\r\n datasets_train_val_score = []\r\n # List which contains, for each dataset, the best model. I.e. there is the triple index-model name-best combination of\r\n # hyperparameters values\r\n datasets_best_model = []\r\n # List which contains, for each dataset, its test score (associated to the best model)\r\n datasets_test_score = []\r\n # List of axes\r\n axes = []\r\n\r\n for i,dataset in enumerate(dataset_list): # Iterate through all the datasets\r\n\r\n X,y = dataset\r\n\r\n # Perform the models validation on the current dataset\r\n models_train_val_score, models_best_params, best_index, test_score, ax = models_validation(X, y,\r\n model_paramGrid_list,\r\n scale_list=scale_list,\r\n test_size=test_size,\r\n time_series=time_series,\r\n random_state=random_state,\r\n n_folds=n_folds,\r\n regr=regr, plot=verbose,\r\n plot_train=plot_train,\r\n xlabel=\"Models\",\r\n title=(\"Dataset \"+str(i)+\r\n \" : models validation\"),\r\n figsize=figsize_verbose)\r\n\r\n datasets_train_val_score.append(tuple(models_train_val_score[best_index,:])) # Add the row related to that dataset\r\n # Add the element related to that dataset\r\n datasets_best_model.append((best_index,model_paramGrid_list[best_index][0],models_best_params[best_index]))\r\n datasets_test_score.append(test_score) # Add the element related to that dataset\r\n if ax:\r\n axes.append(ax)\r\n\r\n datasets_train_val_score = np.array(datasets_train_val_score) # Transform into numpy\r\n\r\n # Find the best index, i.e. the best dataset (more precisely, the best couple dataset-model)\r\n if regr:\r\n best_index = np.argmin(datasets_train_val_score,axis=0)[1]\r\n else:\r\n best_index = np.argmax(datasets_train_val_score,axis=0)[1]\r\n\r\n # Test score of the best couple dataset-model\r\n test_score = datasets_test_score[best_index]\r\n\r\n if(plot): # Make the plot\r\n if not xvalues: # Default values on the x axis\r\n xvalues = range(len(dataset_list))\r\n ax = _plot_TrainVal_values(xvalues,datasets_train_val_score,plot_train,xlabel,title,figsize, bar=True)\r\n axes.append(ax)\r\n\r\n return datasets_train_val_score, datasets_best_model, best_index, test_score, axes\r\n" ]
[ [ "sklearn.model_selection.GridSearchCV", "sklearn.model_selection.cross_val_score", "matplotlib.pyplot.subplots", "sklearn.preprocessing.PolynomialFeatures", "sklearn.model_selection.train_test_split", "sklearn.model_selection.TimeSeriesSplit", "numpy.argmax", "numpy.mean", "sklearn.linear_model.LinearRegression", "numpy.argmin", "numpy.var", "numpy.array", "numpy.sum", "sklearn.preprocessing.MinMaxScaler" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tensorflow/tpu-demos
[ "8aac591077e5781785aa6c22bc400472ba14dada", "8aac591077e5781785aa6c22bc400472ba14dada", "8aac591077e5781785aa6c22bc400472ba14dada", "8aac591077e5781785aa6c22bc400472ba14dada" ]
[ "models/official/unet3d/unet_main.py", "models/official/amoeba_net/tf_hub.py", "models/official/detection/utils/object_detection/box_list_ops.py", "models/official/mnasnet/imagenet_input.py" ]
[ "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nr\"\"\"Training script for UNet-3D.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.compat.v1 import estimator as tf_estimator\n\nfrom hyperparameters import params_dict\nimport input_reader\nimport tpu_executor\nimport unet_config\nimport unet_model\n\n\ntpu_executor.define_tpu_flags()\n\nflags.DEFINE_string(\n 'mode', 'train', 'Mode to run: train or eval or train_and_eval '\n '(default: train)')\nflags.DEFINE_string('model_dir', None, 'Location of model_dir')\nflags.DEFINE_string('training_file_pattern', '', 'Location of the train data.')\nflags.DEFINE_string('eval_file_pattern', '', 'Location of ther eval data')\nflags.DEFINE_string('config_file', '', 'a YAML file which specifies overrides.')\nflags.DEFINE_string('params_override', '',\n 'A JSON-style string that specifies overrides.')\nflags.DEFINE_integer('min_eval_interval', 180,\n 'Minimum seconds between evaluations.')\nflags.DEFINE_integer(\n 'eval_timeout', None,\n 'Maximum seconds between checkpoints before evaluation terminates.')\n\nFLAGS = flags.FLAGS\n\n\ndef run_executer(params,\n train_input_shapes=None, eval_input_shapes=None,\n train_input_fn=None, eval_input_fn=None):\n \"\"\"Runs Mask RCNN model on distribution strategy defined by the user.\"\"\"\n executer = tpu_executor.TPUEstimatorExecuter(\n unet_model.unet_model_fn, params,\n train_input_shapes=train_input_shapes,\n eval_input_shapes=eval_input_shapes)\n\n if FLAGS.mode == 'train':\n assert train_input_fn is not None\n results = executer.train(train_input_fn)\n elif FLAGS.mode == 'eval':\n assert eval_input_fn is not None\n results = executer.evaluate(eval_input_fn)\n elif FLAGS.mode == 'train_and_eval':\n assert train_input_fn is not None\n assert eval_input_fn is not None\n results = executer.train_and_eval(train_input_fn, eval_input_fn)\n else:\n raise ValueError('Mode must be one of `train`, `eval`, or `train_and_eval`')\n\n return results\n\n\ndef main(argv):\n del argv # Unused.\n\n params = params_dict.ParamsDict(unet_config.UNET_CONFIG,\n unet_config.UNET_RESTRICTIONS)\n params = params_dict.override_params_dict(\n params, FLAGS.config_file, is_strict=False)\n\n if FLAGS.training_file_pattern:\n params.override({'training_file_pattern': FLAGS.training_file_pattern},\n is_strict=True)\n\n if FLAGS.eval_file_pattern:\n params.override({'eval_file_pattern': FLAGS.eval_file_pattern},\n is_strict=True)\n\n train_epoch_steps = params.train_item_count // params.train_batch_size\n eval_epoch_steps = params.eval_item_count // params.eval_batch_size\n\n params.override(\n {\n 'model_dir': FLAGS.model_dir,\n 'min_eval_interval': FLAGS.min_eval_interval,\n 'eval_timeout': FLAGS.eval_timeout,\n 'tpu_config': tpu_executor.get_tpu_flags(),\n 'lr_decay_steps': train_epoch_steps,\n 'train_steps': params.train_epochs * train_epoch_steps,\n 'eval_steps': eval_epoch_steps,\n },\n is_strict=False)\n\n params = params_dict.override_params_dict(\n params, FLAGS.params_override, is_strict=True)\n\n params.validate()\n params.lock()\n\n train_input_fn = None\n eval_input_fn = None\n train_input_shapes = None\n eval_input_shapes = None\n if FLAGS.mode in ('train', 'train_and_eval'):\n train_input_fn = input_reader.LiverInputFn(\n params.training_file_pattern, params, mode=tf_estimator.ModeKeys.TRAIN)\n train_input_shapes = train_input_fn.get_input_shapes(params)\n if FLAGS.mode in ('eval', 'train_and_eval'):\n eval_input_fn = input_reader.LiverInputFn(\n params.eval_file_pattern, params, mode=tf_estimator.ModeKeys.EVAL)\n eval_input_shapes = eval_input_fn.get_input_shapes(params)\n\n assert train_input_shapes is not None or eval_input_shapes is not None\n run_executer(params,\n train_input_shapes=train_input_shapes,\n eval_input_shapes=eval_input_shapes,\n train_input_fn=train_input_fn,\n eval_input_fn=eval_input_fn)\n\n\nif __name__ == '__main__':\n tf.disable_v2_behavior()\n app.run(main)\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nr\"\"\"Provide functionalities to export and eval tf_hub module.\n\nExample use of export_to_hub:\n\n tf_hub.py --tf_hub_mode='export_to_hub' --cell_name=amoeba_net_a \\\n --reduction_size=448 --num_cells=18 --image_size=331 \\\n --drop_connect_keep_prob=0.7 \\\n --export_path=/tmp/module_export \\\n --model_dir=/ADD_PATH_WITH_1001_CLASSES_HERE \\\n --alsologtostderr\n\nExample use of eval_from_hub\n tf_hub.py --tf_hub_mode='eval_from_hub' --cell_name=amoeba_net_a \\\n --reduction_size=448 --num_cells=18 --image_size=331 \\\n --export_path=/tmp/module_export \\\n --data_dir=/ADD_DATA_PATH_HERE \\\n --model_dir=/ADD_PATH_WITH_1001_CLASSES_HERE \\\n --eval_batch_size=40 --alsologtostderr\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\n\n# Standard Imports\nfrom absl import app\nfrom absl import flags\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.compat.v1 import estimator as tf_estimator\nimport tensorflow_hub as hub\n\nimport amoeba_net\nimport amoeba_net_model as model_lib\nimport model_builder\nfrom tensorflow.contrib import slim\n\nflags.DEFINE_string('tf_hub_mode', 'export_to_hub',\n 'export_to_hub|eval_from_hub')\n\nflags.DEFINE_string('export_path', None,\n 'Directory where export output is stored')\n\nflags.DEFINE_bool(\n 'export_feature_vector', False,\n 'If true, network builder only returns feature vector after global_pool '\n 'without the fully connected layer.')\n\nflags.DEFINE_bool(\n 'dryrun_with_untrained_weights', None,\n 'FOR TESTING USE ONLY. If set, export_to_hub is done without restoring '\n 'the model\\'s trained weights. This helps test the Python code quickly but '\n 'makes the resulting module useless.')\n\n\nFLAGS = flags.FLAGS\n\n\ndef _make_module_fn(hparams, num_classes):\n \"\"\"Returns a module_fn for use with hub.create_module_spec().\"\"\"\n\n def _module_fn(is_training):\n \"\"\"A module_fn for use with hub.create_module_spec().\n\n Args:\n is_training: a boolean, passed to the config.network_fn.\n This is meant to control whether batch norm, dropout etc. are built\n in training or inference mode for this graph version.\n\n Raises:\n ValueError: if network_fn outputs are not as expected.\n \"\"\"\n # Set up the module input, and attach an ImageModuleInfo about it.\n with tf.name_scope('hub_input'):\n default_size = (hparams.image_size,) * 2\n image_module_info = hub.ImageModuleInfo()\n size_info = image_module_info.default_image_size\n size_info.height, size_info.width = default_size\n # TODO(b/72731449): Support variable input size.\n shape = (None,) + default_size + (3,)\n images = tf.placeholder(dtype=tf.float32, shape=shape, name='images')\n hub.attach_image_module_info(image_module_info)\n # The input is expected to have RGB color values in the range [0,1]\n # and gets converted for AmoebaNet to the Inception-style range [-1,+1].\n scaled_images = tf.multiply(images, 2.0)\n scaled_images = tf.subtract(scaled_images, 1.0)\n\n # Build the net.\n logits, end_points = model_builder.build_network(scaled_images, num_classes,\n is_training, hparams)\n\n with tf.name_scope('hub_output'):\n # Extract the feature_vectors output.\n try:\n feature_vectors = end_points['global_pool']\n except KeyError:\n tf.logging.error('Valid keys of end_points are:', ', '.join(end_points))\n raise\n with tf.name_scope('feature_vector'):\n if feature_vectors.shape.ndims != 2:\n raise ValueError(\n 'Wrong rank (expected 2 after squeeze) '\n 'in feature_vectors:', feature_vectors)\n # Extract the logits output (if applicable).\n if num_classes:\n with tf.name_scope('classification'):\n if logits.shape.ndims != 2:\n raise ValueError('Wrong rank (expected 2) in logits:', logits)\n\n # Add named signatures.\n hub.add_signature('image_feature_vector', dict(images=images),\n dict(end_points, default=feature_vectors))\n if num_classes:\n hub.add_signature('image_classification', dict(images=images),\n dict(end_points, default=logits))\n # Add the default signature.\n if num_classes:\n hub.add_signature('default', dict(images=images), dict(default=logits))\n else:\n hub.add_signature('default', dict(images=images),\n dict(default=feature_vectors))\n return _module_fn\n\n\ndef export_to_hub(checkpoint_path, export_path, num_classes, hparams):\n \"\"\"Exports the network as a TF-Hub Module.\n\n If a positive integer num_classes is given, a module for image classification\n is exported. If num_classes is 0 or None, a module for feature vector\n extraction is exported. In both cases, the default signature returns\n a default output that matches the Python slim API net, _ = network_fn(...).\n\n Args:\n checkpoint_path: a string with the file name of the checkpoint from which\n the trained weights are copied into the Module.\n FOR TESTING USE ONLY, this can be set to empty or None, to skip\n restoring weights, which ignores the checkpoint and copies the random\n initializer values of the weights instead.\n export_path: a string with the directory to pass to hub.Module.export().\n num_classes: an integer with the number of classes for which the given\n checkpoint has been trained. If 0 or None, the classification layer\n is omitted.\n hparams: hyper parameters.\n \"\"\"\n module_fn = _make_module_fn(hparams, num_classes)\n tags_and_args = [\n # The default graph is built with batch_norm, dropout etc. in inference\n # mode. This graph version is good for inference, not training.\n ([], {\n 'is_training': False\n }),\n # A separate 'train' graph builds batch_norm, dropout etc. in training\n # mode.\n (['train'], {\n 'is_training': True\n }),\n ]\n drop_collections = [\n 'moving_vars', tf.GraphKeys.GLOBAL_STEP,\n tf.GraphKeys.MOVING_AVERAGE_VARIABLES\n ]\n spec = hub.create_module_spec(module_fn, tags_and_args, drop_collections)\n\n with tf.Graph().as_default():\n module = hub.Module(spec)\n init_fn = _get_init_fn(\n module,\n checkpoint_path,\n hparams.moving_average_decay > 0,\n moving_averages_blacklist_regex='global_step')\n with tf.Session() as session:\n init_fn(session)\n module.export(export_path, session=session)\n\n tf.logging.info('Export to {} succeeded.'.format(export_path))\n\n\ndef _get_init_fn(module,\n checkpoint_path,\n export_moving_averages=False,\n moving_averages_blacklist_regex=None):\n \"\"\"Returns init_fn for the session that calls hub.Module.export().\"\"\"\n if not checkpoint_path:\n tf.logging.warn('DRYRUN: using random weight initializers, no checkpoint')\n return lambda session: session.run(tf.global_variables_initializer())\n\n # Build `variables_to_restore` as a map from names in the checkpoint to the\n # variable in the instantiated module.\n if export_moving_averages:\n variables_to_restore = {}\n num_averaged = num_blacklisted = 0\n for variable_name, variable in module.variable_map.items():\n if (moving_averages_blacklist_regex and\n re.match(moving_averages_blacklist_regex, variable_name)):\n num_blacklisted += 1\n else:\n variable_name += '/ExponentialMovingAverage'\n num_averaged += 1\n variables_to_restore[variable_name] = variable\n tf.logging.info('Export of moving averages is applied to %d variables '\n 'with %d exempted by matching the blacklist_regex' %\n (num_averaged, num_blacklisted))\n else:\n variables_to_restore = module.variable_map\n tf.logging.info('Export of moving averages is disabled')\n\n unchecked_init_fn = slim.assign_from_checkpoint_fn(checkpoint_path,\n variables_to_restore)\n def init_fn(session):\n unchecked_init_fn(session)\n _check_shapes_of_restored_variables(session, variables_to_restore)\n\n return init_fn\n\n\ndef _check_shapes_of_restored_variables(session, variables_to_restore):\n \"\"\"Raises TypeError if restored variables have unexpected shapes.\"\"\"\n num_errors = 0\n for variable_name, variable in variables_to_restore.items():\n graph_shape = variable.value().shape\n # Values are big, but tf.shape(..) whould echo graph_shape if fully defined.\n checkpoint_shape = session.run(variable.value()).shape\n if not graph_shape.is_compatible_with(checkpoint_shape):\n tf.logging.error('Shape mismatch for variable %s: '\n 'graph expects %s but checkpoint has %s' %\n (variable_name, graph_shape, checkpoint_shape))\n num_errors += 1\n if num_errors:\n raise TypeError(\n 'Shape mismatch for %d variables, see error log for list.' % num_errors)\n\n\ndef _make_model_fn(hub_module_spec):\n \"\"\"Returns a model_fn for estimator using hub_module.\"\"\"\n\n def _model_fn(features, labels, mode, params):\n \"\"\"model_fn for estimator.\"\"\"\n del params\n features = tf.transpose(features, [3, 0, 1, 2]) # HWCN to NHWC\n hub_module = hub.Module(spec=hub_module_spec, trainable=False)\n logits = hub_module(features)\n labels_onehot = tf.one_hot(labels, logits.shape[1])\n loss = tf.losses.softmax_cross_entropy(labels_onehot, logits)\n\n eval_metric_ops = None\n\n def metric_fn(labels, logits):\n \"\"\"Evaluation metric fn. Performed on CPU, do not reference TPU ops.\"\"\"\n predictions = tf.argmax(logits, axis=1)\n top_1_accuracy = tf.metrics.accuracy(labels, predictions)\n in_top_5 = tf.cast(tf.nn.in_top_k(logits, labels, 5), tf.float32)\n top_5_accuracy = tf.metrics.mean(in_top_5)\n\n return {\n 'top_1_accuracy': top_1_accuracy,\n 'top_5_accuracy': top_5_accuracy,\n }\n\n eval_metric_ops = metric_fn(labels, logits)\n return tf_estimator.EstimatorSpec(\n mode=mode, loss=loss, train_op=None, eval_metric_ops=eval_metric_ops)\n\n return _model_fn\n\n\ndef eval_from_hub(model_dir, input_fn, eval_steps):\n \"\"\"Eval using hub module.\"\"\"\n hub_module_spec = hub.load_module_spec(model_dir)\n run_config = tf_estimator.RunConfig(model_dir=model_dir)\n image_classifier = tf_estimator.Estimator(\n model_fn=_make_model_fn(hub_module_spec), config=run_config, params={})\n eval_results = image_classifier.evaluate(input_fn=input_fn, steps=eval_steps)\n tf.logging.info('Evaluation results: %s' % eval_results)\n\n\ndef main(_):\n mode = FLAGS.tf_hub_mode\n data_dir = amoeba_net.FLAGS.data_dir\n model_dir = amoeba_net.FLAGS.model_dir\n hparams = amoeba_net.build_hparams()\n hparams.add_hparam('drop_path_burn_in_steps', 0)\n hparams.set_hparam('use_tpu', False)\n # So far, there is no standardized way of exposing aux heads for\n # fine-tuning Hub image modules. Disable aux heads to avoid putting unused\n # variables and ops into the module.\n hparams.set_hparam('use_aux_head', False)\n eval_steps = FLAGS.num_eval_images // FLAGS.eval_batch_size\n export_path = FLAGS.export_path or (model_dir + '/export')\n\n input_pipeline = model_lib.InputPipeline(\n is_training=False, data_dir=data_dir, hparams=hparams, eval_from_hub=True)\n\n if mode == 'eval_from_hub':\n eval_from_hub(export_path, input_pipeline.input_fn, eval_steps=eval_steps)\n elif mode == 'export_to_hub':\n num_classes = (None if FLAGS.export_feature_vector else\n input_pipeline.num_classes)\n\n if FLAGS.dryrun_with_untrained_weights:\n checkpoint_path = None\n else:\n checkpoint_path = tf.train.latest_checkpoint(model_dir)\n if not checkpoint_path:\n raise IOError('No checkpoint found.')\n export_to_hub(\n checkpoint_path, export_path, num_classes, hparams)\n else:\n raise ValueError('Unsupported tf_hub_mode = {}'.format(mode))\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n app.run(main)\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Bounding Box List operations.\n\nExample box operations that are supported:\n * areas: compute bounding box areas\n * iou: pairwise intersection-over-union scores\n * sq_dist: pairwise distances between bounding boxes\n\nWhenever box_list_ops functions output a BoxList, the fields of the incoming\nBoxList are retained unless documented otherwise.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom six.moves import range\nimport tensorflow.compat.v1 as tf\n\nfrom utils.object_detection import box_list\nfrom utils.object_detection import ops\n\n\nclass SortOrder(object):\n \"\"\"Enum class for sort order.\n\n Attributes:\n ascend: ascend order.\n descend: descend order.\n \"\"\"\n ascend = 1\n descend = 2\n\n\ndef area(boxlist, scope=None):\n \"\"\"Computes area of boxes.\n\n Args:\n boxlist: BoxList holding N boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N] representing box areas.\n \"\"\"\n with tf.name_scope(scope, 'Area'):\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])\n\n\ndef height_width(boxlist, scope=None):\n \"\"\"Computes height and width of boxes in boxlist.\n\n Args:\n boxlist: BoxList holding N boxes\n scope: name scope.\n\n Returns:\n Height: A tensor with shape [N] representing box heights.\n Width: A tensor with shape [N] representing box widths.\n \"\"\"\n with tf.name_scope(scope, 'HeightWidth'):\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n return tf.squeeze(y_max - y_min, [1]), tf.squeeze(x_max - x_min, [1])\n\n\ndef scale(boxlist, y_scale, x_scale, scope=None):\n \"\"\"scale box coordinates in x and y dimensions.\n\n Args:\n boxlist: BoxList holding N boxes\n y_scale: (float) scalar tensor\n x_scale: (float) scalar tensor\n scope: name scope.\n\n Returns:\n boxlist: BoxList holding N boxes\n \"\"\"\n with tf.name_scope(scope, 'Scale'):\n y_scale = tf.cast(y_scale, tf.float32)\n x_scale = tf.cast(x_scale, tf.float32)\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n y_min = y_scale * y_min\n y_max = y_scale * y_max\n x_min = x_scale * x_min\n x_max = x_scale * x_max\n scaled_boxlist = box_list.BoxList(\n tf.concat([y_min, x_min, y_max, x_max], 1))\n return _copy_extra_fields(scaled_boxlist, boxlist)\n\n\ndef clip_to_window(boxlist, window, filter_nonoverlapping=True, scope=None):\n \"\"\"Clip bounding boxes to a window.\n\n This op clips any input bounding boxes (represented by bounding box\n corners) to a window, optionally filtering out boxes that do not\n overlap at all with the window.\n\n Args:\n boxlist: BoxList holding M_in boxes\n window: a tensor of shape [4] representing the [y_min, x_min, y_max, x_max]\n window to which the op should clip boxes.\n filter_nonoverlapping: whether to filter out boxes that do not overlap at\n all with the window.\n scope: name scope.\n\n Returns:\n a BoxList holding M_out boxes where M_out <= M_in\n \"\"\"\n with tf.name_scope(scope, 'ClipToWindow'):\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window)\n y_min_clipped = tf.maximum(tf.minimum(y_min, win_y_max), win_y_min)\n y_max_clipped = tf.maximum(tf.minimum(y_max, win_y_max), win_y_min)\n x_min_clipped = tf.maximum(tf.minimum(x_min, win_x_max), win_x_min)\n x_max_clipped = tf.maximum(tf.minimum(x_max, win_x_max), win_x_min)\n clipped = box_list.BoxList(\n tf.concat([y_min_clipped, x_min_clipped, y_max_clipped, x_max_clipped],\n 1))\n clipped = _copy_extra_fields(clipped, boxlist)\n if filter_nonoverlapping:\n areas = area(clipped)\n nonzero_area_indices = tf.cast(\n tf.reshape(tf.where(tf.greater(areas, 0.0)), [-1]), tf.int32)\n clipped = gather(clipped, nonzero_area_indices)\n return clipped\n\n\ndef prune_outside_window(boxlist, window, scope=None):\n \"\"\"Prunes bounding boxes that fall outside a given window.\n\n This function prunes bounding boxes that even partially fall outside the given\n window. See also clip_to_window which only prunes bounding boxes that fall\n completely outside the window, and clips any bounding boxes that partially\n overflow.\n\n Args:\n boxlist: a BoxList holding M_in boxes.\n window: a float tensor of shape [4] representing [ymin, xmin, ymax, xmax]\n of the window\n scope: name scope.\n\n Returns:\n pruned_corners: a tensor with shape [M_out, 4] where M_out <= M_in\n valid_indices: a tensor with shape [M_out] indexing the valid bounding boxes\n in the input tensor.\n \"\"\"\n with tf.name_scope(scope, 'PruneOutsideWindow'):\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window)\n coordinate_violations = tf.concat([\n tf.less(y_min, win_y_min), tf.less(x_min, win_x_min),\n tf.greater(y_max, win_y_max), tf.greater(x_max, win_x_max)\n ], 1)\n valid_indices = tf.reshape(\n tf.where(tf.logical_not(tf.reduce_any(coordinate_violations, 1))), [-1])\n return gather(boxlist, valid_indices), valid_indices\n\n\ndef prune_completely_outside_window(boxlist, window, scope=None):\n \"\"\"Prunes bounding boxes that fall completely outside of the given window.\n\n The function clip_to_window prunes bounding boxes that fall\n completely outside the window, but also clips any bounding boxes that\n partially overflow. This function does not clip partially overflowing boxes.\n\n Args:\n boxlist: a BoxList holding M_in boxes.\n window: a float tensor of shape [4] representing [ymin, xmin, ymax, xmax]\n of the window\n scope: name scope.\n\n Returns:\n pruned_boxlist: a new BoxList with all bounding boxes partially or fully in\n the window.\n valid_indices: a tensor with shape [M_out] indexing the valid bounding boxes\n in the input tensor.\n \"\"\"\n with tf.name_scope(scope, 'PruneCompleteleyOutsideWindow'):\n y_min, x_min, y_max, x_max = tf.split(\n value=boxlist.get(), num_or_size_splits=4, axis=1)\n win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window)\n coordinate_violations = tf.concat([\n tf.greater_equal(y_min, win_y_max), tf.greater_equal(x_min, win_x_max),\n tf.less_equal(y_max, win_y_min), tf.less_equal(x_max, win_x_min)\n ], 1)\n valid_indices = tf.reshape(\n tf.where(tf.logical_not(tf.reduce_any(coordinate_violations, 1))), [-1])\n return gather(boxlist, valid_indices), valid_indices\n\n\ndef intersection(boxlist1, boxlist2, scope=None):\n \"\"\"Compute pairwise intersection areas between boxes.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N, M] representing pairwise intersections\n \"\"\"\n with tf.name_scope(scope, 'Intersection'):\n y_min1, x_min1, y_max1, x_max1 = tf.split(\n value=boxlist1.get(), num_or_size_splits=4, axis=1)\n y_min2, x_min2, y_max2, x_max2 = tf.split(\n value=boxlist2.get(), num_or_size_splits=4, axis=1)\n all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2))\n all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2))\n intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin)\n all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2))\n all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2))\n intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin)\n return intersect_heights * intersect_widths\n\n\ndef matched_intersection(boxlist1, boxlist2, scope=None):\n \"\"\"Compute intersection areas between corresponding boxes in two boxlists.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding N boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N] representing pairwise intersections\n \"\"\"\n with tf.name_scope(scope, 'MatchedIntersection'):\n y_min1, x_min1, y_max1, x_max1 = tf.split(\n value=boxlist1.get(), num_or_size_splits=4, axis=1)\n y_min2, x_min2, y_max2, x_max2 = tf.split(\n value=boxlist2.get(), num_or_size_splits=4, axis=1)\n min_ymax = tf.minimum(y_max1, y_max2)\n max_ymin = tf.maximum(y_min1, y_min2)\n intersect_heights = tf.maximum(0.0, min_ymax - max_ymin)\n min_xmax = tf.minimum(x_max1, x_max2)\n max_xmin = tf.maximum(x_min1, x_min2)\n intersect_widths = tf.maximum(0.0, min_xmax - max_xmin)\n return tf.reshape(intersect_heights * intersect_widths, [-1])\n\n\ndef iou(boxlist1, boxlist2, scope=None):\n \"\"\"Computes pairwise intersection-over-union between box collections.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N, M] representing pairwise iou scores.\n \"\"\"\n with tf.name_scope(scope, 'IOU'):\n intersections = intersection(boxlist1, boxlist2)\n areas1 = area(boxlist1)\n areas2 = area(boxlist2)\n unions = (\n tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - intersections)\n return tf.where(\n tf.equal(intersections, 0.0),\n tf.zeros_like(intersections), tf.truediv(intersections, unions))\n\n\ndef matched_iou(boxlist1, boxlist2, scope=None):\n \"\"\"Compute intersection-over-union between corresponding boxes in boxlists.\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding N boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N] representing pairwise iou scores.\n \"\"\"\n with tf.name_scope(scope, 'MatchedIOU'):\n intersections = matched_intersection(boxlist1, boxlist2)\n areas1 = area(boxlist1)\n areas2 = area(boxlist2)\n unions = areas1 + areas2 - intersections\n return tf.where(\n tf.equal(intersections, 0.0),\n tf.zeros_like(intersections), tf.truediv(intersections, unions))\n\n\ndef ioa(boxlist1, boxlist2, scope=None):\n \"\"\"Computes pairwise intersection-over-area between box collections.\n\n intersection-over-area (IOA) between two boxes box1 and box2 is defined as\n their intersection area over box2's area. Note that ioa is not symmetric,\n that is, ioa(box1, box2) != ioa(box2, box1).\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N, M] representing pairwise ioa scores.\n \"\"\"\n with tf.name_scope(scope, 'IOA'):\n intersections = intersection(boxlist1, boxlist2)\n areas = tf.expand_dims(area(boxlist2), 0)\n return tf.truediv(intersections, areas)\n\n\ndef prune_non_overlapping_boxes(\n boxlist1, boxlist2, min_overlap=0.0, scope=None):\n \"\"\"Prunes the boxes in boxlist1 that overlap less than thresh with boxlist2.\n\n For each box in boxlist1, we want its IOA to be more than minoverlap with\n at least one of the boxes in boxlist2. If it does not, we remove it.\n\n Args:\n boxlist1: BoxList holding N boxes.\n boxlist2: BoxList holding M boxes.\n min_overlap: Minimum required overlap between boxes, to count them as\n overlapping.\n scope: name scope.\n\n Returns:\n new_boxlist1: A pruned boxlist with size [N', 4].\n keep_inds: A tensor with shape [N'] indexing kept bounding boxes in the\n first input BoxList `boxlist1`.\n \"\"\"\n with tf.name_scope(scope, 'PruneNonOverlappingBoxes'):\n ioa_ = ioa(boxlist2, boxlist1) # [M, N] tensor\n ioa_ = tf.reduce_max(ioa_, reduction_indices=[0]) # [N] tensor\n keep_bool = tf.greater_equal(ioa_, tf.constant(min_overlap))\n keep_inds = tf.squeeze(tf.where(keep_bool), axis=[1])\n new_boxlist1 = gather(boxlist1, keep_inds)\n return new_boxlist1, keep_inds\n\n\ndef prune_small_boxes(boxlist, min_side, scope=None):\n \"\"\"Prunes small boxes in the boxlist which have a side smaller than min_side.\n\n Args:\n boxlist: BoxList holding N boxes.\n min_side: Minimum width AND height of box to survive pruning.\n scope: name scope.\n\n Returns:\n A pruned boxlist.\n \"\"\"\n with tf.name_scope(scope, 'PruneSmallBoxes'):\n height, width = height_width(boxlist)\n is_valid = tf.logical_and(tf.greater_equal(width, min_side),\n tf.greater_equal(height, min_side))\n return gather(boxlist, tf.reshape(tf.where(is_valid), [-1]))\n\n\ndef change_coordinate_frame(boxlist, window, scope=None):\n \"\"\"Change coordinate frame of the boxlist to be relative to window's frame.\n\n Given a window of the form [ymin, xmin, ymax, xmax],\n changes bounding box coordinates from boxlist to be relative to this window\n (e.g., the min corner maps to (0,0) and the max corner maps to (1,1)).\n\n An example use case is data augmentation: where we are given groundtruth\n boxes (boxlist) and would like to randomly crop the image to some\n window (window). In this case we need to change the coordinate frame of\n each groundtruth box to be relative to this new window.\n\n Args:\n boxlist: A BoxList object holding N boxes.\n window: A rank 1 tensor [4].\n scope: name scope.\n\n Returns:\n Returns a BoxList object with N boxes.\n \"\"\"\n with tf.name_scope(scope, 'ChangeCoordinateFrame'):\n win_height = window[2] - window[0]\n win_width = window[3] - window[1]\n boxlist_new = scale(box_list.BoxList(\n boxlist.get() - [window[0], window[1], window[0], window[1]]),\n 1.0 / win_height, 1.0 / win_width)\n boxlist_new = _copy_extra_fields(boxlist_new, boxlist)\n return boxlist_new\n\n\ndef sq_dist(boxlist1, boxlist2, scope=None):\n \"\"\"Computes the pairwise squared distances between box corners.\n\n This op treats each box as if it were a point in a 4d Euclidean space and\n computes pairwise squared distances.\n\n Mathematically, we are given two matrices of box coordinates X and Y,\n where X(i,:) is the i'th row of X, containing the 4 numbers defining the\n corners of the i'th box in boxlist1. Similarly Y(j,:) corresponds to\n boxlist2. We compute\n Z(i,j) = ||X(i,:) - Y(j,:)||^2\n = ||X(i,:)||^2 + ||Y(j,:)||^2 - 2 X(i,:)' * Y(j,:),\n\n Args:\n boxlist1: BoxList holding N boxes\n boxlist2: BoxList holding M boxes\n scope: name scope.\n\n Returns:\n a tensor with shape [N, M] representing pairwise distances\n \"\"\"\n with tf.name_scope(scope, 'SqDist'):\n sqnorm1 = tf.reduce_sum(tf.square(boxlist1.get()), 1, keep_dims=True)\n sqnorm2 = tf.reduce_sum(tf.square(boxlist2.get()), 1, keep_dims=True)\n innerprod = tf.matmul(boxlist1.get(), boxlist2.get(),\n transpose_a=False, transpose_b=True)\n return sqnorm1 + tf.transpose(sqnorm2) - 2.0 * innerprod\n\n\ndef boolean_mask(boxlist, indicator, fields=None, scope=None,\n use_static_shapes=False, indicator_sum=None):\n \"\"\"Select boxes from BoxList according to indicator and return new BoxList.\n\n `boolean_mask` returns the subset of boxes that are marked as \"True\" by the\n indicator tensor. By default, `boolean_mask` returns boxes corresponding to\n the input index list, as well as all additional fields stored in the boxlist\n (indexing into the first dimension). However one can optionally only draw\n from a subset of fields.\n\n Args:\n boxlist: BoxList holding N boxes\n indicator: a rank-1 boolean tensor\n fields: (optional) list of fields to also gather from. If None (default),\n all fields are gathered from. Pass an empty fields list to only gather\n the box coordinates.\n scope: name scope.\n use_static_shapes: Whether to use an implementation with static shape\n gurantees.\n indicator_sum: An integer containing the sum of `indicator` vector. Only\n required if `use_static_shape` is True.\n\n Returns:\n subboxlist: a BoxList corresponding to the subset of the input BoxList\n specified by indicator\n Raises:\n ValueError: if `indicator` is not a rank-1 boolean tensor.\n \"\"\"\n with tf.name_scope(scope, 'BooleanMask'):\n if indicator.shape.ndims != 1:\n raise ValueError('indicator should have rank 1')\n if indicator.dtype != tf.bool:\n raise ValueError('indicator should be a boolean tensor')\n if use_static_shapes:\n if not (indicator_sum and isinstance(indicator_sum, int)):\n raise ValueError('`indicator_sum` must be a of type int')\n selected_positions = tf.cast(indicator, dtype=tf.float32)\n indexed_positions = tf.cast(\n tf.multiply(\n tf.cumsum(selected_positions), selected_positions),\n dtype=tf.int32)\n one_hot_selector = tf.one_hot(\n indexed_positions - 1, indicator_sum, dtype=tf.float32)\n sampled_indices = tf.cast(\n tf.tensordot(\n tf.cast(tf.range(tf.shape(indicator)[0]), dtype=tf.float32),\n one_hot_selector,\n axes=[0, 0]),\n dtype=tf.int32)\n return gather(boxlist, sampled_indices, use_static_shapes=True)\n else:\n subboxlist = box_list.BoxList(tf.boolean_mask(boxlist.get(), indicator))\n if fields is None:\n fields = boxlist.get_extra_fields()\n for field in fields:\n if not boxlist.has_field(field):\n raise ValueError('boxlist must contain all specified fields')\n subfieldlist = tf.boolean_mask(boxlist.get_field(field), indicator)\n subboxlist.add_field(field, subfieldlist)\n return subboxlist\n\n\ndef gather(boxlist, indices, fields=None, scope=None, use_static_shapes=False):\n \"\"\"Gather boxes from BoxList according to indices and return new BoxList.\n\n By default, `gather` returns boxes corresponding to the input index list, as\n well as all additional fields stored in the boxlist (indexing into the\n first dimension). However one can optionally only gather from a\n subset of fields.\n\n Args:\n boxlist: BoxList holding N boxes\n indices: a rank-1 tensor of type int32 / int64\n fields: (optional) list of fields to also gather from. If None (default),\n all fields are gathered from. Pass an empty fields list to only gather\n the box coordinates.\n scope: name scope.\n use_static_shapes: Whether to use an implementation with static shape\n gurantees.\n\n Returns:\n subboxlist: a BoxList corresponding to the subset of the input BoxList\n specified by indices\n Raises:\n ValueError: if specified field is not contained in boxlist or if the\n indices are not of type int32\n \"\"\"\n with tf.name_scope(scope, 'Gather'):\n if len(indices.shape.as_list()) != 1:\n raise ValueError('indices should have rank 1')\n if indices.dtype != tf.int32 and indices.dtype != tf.int64:\n raise ValueError('indices should be an int32 / int64 tensor')\n gather_op = tf.gather\n if use_static_shapes:\n gather_op = ops.matmul_gather_on_zeroth_axis\n subboxlist = box_list.BoxList(gather_op(boxlist.get(), indices))\n if fields is None:\n fields = boxlist.get_extra_fields()\n fields += ['boxes']\n for field in fields:\n if not boxlist.has_field(field):\n raise ValueError('boxlist must contain all specified fields')\n subfieldlist = gather_op(boxlist.get_field(field), indices)\n subboxlist.add_field(field, subfieldlist)\n return subboxlist\n\n\ndef concatenate(boxlists, fields=None, scope=None):\n \"\"\"Concatenate list of BoxLists.\n\n This op concatenates a list of input BoxLists into a larger BoxList. It also\n handles concatenation of BoxList fields as long as the field tensor shapes\n are equal except for the first dimension.\n\n Args:\n boxlists: list of BoxList objects\n fields: optional list of fields to also concatenate. By default, all\n fields from the first BoxList in the list are included in the\n concatenation.\n scope: name scope.\n\n Returns:\n a BoxList with number of boxes equal to\n sum([boxlist.num_boxes() for boxlist in BoxList])\n Raises:\n ValueError: if boxlists is invalid (i.e., is not a list, is empty, or\n contains non BoxList objects), or if requested fields are not contained in\n all boxlists\n \"\"\"\n with tf.name_scope(scope, 'Concatenate'):\n if not isinstance(boxlists, list):\n raise ValueError('boxlists should be a list')\n if not boxlists:\n raise ValueError('boxlists should have nonzero length')\n for boxlist in boxlists:\n if not isinstance(boxlist, box_list.BoxList):\n raise ValueError('all elements of boxlists should be BoxList objects')\n concatenated = box_list.BoxList(\n tf.concat([boxlist.get() for boxlist in boxlists], 0))\n if fields is None:\n fields = boxlists[0].get_extra_fields()\n for field in fields:\n first_field_shape = boxlists[0].get_field(field).get_shape().as_list()\n first_field_shape[0] = -1\n if None in first_field_shape:\n raise ValueError('field %s must have fully defined shape except for the'\n ' 0th dimension.' % field)\n for boxlist in boxlists:\n if not boxlist.has_field(field):\n raise ValueError('boxlist must contain all requested fields')\n field_shape = boxlist.get_field(field).get_shape().as_list()\n field_shape[0] = -1\n if field_shape != first_field_shape:\n raise ValueError('field %s must have same shape for all boxlists '\n 'except for the 0th dimension.' % field)\n concatenated_field = tf.concat(\n [boxlist.get_field(field) for boxlist in boxlists], 0)\n concatenated.add_field(field, concatenated_field)\n return concatenated\n\n\ndef sort_by_field(boxlist, field, order=SortOrder.descend, scope=None):\n \"\"\"Sort boxes and associated fields according to a scalar field.\n\n A common use case is reordering the boxes according to descending scores.\n\n Args:\n boxlist: BoxList holding N boxes.\n field: A BoxList field for sorting and reordering the BoxList.\n order: (Optional) descend or ascend. Default is descend.\n scope: name scope.\n\n Returns:\n sorted_boxlist: A sorted BoxList with the field in the specified order.\n\n Raises:\n ValueError: if specified field does not exist\n ValueError: if the order is not either descend or ascend\n \"\"\"\n with tf.name_scope(scope, 'SortByField'):\n if order != SortOrder.descend and order != SortOrder.ascend:\n raise ValueError('Invalid sort order')\n\n field_to_sort = boxlist.get_field(field)\n if len(field_to_sort.shape.as_list()) != 1:\n raise ValueError('Field should have rank 1')\n\n num_boxes = boxlist.num_boxes()\n num_entries = tf.size(field_to_sort)\n length_assert = tf.Assert(\n tf.equal(num_boxes, num_entries),\n ['Incorrect field size: actual vs expected.', num_entries, num_boxes])\n\n with tf.control_dependencies([length_assert]):\n _, sorted_indices = tf.nn.top_k(field_to_sort, num_boxes, sorted=True)\n\n if order == SortOrder.ascend:\n sorted_indices = tf.reverse_v2(sorted_indices, [0])\n\n return gather(boxlist, sorted_indices)\n\n\ndef visualize_boxes_in_image(image, boxlist, normalized=False, scope=None):\n \"\"\"Overlay bounding box list on image.\n\n Currently this visualization plots a 1 pixel thick red bounding box on top\n of the image. Note that tf.image.draw_bounding_boxes essentially is\n 1 indexed.\n\n Args:\n image: an image tensor with shape [height, width, 3]\n boxlist: a BoxList\n normalized: (boolean) specify whether corners are to be interpreted\n as absolute coordinates in image space or normalized with respect to the\n image size.\n scope: name scope.\n\n Returns:\n image_and_boxes: an image tensor with shape [height, width, 3]\n \"\"\"\n with tf.name_scope(scope, 'VisualizeBoxesInImage'):\n if not normalized:\n height, width, _ = tf.unstack(tf.shape(image))\n boxlist = scale(boxlist,\n 1.0 / tf.cast(height, tf.float32),\n 1.0 / tf.cast(width, tf.float32))\n corners = tf.expand_dims(boxlist.get(), 0)\n image = tf.expand_dims(image, 0)\n return tf.squeeze(tf.image.draw_bounding_boxes(image, corners), [0])\n\n\ndef filter_field_value_equals(boxlist, field, value, scope=None):\n \"\"\"Filter to keep only boxes with field entries equal to the given value.\n\n Args:\n boxlist: BoxList holding N boxes.\n field: field name for filtering.\n value: scalar value.\n scope: name scope.\n\n Returns:\n a BoxList holding M boxes where M <= N\n\n Raises:\n ValueError: if boxlist not a BoxList object or if it does not have\n the specified field.\n \"\"\"\n with tf.name_scope(scope, 'FilterFieldValueEquals'):\n if not isinstance(boxlist, box_list.BoxList):\n raise ValueError('boxlist must be a BoxList')\n if not boxlist.has_field(field):\n raise ValueError('boxlist must contain the specified field')\n filter_field = boxlist.get_field(field)\n gather_index = tf.reshape(tf.where(tf.equal(filter_field, value)), [-1])\n return gather(boxlist, gather_index)\n\n\ndef filter_greater_than(boxlist, thresh, scope=None):\n \"\"\"Filter to keep only boxes with score exceeding a given threshold.\n\n This op keeps the collection of boxes whose corresponding scores are\n greater than the input threshold.\n\n TODO(jonathanhuang): Change function name to filter_scores_greater_than\n\n Args:\n boxlist: BoxList holding N boxes. Must contain a 'scores' field\n representing detection scores.\n thresh: scalar threshold\n scope: name scope.\n\n Returns:\n a BoxList holding M boxes where M <= N\n\n Raises:\n ValueError: if boxlist not a BoxList object or if it does not\n have a scores field\n \"\"\"\n with tf.name_scope(scope, 'FilterGreaterThan'):\n if not isinstance(boxlist, box_list.BoxList):\n raise ValueError('boxlist must be a BoxList')\n if not boxlist.has_field('scores'):\n raise ValueError('input boxlist must have \\'scores\\' field')\n scores = boxlist.get_field('scores')\n if len(scores.shape.as_list()) > 2:\n raise ValueError('Scores should have rank 1 or 2')\n if len(scores.shape.as_list()) == 2 and scores.shape.as_list()[1] != 1:\n raise ValueError('Scores should have rank 1 or have shape '\n 'consistent with [None, 1]')\n high_score_indices = tf.cast(tf.reshape(\n tf.where(tf.greater(scores, thresh)),\n [-1]), tf.int32)\n return gather(boxlist, high_score_indices)\n\n\ndef non_max_suppression(boxlist, thresh, max_output_size, scope=None):\n \"\"\"Non maximum suppression.\n\n This op greedily selects a subset of detection bounding boxes, pruning\n away boxes that have high IOU (intersection over union) overlap (> thresh)\n with already selected boxes. Note that this only works for a single class ---\n to apply NMS to multi-class predictions, use MultiClassNonMaxSuppression.\n\n Args:\n boxlist: BoxList holding N boxes. Must contain a 'scores' field\n representing detection scores.\n thresh: scalar threshold\n max_output_size: maximum number of retained boxes\n scope: name scope.\n\n Returns:\n a BoxList holding M boxes where M <= max_output_size\n Raises:\n ValueError: if thresh is not in [0, 1]\n \"\"\"\n with tf.name_scope(scope, 'NonMaxSuppression'):\n if not 0 <= thresh <= 1.0:\n raise ValueError('thresh must be between 0 and 1')\n if not isinstance(boxlist, box_list.BoxList):\n raise ValueError('boxlist must be a BoxList')\n if not boxlist.has_field('scores'):\n raise ValueError('input boxlist must have \\'scores\\' field')\n selected_indices = tf.image.non_max_suppression(\n boxlist.get(), boxlist.get_field('scores'),\n max_output_size, iou_threshold=thresh)\n return gather(boxlist, selected_indices)\n\n\ndef _copy_extra_fields(boxlist_to_copy_to, boxlist_to_copy_from):\n \"\"\"Copies the extra fields of boxlist_to_copy_from to boxlist_to_copy_to.\n\n Args:\n boxlist_to_copy_to: BoxList to which extra fields are copied.\n boxlist_to_copy_from: BoxList from which fields are copied.\n\n Returns:\n boxlist_to_copy_to with extra fields.\n \"\"\"\n for field in boxlist_to_copy_from.get_extra_fields():\n boxlist_to_copy_to.add_field(field, boxlist_to_copy_from.get_field(field))\n return boxlist_to_copy_to\n\n\ndef to_normalized_coordinates(boxlist, height, width,\n check_range=True, scope=None):\n \"\"\"Converts absolute box coordinates to normalized coordinates in [0, 1].\n\n Usually one uses the dynamic shape of the image or conv-layer tensor:\n boxlist = box_list_ops.to_normalized_coordinates(boxlist,\n tf.shape(images)[1],\n tf.shape(images)[2]),\n\n This function raises an assertion failed error at graph execution time when\n the maximum coordinate is smaller than 1.01 (which means that coordinates are\n already normalized). The value 1.01 is to deal with small rounding errors.\n\n Args:\n boxlist: BoxList with coordinates in terms of pixel-locations.\n height: Maximum value for height of absolute box coordinates.\n width: Maximum value for width of absolute box coordinates.\n check_range: If True, checks if the coordinates are normalized or not.\n scope: name scope.\n\n Returns:\n boxlist with normalized coordinates in [0, 1].\n \"\"\"\n with tf.name_scope(scope, 'ToNormalizedCoordinates'):\n height = tf.cast(height, tf.float32)\n width = tf.cast(width, tf.float32)\n\n if check_range:\n max_val = tf.reduce_max(boxlist.get())\n max_assert = tf.Assert(tf.greater(max_val, 1.01),\n ['max value is lower than 1.01: ', max_val])\n with tf.control_dependencies([max_assert]):\n width = tf.identity(width)\n\n return scale(boxlist, 1 / height, 1 / width)\n\n\ndef to_absolute_coordinates(boxlist,\n height,\n width,\n check_range=True,\n maximum_normalized_coordinate=1.1,\n scope=None):\n \"\"\"Converts normalized box coordinates to absolute pixel coordinates.\n\n This function raises an assertion failed error when the maximum box coordinate\n value is larger than maximum_normalized_coordinate (in which case coordinates\n are already absolute).\n\n Args:\n boxlist: BoxList with coordinates in range [0, 1].\n height: Maximum value for height of absolute box coordinates.\n width: Maximum value for width of absolute box coordinates.\n check_range: If True, checks if the coordinates are normalized or not.\n maximum_normalized_coordinate: Maximum coordinate value to be considered\n as normalized, default to 1.1.\n scope: name scope.\n\n Returns:\n boxlist with absolute coordinates in terms of the image size.\n\n \"\"\"\n with tf.name_scope(scope, 'ToAbsoluteCoordinates'):\n height = tf.cast(height, tf.float32)\n width = tf.cast(width, tf.float32)\n\n # Ensure range of input boxes is correct.\n if check_range:\n box_maximum = tf.reduce_max(boxlist.get())\n max_assert = tf.Assert(\n tf.greater_equal(maximum_normalized_coordinate, box_maximum),\n ['maximum box coordinate value is larger '\n 'than %f: ' % maximum_normalized_coordinate, box_maximum])\n with tf.control_dependencies([max_assert]):\n width = tf.identity(width)\n\n return scale(boxlist, height, width)\n\n\ndef refine_boxes_multi_class(pool_boxes,\n num_classes,\n nms_iou_thresh,\n nms_max_detections,\n voting_iou_thresh=0.5):\n \"\"\"Refines a pool of boxes using non max suppression and box voting.\n\n Box refinement is done independently for each class.\n\n Args:\n pool_boxes: (BoxList) A collection of boxes to be refined. pool_boxes must\n have a rank 1 'scores' field and a rank 1 'classes' field.\n num_classes: (int scalar) Number of classes.\n nms_iou_thresh: (float scalar) iou threshold for non max suppression (NMS).\n nms_max_detections: (int scalar) maximum output size for NMS.\n voting_iou_thresh: (float scalar) iou threshold for box voting.\n\n Returns:\n BoxList of refined boxes.\n\n Raises:\n ValueError: if\n a) nms_iou_thresh or voting_iou_thresh is not in [0, 1].\n b) pool_boxes is not a BoxList.\n c) pool_boxes does not have a scores and classes field.\n \"\"\"\n if not 0.0 <= nms_iou_thresh <= 1.0:\n raise ValueError('nms_iou_thresh must be between 0 and 1')\n if not 0.0 <= voting_iou_thresh <= 1.0:\n raise ValueError('voting_iou_thresh must be between 0 and 1')\n if not isinstance(pool_boxes, box_list.BoxList):\n raise ValueError('pool_boxes must be a BoxList')\n if not pool_boxes.has_field('scores'):\n raise ValueError('pool_boxes must have a \\'scores\\' field')\n if not pool_boxes.has_field('classes'):\n raise ValueError('pool_boxes must have a \\'classes\\' field')\n\n refined_boxes = []\n for i in range(num_classes):\n boxes_class = filter_field_value_equals(pool_boxes, 'classes', i)\n refined_boxes_class = refine_boxes(boxes_class, nms_iou_thresh,\n nms_max_detections, voting_iou_thresh)\n refined_boxes.append(refined_boxes_class)\n return sort_by_field(concatenate(refined_boxes), 'scores')\n\n\ndef refine_boxes(pool_boxes,\n nms_iou_thresh,\n nms_max_detections,\n voting_iou_thresh=0.5):\n \"\"\"Refines a pool of boxes using non max suppression and box voting.\n\n Args:\n pool_boxes: (BoxList) A collection of boxes to be refined. pool_boxes must\n have a rank 1 'scores' field.\n nms_iou_thresh: (float scalar) iou threshold for non max suppression (NMS).\n nms_max_detections: (int scalar) maximum output size for NMS.\n voting_iou_thresh: (float scalar) iou threshold for box voting.\n\n Returns:\n BoxList of refined boxes.\n\n Raises:\n ValueError: if\n a) nms_iou_thresh or voting_iou_thresh is not in [0, 1].\n b) pool_boxes is not a BoxList.\n c) pool_boxes does not have a scores field.\n \"\"\"\n if not 0.0 <= nms_iou_thresh <= 1.0:\n raise ValueError('nms_iou_thresh must be between 0 and 1')\n if not 0.0 <= voting_iou_thresh <= 1.0:\n raise ValueError('voting_iou_thresh must be between 0 and 1')\n if not isinstance(pool_boxes, box_list.BoxList):\n raise ValueError('pool_boxes must be a BoxList')\n if not pool_boxes.has_field('scores'):\n raise ValueError('pool_boxes must have a \\'scores\\' field')\n\n nms_boxes = non_max_suppression(\n pool_boxes, nms_iou_thresh, nms_max_detections)\n return box_voting(nms_boxes, pool_boxes, voting_iou_thresh)\n\n\ndef box_voting(selected_boxes, pool_boxes, iou_thresh=0.5):\n \"\"\"Performs box voting as described in S. Gidaris and N. Komodakis, ICCV 2015.\n\n Performs box voting as described in 'Object detection via a multi-region &\n semantic segmentation-aware CNN model', Gidaris and Komodakis, ICCV 2015. For\n each box 'B' in selected_boxes, we find the set 'S' of boxes in pool_boxes\n with iou overlap >= iou_thresh. The location of B is set to the weighted\n average location of boxes in S (scores are used for weighting). And the score\n of B is set to the average score of boxes in S.\n\n Args:\n selected_boxes: BoxList containing a subset of boxes in pool_boxes. These\n boxes are usually selected from pool_boxes using non max suppression.\n pool_boxes: BoxList containing a set of (possibly redundant) boxes.\n iou_thresh: (float scalar) iou threshold for matching boxes in\n selected_boxes and pool_boxes.\n\n Returns:\n BoxList containing averaged locations and scores for each box in\n selected_boxes.\n\n Raises:\n ValueError: if\n a) selected_boxes or pool_boxes is not a BoxList.\n b) if iou_thresh is not in [0, 1].\n c) pool_boxes does not have a scores field.\n \"\"\"\n if not 0.0 <= iou_thresh <= 1.0:\n raise ValueError('iou_thresh must be between 0 and 1')\n if not isinstance(selected_boxes, box_list.BoxList):\n raise ValueError('selected_boxes must be a BoxList')\n if not isinstance(pool_boxes, box_list.BoxList):\n raise ValueError('pool_boxes must be a BoxList')\n if not pool_boxes.has_field('scores'):\n raise ValueError('pool_boxes must have a \\'scores\\' field')\n\n iou_ = iou(selected_boxes, pool_boxes)\n match_indicator = tf.cast(tf.greater(iou_, iou_thresh), dtype=tf.float32)\n num_matches = tf.reduce_sum(match_indicator, 1)\n # TODO(kbanoop): Handle the case where some boxes in selected_boxes do not\n # match to any boxes in pool_boxes. For such boxes without any matches, we\n # should return the original boxes without voting.\n match_assert = tf.Assert(\n tf.reduce_all(tf.greater(num_matches, 0)),\n ['Each box in selected_boxes must match with at least one box '\n 'in pool_boxes.'])\n\n scores = tf.expand_dims(pool_boxes.get_field('scores'), 1)\n scores_assert = tf.Assert(\n tf.reduce_all(tf.greater_equal(scores, 0)),\n ['Scores must be non negative.'])\n\n with tf.control_dependencies([scores_assert, match_assert]):\n sum_scores = tf.matmul(match_indicator, scores)\n averaged_scores = tf.reshape(sum_scores, [-1]) / num_matches\n\n box_locations = tf.matmul(match_indicator,\n pool_boxes.get() * scores) / sum_scores\n averaged_boxes = box_list.BoxList(box_locations)\n _copy_extra_fields(averaged_boxes, selected_boxes)\n averaged_boxes.add_field('scores', averaged_scores)\n return averaged_boxes\n\n\ndef get_minimal_coverage_box(boxlist,\n default_box=None,\n scope=None):\n \"\"\"Creates a single bounding box which covers all boxes in the boxlist.\n\n Args:\n boxlist: A Boxlist.\n default_box: A [1, 4] float32 tensor. If no boxes are present in `boxlist`,\n this default box will be returned. If None, will use a default box of\n [[0., 0., 1., 1.]].\n scope: Name scope.\n\n Returns:\n A [1, 4] float32 tensor with a bounding box that tightly covers all the\n boxes in the box list. If the boxlist does not contain any boxes, the\n default box is returned.\n \"\"\"\n with tf.name_scope(scope, 'CreateCoverageBox'):\n num_boxes = boxlist.num_boxes()\n\n def coverage_box(bboxes):\n y_min, x_min, y_max, x_max = tf.split(\n value=bboxes, num_or_size_splits=4, axis=1)\n y_min_coverage = tf.reduce_min(y_min, axis=0)\n x_min_coverage = tf.reduce_min(x_min, axis=0)\n y_max_coverage = tf.reduce_max(y_max, axis=0)\n x_max_coverage = tf.reduce_max(x_max, axis=0)\n return tf.stack(\n [y_min_coverage, x_min_coverage, y_max_coverage, x_max_coverage],\n axis=1)\n\n default_box = default_box or tf.constant([[0., 0., 1., 1.]])\n return tf.cond(\n tf.greater_equal(num_boxes, 1),\n true_fn=lambda: coverage_box(boxlist.get()),\n false_fn=lambda: default_box)\n\n\ndef sample_boxes_by_jittering(boxlist,\n num_boxes_to_sample,\n stddev=0.1,\n scope=None):\n \"\"\"Samples num_boxes_to_sample boxes by jittering around boxlist boxes.\n\n It is possible that this function might generate boxes with size 0. The larger\n the stddev, this is more probable. For a small stddev of 0.1 this probability\n is very small.\n\n Args:\n boxlist: A boxlist containing N boxes in normalized coordinates.\n num_boxes_to_sample: A positive integer containing the number of boxes to\n sample.\n stddev: Standard deviation. This is used to draw random offsets for the\n box corners from a normal distribution. The offset is multiplied by the\n box size so will be larger in terms of pixels for larger boxes.\n scope: Name scope.\n\n Returns:\n sampled_boxlist: A boxlist containing num_boxes_to_sample boxes in\n normalized coordinates.\n \"\"\"\n with tf.name_scope(scope, 'SampleBoxesByJittering'):\n num_boxes = boxlist.num_boxes()\n box_indices = tf.random_uniform(\n [num_boxes_to_sample],\n minval=0,\n maxval=num_boxes,\n dtype=tf.int32)\n sampled_boxes = tf.gather(boxlist.get(), box_indices)\n sampled_boxes_height = sampled_boxes[:, 2] - sampled_boxes[:, 0]\n sampled_boxes_width = sampled_boxes[:, 3] - sampled_boxes[:, 1]\n rand_miny_gaussian = tf.random_normal([num_boxes_to_sample], stddev=stddev)\n rand_minx_gaussian = tf.random_normal([num_boxes_to_sample], stddev=stddev)\n rand_maxy_gaussian = tf.random_normal([num_boxes_to_sample], stddev=stddev)\n rand_maxx_gaussian = tf.random_normal([num_boxes_to_sample], stddev=stddev)\n miny = rand_miny_gaussian * sampled_boxes_height + sampled_boxes[:, 0]\n minx = rand_minx_gaussian * sampled_boxes_width + sampled_boxes[:, 1]\n maxy = rand_maxy_gaussian * sampled_boxes_height + sampled_boxes[:, 2]\n maxx = rand_maxx_gaussian * sampled_boxes_width + sampled_boxes[:, 3]\n maxy = tf.maximum(miny, maxy)\n maxx = tf.maximum(minx, maxx)\n sampled_boxes = tf.stack([miny, minx, maxy, maxx], axis=1)\n sampled_boxes = tf.maximum(tf.minimum(sampled_boxes, 1.0), 0.0)\n return box_list.BoxList(sampled_boxes)\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Efficient ImageNet input pipeline using tf.data.Dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport collections\nimport functools\nimport os\nfrom absl import logging\nimport tensorflow.compat.v1 as tf\nfrom tensorflow.compat.v1 import estimator as tf_estimator\n\nimport preprocessing\n\n\n# The input tensor is in the range of [0, 255], we need to scale them.\nMEAN_RGB = [0.485 * 255, 0.456 * 255, 0.406 * 255]\nSTDDEV_RGB = [0.229 * 255, 0.224 * 255, 0.225 * 255]\n\n\ndef build_image_serving_input_fn(image_size):\n \"\"\"Builds a serving input fn for raw images.\"\"\"\n def _image_serving_input_fn():\n \"\"\"Serving input fn for raw images.\"\"\"\n def _preprocess_image(image_bytes):\n \"\"\"Preprocess a single raw image.\"\"\"\n image = preprocessing.preprocess_image(\n image_bytes=image_bytes, is_training=False, image_size=image_size)\n return image\n\n image_bytes_list = tf.placeholder(\n shape=[None],\n dtype=tf.string,\n )\n images = tf.map_fn(\n _preprocess_image, image_bytes_list, back_prop=False, dtype=tf.float32)\n return tf_estimator.export.ServingInputReceiver(\n images, {'image_bytes': image_bytes_list})\n return _image_serving_input_fn\n\n\nclass ImageNetTFExampleInput(object):\n \"\"\"Base class for ImageNet input_fn generator.\n\n Attributes:\n image_preprocessing_fn: function to preprocess images\n is_training: `bool` for whether the input is for training\n use_bfloat16: If True, use bfloat16 precision; else use float32.\n num_cores: `int` for the number of TPU cores\n image_size: `int` for image size (both width and height).\n transpose_input: 'bool' for whether to use the double transpose trick\n \"\"\"\n __metaclass__ = abc.ABCMeta\n\n def __init__(self,\n is_training,\n use_bfloat16,\n num_cores=8,\n image_size=224,\n transpose_input=False):\n self.image_preprocessing_fn = preprocessing.preprocess_image\n self.is_training = is_training\n self.use_bfloat16 = use_bfloat16\n self.num_cores = num_cores\n self.transpose_input = transpose_input\n self.image_size = image_size\n\n def set_shapes(self, batch_size, images, labels):\n \"\"\"Statically set the batch_size dimension.\"\"\"\n if self.transpose_input:\n images.set_shape(images.get_shape().merge_with(\n tf.TensorShape([None, None, None, batch_size])))\n labels.set_shape(labels.get_shape().merge_with(\n tf.TensorShape([batch_size])))\n else:\n images.set_shape(images.get_shape().merge_with(\n tf.TensorShape([batch_size, None, None, None])))\n labels.set_shape(labels.get_shape().merge_with(\n tf.TensorShape([batch_size])))\n\n return images, labels\n\n def dataset_parser(self, value):\n \"\"\"Parses an image and its label from a serialized ResNet-50 TFExample.\n\n Args:\n value: serialized string containing an ImageNet TFExample.\n\n Returns:\n Returns a tuple of (image, label) from the TFExample.\n \"\"\"\n keys_to_features = {\n 'image/encoded': tf.FixedLenFeature((), tf.string, ''),\n 'image/class/label': tf.FixedLenFeature([], tf.int64, -1),\n }\n\n parsed = tf.parse_single_example(value, keys_to_features)\n image_bytes = tf.reshape(parsed['image/encoded'], shape=[])\n\n image = self.image_preprocessing_fn(\n image_bytes=image_bytes,\n is_training=self.is_training,\n image_size=self.image_size,\n use_bfloat16=self.use_bfloat16)\n\n # Subtract one so that labels are in [0, 1000).\n label = tf.cast(\n tf.reshape(parsed['image/class/label'], shape=[]), dtype=tf.int32) - 1\n\n return image, label\n\n @abc.abstractmethod\n def make_source_dataset(self, index, num_hosts):\n \"\"\"Makes dataset of serialized TFExamples.\n\n The returned dataset will contain `tf.string` tensors, but these strings are\n serialized `TFExample` records that will be parsed by `dataset_parser`.\n\n If self.is_training, the dataset should be infinite.\n\n Args:\n index: current host index.\n num_hosts: total number of hosts.\n\n Returns:\n A `tf.data.Dataset` object.\n \"\"\"\n return\n\n def input_fn(self, params):\n \"\"\"Input function which provides a single batch for train or eval.\n\n Args:\n params: `dict` of parameters passed from the `TPUEstimator`.\n `params['batch_size']` is always provided and should be used as the\n effective batch size.\n\n Returns:\n A `tf.data.Dataset` object.\n \"\"\"\n # Retrieves the batch size for the current shard. The # of shards is\n # computed according to the input pipeline deployment. See\n # tf.estimator.tpu.RunConfig for details.\n batch_size = params['batch_size']\n\n if 'context' in params:\n current_host = params['context'].current_input_fn_deployment()[1]\n num_hosts = params['context'].num_hosts\n else:\n current_host = 0\n num_hosts = 1\n\n dataset = self.make_source_dataset(current_host, num_hosts)\n\n # Use the fused map-and-batch operation.\n #\n # For XLA, we must used fixed shapes. Because we repeat the source training\n # dataset indefinitely, we can use `drop_remainder=True` to get fixed-size\n # batches without dropping any training examples.\n #\n # When evaluating, `drop_remainder=True` prevents accidentally evaluating\n # the same image twice by dropping the final batch if it is less than a full\n # batch size. As long as this validation is done with consistent batch size,\n # exactly the same images will be used.\n dataset = dataset.apply(\n tf.data.experimental.map_and_batch(\n self.dataset_parser,\n batch_size=batch_size,\n num_parallel_batches=self.num_cores,\n drop_remainder=True))\n\n # Transpose for performance on TPU\n if self.transpose_input:\n dataset = dataset.map(\n lambda images, labels: (tf.transpose(images, [1, 2, 3, 0]), labels),\n num_parallel_calls=self.num_cores)\n\n # Assign static batch size dimension\n dataset = dataset.map(functools.partial(self.set_shapes, batch_size))\n\n # Prefetch overlaps in-feed with training\n dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)\n return dataset\n\n\nclass ImageNetInput(ImageNetTFExampleInput):\n \"\"\"Generates ImageNet input_fn from a series of TFRecord files.\n\n The training data is assumed to be in TFRecord format with keys as specified\n in the dataset_parser below, sharded across 1024 files, named sequentially:\n\n train-00000-of-01024\n train-00001-of-01024\n ...\n train-01023-of-01024\n\n The validation data is in the same format but sharded in 128 files.\n\n The format of the data required is created by the script at:\n https://github.com/tensorflow/tpu/blob/master/tools/datasets/imagenet_to_gcs.py\n \"\"\"\n\n def __init__(self,\n is_training,\n use_bfloat16,\n transpose_input,\n data_dir,\n image_size=224,\n num_parallel_calls=64,\n cache=False):\n \"\"\"Create an input from TFRecord files.\n\n Args:\n is_training: `bool` for whether the input is for training\n use_bfloat16: If True, use bfloat16 precision; else use float32.\n transpose_input: 'bool' for whether to use the double transpose trick\n data_dir: `str` for the directory of the training and validation data;\n if 'null' (the literal string 'null') or implicitly False\n then construct a null pipeline, consisting of empty images\n and blank labels.\n image_size: `int` for image size (both width and height).\n num_parallel_calls: concurrency level to use when reading data from disk.\n cache: if true, fill the dataset by repeating from its cache\n \"\"\"\n super(ImageNetInput, self).__init__(\n is_training=is_training,\n image_size=image_size,\n use_bfloat16=use_bfloat16,\n transpose_input=transpose_input)\n self.data_dir = data_dir\n if self.data_dir == 'null' or not self.data_dir:\n self.data_dir = None\n self.num_parallel_calls = num_parallel_calls\n self.cache = cache\n\n def _get_null_input(self, data):\n \"\"\"Returns a null image (all black pixels).\n\n Args:\n data: element of a dataset, ignored in this method, since it produces\n the same null image regardless of the element.\n\n Returns:\n a tensor representing a null image.\n \"\"\"\n del data # Unused since output is constant regardless of input\n return tf.zeros([self.image_size, self.image_size, 3], tf.bfloat16\n if self.use_bfloat16 else tf.float32)\n\n def dataset_parser(self, value):\n \"\"\"See base class.\"\"\"\n if not self.data_dir:\n return value, tf.constant(0, tf.int32)\n return super(ImageNetInput, self).dataset_parser(value)\n\n def make_source_dataset(self, index, num_hosts):\n \"\"\"See base class.\"\"\"\n if not self.data_dir:\n tf.logging.info('Undefined data_dir implies null input')\n return tf.data.Dataset.range(1).repeat().map(self._get_null_input)\n\n # Shuffle the filenames to ensure better randomization.\n file_pattern = os.path.join(\n self.data_dir, 'train-*' if self.is_training else 'validation-*')\n\n # For multi-host training, we want each hosts to always process the same\n # subset of files. Each host only sees a subset of the entire dataset,\n # allowing us to cache larger datasets in memory.\n dataset = tf.data.Dataset.list_files(file_pattern, shuffle=False)\n dataset = dataset.shard(num_hosts, index)\n\n if self.is_training and not self.cache:\n dataset = dataset.repeat()\n\n def fetch_dataset(filename):\n buffer_size = 8 * 1024 * 1024 # 8 MiB per file\n dataset = tf.data.TFRecordDataset(filename, buffer_size=buffer_size)\n return dataset\n\n # Read the data from disk in parallel\n dataset = dataset.apply(\n tf.data.experimental.parallel_interleave(\n fetch_dataset, cycle_length=self.num_parallel_calls, sloppy=True))\n\n if self.cache:\n dataset = dataset.cache().apply(\n tf.data.experimental.shuffle_and_repeat(1024 * 16))\n else:\n dataset = dataset.shuffle(1024)\n return dataset\n\n\n# Defines a selection of data from a Cloud Bigtable.\nBigtableSelection = collections.namedtuple('BigtableSelection', [\n 'project', 'instance', 'table', 'prefix', 'column_family',\n 'column_qualifier'\n])\n\n\nclass ImageNetBigtableInput(ImageNetTFExampleInput):\n \"\"\"Generates ImageNet input_fn from a Bigtable for training or evaluation.\n \"\"\"\n\n def __init__(self, is_training, use_bfloat16, transpose_input, selection):\n \"\"\"Constructs an ImageNet input from a BigtableSelection.\n\n Args:\n is_training: `bool` for whether the input is for training\n use_bfloat16: If True, use bfloat16 precision; else use float32.\n transpose_input: 'bool' for whether to use the double transpose trick\n selection: a BigtableSelection specifying a part of a Bigtable.\n \"\"\"\n super(ImageNetBigtableInput, self).__init__(\n is_training=is_training,\n use_bfloat16=use_bfloat16,\n transpose_input=transpose_input)\n self.selection = selection\n\n def make_source_dataset(self, index, num_hosts):\n \"\"\"See base class.\"\"\"\n data = self.selection\n try:\n from tensorflow.contrib.cloud import BigtableClient # pylint: disable=g-import-not-at-top\n except ImportError as e:\n logging.exception('Bigtable is not supported in TensorFlow 2.x.')\n raise e\n\n client = BigtableClient(data.project, data.instance)\n table = client.table(data.table)\n ds = table.parallel_scan_prefix(data.prefix,\n columns=[(data.column_family,\n data.column_qualifier)])\n # The Bigtable datasets will have the shape (row_key, data)\n ds_data = ds.map(lambda index, data: data)\n\n if self.is_training:\n ds_data = ds_data.repeat()\n\n return ds_data\n" ]
[ [ "tensorflow.compat.v1.disable_v2_behavior" ], [ "tensorflow.compat.v1.metrics.mean", "tensorflow.compat.v1.subtract", "tensorflow.compat.v1.logging.warn", "tensorflow.compat.v1.estimator.RunConfig", "tensorflow.compat.v1.multiply", "tensorflow.compat.v1.one_hot", "tensorflow.compat.v1.transpose", "tensorflow.contrib.slim.assign_from_checkpoint_fn", "tensorflow.compat.v1.name_scope", "tensorflow.compat.v1.estimator.EstimatorSpec", "tensorflow.compat.v1.metrics.accuracy", "tensorflow.compat.v1.Graph", "tensorflow.compat.v1.losses.softmax_cross_entropy", "tensorflow.compat.v1.train.latest_checkpoint", "tensorflow.compat.v1.argmax", "tensorflow.compat.v1.logging.error", "tensorflow.compat.v1.logging.set_verbosity", "tensorflow.compat.v1.Session", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.compat.v1.placeholder", "tensorflow.compat.v1.logging.info", "tensorflow.compat.v1.nn.in_top_k" ], [ "tensorflow.compat.v1.concat", "tensorflow.compat.v1.equal", "tensorflow.compat.v1.random_normal", "tensorflow.compat.v1.shape", "tensorflow.compat.v1.greater_equal", "tensorflow.compat.v1.constant", "tensorflow.compat.v1.identity", "tensorflow.compat.v1.cumsum", "tensorflow.compat.v1.nn.top_k", "tensorflow.compat.v1.reduce_sum", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.one_hot", "tensorflow.compat.v1.maximum", "tensorflow.compat.v1.random_uniform", "tensorflow.compat.v1.zeros_like", "tensorflow.compat.v1.unstack", "tensorflow.compat.v1.transpose", "tensorflow.compat.v1.name_scope", "tensorflow.compat.v1.where", "tensorflow.compat.v1.reduce_any", "tensorflow.compat.v1.reverse_v2", "tensorflow.compat.v1.less", "tensorflow.compat.v1.split", "tensorflow.compat.v1.minimum", "tensorflow.compat.v1.reduce_max", "tensorflow.compat.v1.cast", "tensorflow.compat.v1.stack", "tensorflow.compat.v1.expand_dims", "tensorflow.compat.v1.image.draw_bounding_boxes", "tensorflow.compat.v1.less_equal", "tensorflow.compat.v1.control_dependencies", "tensorflow.compat.v1.truediv", "tensorflow.compat.v1.matmul", "tensorflow.compat.v1.reduce_min", "tensorflow.compat.v1.size", "tensorflow.compat.v1.squeeze", "tensorflow.compat.v1.greater" ], [ "tensorflow.compat.v1.data.TFRecordDataset", "tensorflow.compat.v1.estimator.export.ServingInputReceiver", "tensorflow.compat.v1.data.experimental.map_and_batch", "tensorflow.compat.v1.data.Dataset.list_files", "tensorflow.contrib.cloud.BigtableClient", "tensorflow.compat.v1.data.experimental.parallel_interleave", "tensorflow.compat.v1.reshape", "tensorflow.compat.v1.map_fn", "tensorflow.compat.v1.zeros", "tensorflow.compat.v1.data.Dataset.range", "tensorflow.compat.v1.FixedLenFeature", "tensorflow.compat.v1.placeholder", "tensorflow.compat.v1.logging.info", "tensorflow.compat.v1.data.experimental.shuffle_and_repeat", "tensorflow.compat.v1.parse_single_example", "tensorflow.compat.v1.TensorShape", "tensorflow.compat.v1.transpose", "tensorflow.compat.v1.constant" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
WuYichen-97/Learning-to-Purify-Noisy-Labels-via-Meta-Soft-Label-Corrector
[ "9fda4caf75a35de891a48aae44b6cb0cd36ea8cc" ]
[ "dataloader.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 27 17:38:25 2020\r\n\r\n@author: Wu Yichen\r\n\"\"\"\r\n\r\nfrom PIL import Image\r\nimport os\r\nimport os.path\r\nimport errno\r\nimport numpy as np\r\nimport sys\r\nimport pickle\r\n\r\n\r\nimport torch.utils.data as data\r\nfrom torchvision.datasets.utils import download_url, check_integrity\r\n\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom torch.autograd import Variable as V\r\nimport wideresnet as wrn\r\nimport torchvision.transforms as transforms\r\n\r\n\r\ndef uniform_mix_C(mixing_ratio, num_classes):\r\n '''\r\n returns a linear interpolation of a uniform matrix and an identity matrix\r\n '''\r\n return mixing_ratio * np.full((num_classes, num_classes), 1 / num_classes) + \\\r\n (1 - mixing_ratio) * np.eye(num_classes)\r\n\r\ndef flip_labels_C(corruption_prob, num_classes, seed=1):\r\n '''\r\n returns a matrix with (1 - corruption_prob) on the diagonals, and corruption_prob\r\n concentrated in only one other entry for each row\r\n '''\r\n np.random.seed(seed)\r\n C = np.eye(num_classes) * (1 - corruption_prob)\r\n row_indices = np.arange(num_classes)\r\n for i in range(num_classes):\r\n C[i][np.random.choice(row_indices[row_indices != i])] = corruption_prob\r\n return C\r\n\r\ndef flip_labels_C_two(corruption_prob, num_classes, seed=1):\r\n '''\r\n returns a matrix with (1 - corruption_prob) on the diagonals, and corruption_prob\r\n concentrated in only one other entry for each row\r\n '''\r\n np.random.seed(seed)\r\n C = np.eye(num_classes) * (1 - corruption_prob)\r\n row_indices = np.arange(num_classes)\r\n for i in range(num_classes):\r\n C[i][np.random.choice(row_indices[row_indices != i], 2, replace=False)] = corruption_prob / 2\r\n return C\r\n\r\n\r\nclass CIFAR10(data.Dataset):\r\n base_folder = 'cifar-10-batches-py'\r\n url = \"http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\"\r\n filename = \"cifar-10-python.tar.gz\"\r\n tgz_md5 = 'c58f30108f718f92721af3b95e74349a'\r\n train_list = [\r\n ['data_batch_1', 'c99cafc152244af753f735de768cd75f'],\r\n ['data_batch_2', 'd4bba439e000b95fd0a9bffe97cbabec'],\r\n ['data_batch_3', '54ebc095f3ab1f0389bbae665268c751'],\r\n ['data_batch_4', '634d18415352ddfa80567beed471001a'],\r\n ['data_batch_5', '482c414d41f54cd18b22e5b47cb7c3cb'],\r\n ]\r\n\r\n test_list = [\r\n ['test_batch', '40351d587109b95175f43aff81a1287e'],\r\n ]\r\n\r\n def __init__(self, root='', train=True, meta=True, num_meta=1000,\r\n corruption_prob=0, corruption_type='unif', transform=None, target_transform=None,\r\n download=False, seed=1):\r\n self.count = 0\r\n self.root = root\r\n self.transform = transform\r\n self.target_transform = target_transform\r\n self.train = train # training set or test set\r\n self.meta = meta\r\n self.corruption_prob = corruption_prob\r\n self.num_meta = num_meta\r\n \r\n\r\n if download:\r\n self.download()\r\n\r\n if not self._check_integrity():\r\n raise RuntimeError('Dataset not found or corrupted.' +\r\n ' You can use download=True to download it')\r\n\r\n # now load the picked numpy arrays\r\n if self.train:\r\n self.train_data = []\r\n self.train_labels = []\r\n self.train_coarse_labels = []\r\n self.train_labels_true = []\r\n self.soft_labels = []\r\n for fentry in self.train_list:\r\n f = fentry[0]\r\n file = os.path.join(root, self.base_folder, f)\r\n fo = open(file, 'rb')\r\n if sys.version_info[0] == 2:\r\n entry = pickle.load(fo)\r\n else:\r\n entry = pickle.load(fo, encoding='latin1')\r\n self.train_data.append(entry['data'])\r\n if 'labels' in entry:\r\n self.train_labels += entry['labels']\r\n self.train_labels_true += entry['labels']\r\n img_num_list = [int(self.num_meta/10)] * 10\r\n num_classes = 10\r\n else:\r\n self.train_labels += entry['fine_labels']\r\n self.train_labels_true += entry['fine_labels']\r\n self.train_coarse_labels += entry['coarse_labels']\r\n img_num_list = [int(self.num_meta/100)] * 100\r\n num_classes = 100\r\n fo.close()\r\n\r\n self.train_data = np.concatenate(self.train_data)\r\n self.train_data = self.train_data.reshape((50000, 3, 32, 32))\r\n self.train_data = self.train_data.transpose((0, 2, 3, 1)) # convert to HWC\r\n\r\n data_list_val = {}\r\n for j in range(num_classes):\r\n data_list_val[j] = [i for i, label in enumerate(self.train_labels) if label == j]\r\n\r\n\r\n idx_to_meta = []\r\n idx_to_train = []\r\n print(img_num_list)\r\n\r\n for cls_idx, img_id_list in data_list_val.items():\r\n np.random.shuffle(img_id_list)\r\n img_num = img_num_list[int(cls_idx)]\r\n idx_to_meta.extend(img_id_list[:img_num])\r\n idx_to_train.extend(img_id_list[img_num:])\r\n\r\n\r\n if meta is True:\r\n self.train_data = self.train_data[idx_to_meta]\r\n self.train_labels = list(np.array(self.train_labels)[idx_to_meta])\r\n else:\r\n self.train_data = self.train_data[idx_to_train]\r\n self.train_labels = list(np.array(self.train_labels)[idx_to_train])\r\n self.train_labels_true = list(np.array(self.train_labels_true)[idx_to_train])\r\n self.soft_labels = list(np.zeros((len(self.train_data),num_classes),dtype=np.float32))\r\n self.prediction = np.zeros((len(self.train_data),10,num_classes),dtype=np.float32)\r\n \r\n clean_labels = self.train_labels\r\n np.save('clean_labels.npy', clean_labels)\r\n\r\n if corruption_type == 'unif':\r\n C = uniform_mix_C(self.corruption_prob, num_classes)\r\n print(C)\r\n self.C = C\r\n elif corruption_type == 'flip':\r\n C = flip_labels_C(self.corruption_prob, num_classes)\r\n print(C)\r\n self.C = C\r\n elif corruption_type == 'flip2':\r\n C = flip_labels_C_two(self.corruption_prob, num_classes)\r\n print(C)\r\n self.C = C\r\n elif corruption_type == 'hierarchical':\r\n assert num_classes == 100, 'You must use CIFAR-100 with the hierarchical corruption.'\r\n coarse_fine = []\r\n for i in range(20):\r\n coarse_fine.append(set())\r\n for i in range(len(self.train_labels)):\r\n coarse_fine[self.train_coarse_labels[i]].add(self.train_labels[i])\r\n for i in range(20):\r\n coarse_fine[i] = list(coarse_fine[i])\r\n\r\n C = np.eye(num_classes) * (1 - corruption_prob)\r\n\r\n for i in range(20):\r\n tmp = np.copy(coarse_fine[i])\r\n for j in range(len(tmp)):\r\n tmp2 = np.delete(np.copy(tmp), j)\r\n C[tmp[j], tmp2] += corruption_prob * 1/len(tmp2)\r\n self.C = C\r\n print(C)\r\n elif corruption_type == 'clabels':\r\n net = wrn.WideResNet(40, num_classes, 2, dropRate=0.3).cuda()\r\n model_name = './cifar{}_labeler'.format(num_classes)\r\n net.load_state_dict(torch.load(model_name))\r\n net.eval()\r\n else:\r\n assert False, \"Invalid corruption type '{}' given. Must be in {'unif', 'flip', 'hierarchical'}\".format(corruption_type)\r\n np.random.seed(seed)\r\n if corruption_type == 'clabels':\r\n mean = [x / 255 for x in [125.3, 123.0, 113.9]]\r\n std = [x / 255 for x in [63.0, 62.1, 66.7]]\r\n\r\n test_transform = transforms.Compose(\r\n [transforms.ToTensor(), transforms.Normalize(mean, std)])\r\n\r\n # obtain sampling probabilities\r\n sampling_probs = []\r\n print('Starting labeling')\r\n\r\n for i in range((len(self.train_labels) // 64) + 1):\r\n current = self.train_data[i*64:(i+1)*64]\r\n current = [Image.fromarray(current[i]) for i in range(len(current))]\r\n current = torch.cat([test_transform(current[i]).unsqueeze(0) for i in range(len(current))], dim=0)\r\n\r\n data = V(current).cuda()\r\n logits = net(data)\r\n smax = F.softmax(logits / 5) # temperature of 1\r\n sampling_probs.append(smax.data.cpu().numpy())\r\n\r\n\r\n sampling_probs = np.concatenate(sampling_probs, 0)\r\n print('Finished labeling 1')\r\n\r\n new_labeling_correct = 0\r\n argmax_labeling_correct = 0\r\n for i in range(len(self.train_labels)):\r\n old_label = self.train_labels[i]\r\n new_label = np.random.choice(num_classes, p=sampling_probs[i])\r\n self.train_labels[i] = new_label\r\n if old_label == new_label:\r\n new_labeling_correct += 1\r\n if old_label == np.argmax(sampling_probs[i]):\r\n argmax_labeling_correct += 1\r\n print('Finished labeling 2')\r\n print('New labeling accuracy:', new_labeling_correct / len(self.train_labels))\r\n print('Argmax labeling accuracy:', argmax_labeling_correct / len(self.train_labels))\r\n else: \r\n for i in range(len(self.train_labels)):\r\n self.train_labels_true[i] = self.train_labels[i]\r\n for i in range(len(self.train_labels)):\r\n self.train_labels[i] = np.random.choice(num_classes, p=C[self.train_labels[i]])\r\n print('train',len(self.train_labels))\r\n print('type',type(self.train_labels))\r\n self.corruption_matrix = C\r\n noise_labels = self.train_labels\r\n np.save('noise_labels.npy', noise_labels)\r\n\r\n\r\n else:\r\n f = self.test_list[0][0]\r\n file = os.path.join(root, self.base_folder, f)\r\n fo = open(file, 'rb')\r\n if sys.version_info[0] == 2:\r\n entry = pickle.load(fo)\r\n else:\r\n entry = pickle.load(fo, encoding='latin1')\r\n self.test_data = entry['data']\r\n if 'labels' in entry:\r\n self.test_labels = entry['labels']\r\n else:\r\n self.test_labels = entry['fine_labels']\r\n fo.close()\r\n self.test_data = self.test_data.reshape((10000, 3, 32, 32))\r\n self.test_data = self.test_data.transpose((0, 2, 3, 1)) # convert to HWC\r\n def label_update(self, results):\r\n self.count += 1\r\n # While updating the noisy label y_i by the probability s, we used the average output probability of the network of the past 10 epochs as s.\r\n idx = (self.count - 1) % 10#10 #10\r\n self.prediction[:, idx] = results\r\n #self.prediction[:] =results\r\n #print(self.prediction)\r\n\r\n\r\n if self.count == 79: #79\r\n self.soft_labels = self.prediction.mean(axis=1)\r\n #print(self.soft_labels.shape)\r\n #print(self.soft_labels)\r\n #self.soft_labels = list(np.argmax(self.soft_labels, axis=1).astype(np.int64))\r\n if self.count > 79:\r\n self.soft_labels = results\r\n #self.soft_labels = list(np.argmax(self.soft_labels, axis=1).astype(np.int64))\r\n \r\n def __getitem__(self, index):\r\n if self.train:\r\n if self.meta:\r\n #print(self.train_labels[index])\r\n img, target, target_true= self.train_data[index], self.train_labels[index],self.train_labels_true[index]\r\n else:\r\n img, target, target_true= self.train_data[index], self.train_labels[index],self.train_labels_true[index]\r\n soft_labels = self.soft_labels[index]\r\n else:\r\n img, target = self.test_data[index], self.test_labels[index]\r\n\r\n # doing this so that it is consistent with all other datasets\r\n # to return a PIL Image\r\n img = Image.fromarray(img)\r\n\r\n if self.transform is not None:\r\n img = self.transform(img)\r\n\r\n if self.target_transform is not None:\r\n target = self.target_transform(target)\r\n if self.train :\r\n if self.meta:\r\n return img, target\r\n else:\r\n return img,target,target_true,soft_labels,index\r\n else:\r\n return img, target\r\n \r\n \r\n def __len__(self):\r\n if self.train:\r\n if self.meta is True:\r\n return self.num_meta\r\n else:\r\n return 50000 - self.num_meta\r\n else:\r\n return 10000\r\n\r\n def _check_integrity(self):\r\n root = self.root\r\n for fentry in (self.train_list + self.test_list):\r\n filename, md5 = fentry[0], fentry[1]\r\n fpath = os.path.join(root, self.base_folder, filename)\r\n if not check_integrity(fpath, md5):\r\n return False\r\n return True\r\n\r\n def download(self):\r\n import tarfile\r\n\r\n if self._check_integrity():\r\n print('Files already downloaded and verified')\r\n return\r\n\r\n root = self.root\r\n download_url(self.url, root, self.filename, self.tgz_md5)\r\n\r\n # extract file\r\n cwd = os.getcwd()\r\n tar = tarfile.open(os.path.join(root, self.filename), \"r:gz\")\r\n os.chdir(root)\r\n tar.extractall()\r\n tar.close()\r\n os.chdir(cwd)\r\n\r\n\r\nclass CIFAR100(CIFAR10):\r\n base_folder = 'cifar-100-python'\r\n url = \"http://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz\"\r\n filename = \"cifar-100-python.tar.gz\"\r\n tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'\r\n train_list = [\r\n ['train', '16019d7e3df5f24257cddd939b257f8d'],\r\n ]\r\n\r\n test_list = [\r\n ['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'],\r\n ]\r\n" ]
[ [ "torch.nn.functional.softmax", "numpy.random.seed", "numpy.random.choice", "torch.load", "numpy.arange", "numpy.eye", "numpy.save", "numpy.full", "numpy.concatenate", "numpy.random.shuffle", "numpy.copy", "numpy.argmax", "numpy.array", "torch.autograd.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
szzexpoi/AiR
[ "938ecfec51a306144eb72758530d42e35a10208d", "938ecfec51a306144eb72758530d42e35a10208d" ]
[ "AiR-M/ban/base_model.py", "AiR-M/util/loss.py" ]
[ "\"\"\"\nBilinear Attention Networks\nJin-Hwa Kim, Jaehyun Jun, Byoung-Tak Zhang\nhttps://arxiv.org/abs/1805.07932\n\nThis code is written by Jin-Hwa Kim.\n\"\"\"\nimport sys\nsys.path.append('./ban')\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.utils.weight_norm import weight_norm\nfrom attention import BiAttention\nfrom language_model import WordEmbedding, QuestionEmbedding\nfrom classifier import SimpleClassifier\nfrom fc import FCNet\nfrom bc import BCNet\nfrom counting import Counter\nfrom torch.autograd import Variable\n\n\nclass GRU(nn.Module):\n \"\"\"\n Gated Recurrent Unit without long-term memory\n \"\"\"\n def __init__(self,embed_size=512):\n super(GRU,self).__init__()\n self.update_x = nn.Linear(embed_size,embed_size,bias=True)\n self.update_h = nn.Linear(embed_size,embed_size,bias=True)\n self.reset_x = nn.Linear(embed_size,embed_size,bias=True)\n self.reset_h = nn.Linear(embed_size,embed_size,bias=True)\n self.memory_x = nn.Linear(embed_size,embed_size,bias=True)\n self.memory_h = nn.Linear(embed_size,embed_size,bias=True)\n\n def forward(self,x,state):\n z = F.sigmoid(self.update_x(x) + self.update_h(state))\n r = F.sigmoid(self.reset_x(x) + self.reset_h(state))\n mem = F.tanh(self.memory_x(x) + self.memory_h(torch.mul(r,state)))\n state = torch.mul(1-z,state) + torch.mul(z,mem)\n return state\n\ndef process_lengths(input):\n \"\"\"\n Computing the lengths of sentences in current batchs\n \"\"\"\n max_length = input.size(1)\n lengths = list(max_length - input.data.eq(0).sum(1).squeeze())\n return lengths\n\ndef select_last(x, lengths):\n \"\"\"\n Adaptively select the hidden state at the end of sentences\n \"\"\"\n batch_size = x.size(0)\n seq_length = x.size(1)\n mask = x.data.new().resize_as_(x.data).fill_(0)\n for i in range(batch_size):\n mask[i][lengths[i]-1].fill_(1)\n mask = Variable(mask)\n x = x.mul(mask)\n x = x.sum(1).view(batch_size, x.size(2), x.size(3))\n return x\n\nclass BanModel(nn.Module):\n def __init__(self, w_emb, q_emb, v_att, b_net, q_prj, c_prj, classifier, counter, op, glimpse,num_hid):\n super(BanModel, self).__init__()\n self.op = op\n self.glimpse = glimpse\n self.w_emb = w_emb\n self.q_emb = q_emb\n self.v_att = v_att\n self.b_net = nn.ModuleList(b_net)\n self.q_prj = nn.ModuleList(q_prj)\n self.c_prj = nn.ModuleList(c_prj)\n self.classifier = classifier\n self.counter = counter\n self.drop = nn.Dropout(.5)\n self.tanh = nn.Tanh()\n\n def forward(self, v, b, q):\n \"\"\"Forward\n\n v: [batch, num_objs, obj_dim]\n b: [batch, num_objs, b_dim]\n q: [batch_size, seq_length]\n\n return: logits, not probs\n \"\"\"\n w_emb = self.w_emb(q)\n q_emb = self.q_emb.forward_all(w_emb) # [batch, q_len, q_dim]\n boxes = b[:,:,:4].transpose(1,2)\n\n b_emb = [0] * self.glimpse\n att, logits = self.v_att.forward_all(v, q_emb) # b x g x v x q\n\n for g in range(self.glimpse):\n b_emb[g] = self.b_net[g].forward_with_weights(v, q_emb, att[:,g,:,:]) # b x l x h\n\n atten, _ = logits[:,g,:,:].max(2)\n embed = self.counter(boxes, atten)\n\n q_emb = self.q_prj[g](b_emb[g].unsqueeze(1)) + q_emb\n q_emb = q_emb + self.c_prj[g](embed).unsqueeze(1)\n\n logits = self.classifier(q_emb.sum(1))\n\n return F.softmax(logits,dim=-1), att\n\ndef build_ban(num_token, v_dim, num_hid, num_ans, op='', gamma=4, reasoning=False):\n w_emb = WordEmbedding(num_token, 300, .0, op)\n q_emb = QuestionEmbedding(300 if 'c' not in op else 600, num_hid, 1, False, .0)\n if not reasoning:\n v_att = BiAttention(v_dim, num_hid, num_hid, gamma)\n else:\n v_att = BiAttention(v_dim, num_hid, num_hid, 1)\n\n # constructing the model\n b_net = []\n q_prj = []\n c_prj = []\n objects = 36 # minimum number of boxes, originally 10\n for i in range(gamma):\n b_net.append(BCNet(v_dim, num_hid, num_hid, None, k=1))\n q_prj.append(FCNet([num_hid, num_hid], '', .2))\n c_prj.append(FCNet([objects + 1, num_hid], 'ReLU', .0))\n classifier = SimpleClassifier(\n num_hid, num_hid * 2, num_ans, .5)\n counter = Counter(objects)\n if not reasoning:\n return BanModel(w_emb, q_emb, v_att, b_net, q_prj, c_prj, classifier, counter, op, gamma, num_hid)\n else:\n return BanModel_Reasoning(w_emb, q_emb, v_att, b_net, q_prj, c_prj, classifier, counter, op, gamma, num_hid)\n\nclass BanModel_Reasoning(nn.Module):\n def __init__(self, w_emb, q_emb, v_att, b_net, q_prj, c_prj, classifier, counter, op, glimpse,num_hid):\n super(BanModel_Reasoning, self).__init__()\n self.op = op\n self.glimpse = glimpse\n self.w_emb = w_emb\n self.q_emb = q_emb\n self.v_att = v_att\n self.b_net = nn.ModuleList(b_net)\n self.q_prj = nn.ModuleList(q_prj)\n self.c_prj = nn.ModuleList(c_prj)\n self.classifier = classifier\n self.counter = counter\n self.drop = nn.Dropout(.5)\n self.tanh = nn.Tanh()\n\n self.semantic_rnn = GRU(256)\n self.semantic_q = nn.Linear(num_hid,256)\n self.semantic_pred = nn.Linear(256,9)\n self.semantic_embed = nn.Embedding(num_embeddings=9,embedding_dim=256) # embedding layer for the semantic operations\n self.att_p = nn.Linear(num_hid,num_hid)\n self.att = nn.Linear(num_hid,1)\n self.att_s = nn.Linear(256,num_hid)\n self.att_v = nn.Linear(2048,num_hid)\n\n\n def init_hidden_state(self,batch,s_embed=256):\n init_s = torch.zeros(batch,s_embed).cuda()\n return init_s\n\n def forward(self, v, b, q):\n \"\"\"Forward\n\n v: [batch, num_objs, obj_dim]\n b: [batch, num_objs, b_dim]\n q: [batch_size, seq_length]\n\n return: logits, not probs\n \"\"\"\n w_emb = self.w_emb(q)\n q_emb = self.q_emb.forward_all(w_emb) # [batch, q_len, q_dim]\n ori_q_emb = q_emb\n boxes = b[:,:,:4].transpose(1,2)\n b_emb = [0] * self.glimpse\n\n\n s_x = self.init_hidden_state(len(q),256)\n s_h = torch.tanh(self.semantic_q(ori_q_emb.mean(1)))\n v_att = torch.tanh(self.att_v(F.dropout(v,0.25)))\n op = []\n att_mask = []\n q_emb_pool = []\n\n for g in range(self.glimpse):\n # reasoning attention\n s_h = self.semantic_rnn(s_x,s_h)\n s_x = F.softmax(self.semantic_pred(s_h),dim=-1)\n op.append(s_x)\n s_x = torch.max(s_x,dim=-1)[1]\n s_x = self.semantic_embed(s_x)\n s_att = torch.tanh(self.att_s(s_h)).unsqueeze(1).expand_as(v_att)\n fuse_feat = torch.tanh(self.att_p(torch.mul(s_att,v_att)))\n reason_att = self.att(fuse_feat)\n reason_att = F.softmax(reason_att.view(reason_att.size(0),-1),dim=-1)\n # reason_att = torch.sigmoid(reason_att.view(reason_att.size(0),-1),dim=-1)\n # cur_v = v + torch.mul(v,reason_att.unsqueeze(-1).expand_as(v))\n cur_v = torch.mul(v,reason_att.unsqueeze(-1).expand_as(v))\n\n # original ban\n att, logits = self.v_att(cur_v, ori_q_emb) # b x g x v x q\n att, logits = att.squeeze(), logits.squeeze()\n b_emb[g] = self.b_net[g].forward_with_weights(v, q_emb, att) # b x l x h\n\n atten, _ = logits.max(2)\n embed = self.counter(boxes, atten)\n\n q_emb = self.q_prj[g](b_emb[g].unsqueeze(1)) + q_emb\n q_emb = q_emb + self.c_prj[g](embed).unsqueeze(1)\n q_emb_pool.append(q_emb)\n att_mask.append(reason_att)\n\n\n op = torch.cat([_.unsqueeze(1) for _ in op],dim=1)\n att_mask = torch.cat([_.unsqueeze(1) for _ in att_mask],dim=1)\n valid_op = process_lengths(torch.max(op,dim=-1)[1])\n q_emb_pool = torch.cat([_.unsqueeze(1) for _ in q_emb_pool],dim=1)\n q_emb = select_last(q_emb_pool,valid_op)\n\n logits = self.classifier(q_emb.sum(1))\n\n return F.softmax(logits,dim=-1), op, att_mask\n", "import torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nepsilon = 1e-16\n\ndef answer_loss(pred_ans,gt_ans,mask):\n gt_ans = gt_ans.unsqueeze(1).expand_as(pred_ans)\n loss = -(gt_ans*torch.log(torch.clamp(pred_ans,min=epsilon,max=1))).sum(-1)\n loss = torch.mul(loss,mask).sum(-1)/mask.sum(-1)\n return loss.mean()\n\ndef cross_entropy(input_,target):\n input_ = input_.view(input_.size(0), -1)\n loss = -(target*torch.log(torch.clamp(input_,min=epsilon,max=1))).sum(-1)\n return loss.mean()\n\ndef get_mask(gt_op):\n max_length = gt_op.size(1)\n gt_op = gt_op.sum(-1)\n lengths = list(max_length - gt_op.data.eq(0).sum(1).squeeze()) # get the valid length\n att_mask = gt_op.data.new().resize_as_(gt_op.data).fill_(0)\n ans_mask = gt_op.data.new().resize_as_(gt_op.data).fill_(0)\n for i in range(len(gt_op)):\n att_mask[i][:lengths[i]].fill_(1)\n ans_mask[i][:lengths[i]].fill_(1)\n # ans_mask[i][lengths[i]-1].fill_(1)\n att_mask = Variable(att_mask).cuda()\n ans_mask = Variable(ans_mask).cuda()\n\n return ans_mask, att_mask\n\ndef semantic_loss(pred_op,gt_op):\n loss = -(gt_op*torch.log(torch.clamp(pred_op,min=epsilon,max=1))).sum(-1)\n return loss.mean()\n\ndef attention_loss_mask(pred_att,gt_att,mask):\n # loss = ((pred_att-gt_att)**2).sum(-1) # MSE\n loss = -(gt_att*torch.log(torch.clamp(pred_att,min=epsilon,max=1))).sum(-1) # CE\n loss = torch.mul(loss,mask).mean()\n return loss\n\ndef attention_loss_mask_kld(pred_att,gt_att,mask):\n pred_att = pred_att.view(pred_att.size(0),pred_att.size(1),-1)\n gt_att = gt_att.view(gt_att.size(0),gt_att.size(1),-1)\n loss = torch.mul(gt_att,torch.log(torch.div(gt_att,pred_att+epsilon) + epsilon))\n loss = loss.sum(-1)\n loss = torch.mul(loss,mask).mean()\n return loss \n\ndef attention_loss(pred_att,gt_att):\n # loss = ((pred_att-gt_att)**2).sum(-1) # MSE\n loss = -(gt_att*torch.log(torch.clamp(pred_att,min=epsilon,max=1))).sum(-1) # CE\n return loss.mean() \n\ndef kld(pred_att,gt_att):\n pred_att = pred_att.view(pred_att.size(0),-1)\n gt_att = gt_att.view(gt_att.size(0),-1)\n loss = torch.mul(gt_att,torch.log(torch.div(gt_att,pred_att+epsilon) + epsilon))\n loss = loss.sum(-1)\n return torch.mean(loss)" ]
[ [ "torch.nn.Dropout", "torch.nn.functional.softmax", "torch.max", "torch.zeros", "torch.nn.functional.dropout", "torch.nn.ModuleList", "torch.nn.Embedding", "torch.nn.Tanh", "torch.nn.Linear", "torch.mul", "torch.autograd.Variable" ], [ "torch.mean", "torch.div", "torch.mul", "torch.clamp", "torch.autograd.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
SiggyF/bokeh
[ "52a2ce993b0f1102fd9e136f66036f52e91cdcc3" ]
[ "examples/app/clustering/main.py" ]
[ "import numpy as np\nnp.random.seed(0)\n\nfrom bokeh.io import curdoc\nfrom bokeh.layouts import widgetbox, row, column\nfrom bokeh.models import ColumnDataSource, Select, Slider\nfrom bokeh.plotting import figure\nfrom bokeh.palettes import Spectral6\n\nfrom sklearn import cluster, datasets\nfrom sklearn.neighbors import kneighbors_graph\nfrom sklearn.preprocessing import StandardScaler\n\n# define some helper functions\ndef clustering(X, algorithm, n_clusters):\n # normalize dataset for easier parameter selection\n X = StandardScaler().fit_transform(X)\n\n # estimate bandwidth for mean shift\n bandwidth = cluster.estimate_bandwidth(X, quantile=0.3)\n\n # connectivity matrix for structured Ward\n connectivity = kneighbors_graph(X, n_neighbors=10, include_self=False)\n\n # make connectivity symmetric\n connectivity = 0.5 * (connectivity + connectivity.T)\n\n # Generate the new colors:\n if algorithm=='MiniBatchKMeans':\n model = cluster.MiniBatchKMeans(n_clusters=n_clusters)\n\n elif algorithm=='Birch':\n model = cluster.Birch(n_clusters=n_clusters)\n\n elif algorithm=='DBSCAN':\n model = cluster.DBSCAN(eps=.2)\n\n elif algorithm=='AffinityPropagation':\n model = cluster.AffinityPropagation(damping=.9,\n preference=-200)\n\n elif algorithm=='MeanShift':\n model = cluster.MeanShift(bandwidth=bandwidth,\n bin_seeding=True)\n\n elif algorithm=='SpectralClustering':\n model = cluster.SpectralClustering(n_clusters=n_clusters,\n eigen_solver='arpack',\n affinity=\"nearest_neighbors\")\n\n elif algorithm=='Ward':\n model = cluster.AgglomerativeClustering(n_clusters=n_clusters,\n linkage='ward',\n connectivity=connectivity)\n\n elif algorithm=='AgglomerativeClustering':\n model = cluster.AgglomerativeClustering(linkage=\"average\",\n affinity=\"cityblock\",\n n_clusters=n_clusters,\n connectivity=connectivity)\n\n model.fit(X)\n\n if hasattr(model, 'labels_'):\n y_pred = model.labels_.astype(np.int)\n else:\n y_pred = model.predict(X)\n\n return X, y_pred\n\ndef get_dataset(dataset, n_samples):\n if dataset == 'Noisy Circles':\n return datasets.make_circles(n_samples=n_samples,\n factor=0.5,\n noise=0.05)\n\n elif dataset == 'Noisy Moons':\n return datasets.make_moons(n_samples=n_samples,\n noise=0.05)\n\n elif dataset == 'Blobs':\n return datasets.make_blobs(n_samples=n_samples,\n random_state=8)\n\n elif dataset == \"No Structure\":\n return np.random.rand(n_samples, 2), None\n\n# set up initial data\nn_samples = 1500\nn_clusters = 2\nalgorithm = 'MiniBatchKMeans'\ndataset = 'Noisy Circles'\n\nX, y = get_dataset(dataset, n_samples)\nX, y_pred = clustering(X, algorithm, n_clusters)\nspectral = np.hstack([Spectral6] * 20)\ncolors = [spectral[i] for i in y]\n\n# set up plot (styling in theme.yaml)\nplot = figure(toolbar_location=None, title=algorithm)\nsource = ColumnDataSource(data=dict(x=X[:, 0], y=X[:, 1], colors=colors))\nplot.circle('x', 'y', fill_color='colors', line_color=None, source=source)\n\n# set up widgets\nclustering_algorithms= [\n 'MiniBatchKMeans',\n 'AffinityPropagation',\n 'MeanShift',\n 'SpectralClustering',\n 'Ward',\n 'AgglomerativeClustering',\n 'DBSCAN',\n 'Birch'\n]\n\ndatasets_names = [\n 'Noisy Circles',\n 'Noisy Moons',\n 'Blobs',\n 'No Structure'\n]\n\nalgorithm_select = Select(value='MiniBatchKMeans',\n title='Select algorithm:',\n width=200,\n options=clustering_algorithms)\n\ndataset_select = Select(value='Noisy Circles',\n title='Select dataset:',\n width=200,\n options=datasets_names)\n\nsamples_slider = Slider(title=\"Number of samples\",\n value=1500.0,\n start=1000.0,\n end=3000.0,\n step=100,\n width=400)\n\nclusters_slider = Slider(title=\"Number of clusters\",\n value=2.0,\n start=2.0,\n end=10.0,\n step=1,\n width=400)\n\n# set up callbacks\ndef update_algorithm_or_clusters(attrname, old, new):\n global X\n\n algorithm = algorithm_select.value\n n_clusters = int(clusters_slider.value)\n\n X, y_pred = clustering(X, algorithm, n_clusters)\n colors = [spectral[i] for i in y_pred]\n\n source.data['colors'] = colors\n source.data['x'] = X[:, 0]\n source.data['y'] = X[:, 1]\n\n plot.title.text = algorithm\n\ndef update_samples_or_dataset(attrname, old, new):\n global X, y\n\n dataset = dataset_select.value\n algorithm = algorithm_select.value\n n_clusters = int(clusters_slider.value)\n n_samples = int(samples_slider.value)\n\n X, y = get_dataset(dataset, n_samples)\n X, y_pred = clustering(X, algorithm, n_clusters)\n colors = [spectral[i] for i in y_pred]\n\n source.data['x'] = X[:, 0]\n source.data['y'] = X[:, 1]\n source.data['colors'] = colors\n\nalgorithm_select.on_change('value', update_algorithm_or_clusters)\nclusters_slider.on_change('value', update_algorithm_or_clusters)\n\ndataset_select.on_change('value', update_samples_or_dataset)\nsamples_slider.on_change('value', update_samples_or_dataset)\n\n# set up layout\nselects = row(dataset_select, algorithm_select, width=420)\ninputs = column(selects, widgetbox(samples_slider, clusters_slider))\n\n# add to document\ncurdoc().add_root(row(inputs, plot))\ncurdoc().title = \"Clustering\"\n" ]
[ [ "numpy.hstack", "sklearn.cluster.estimate_bandwidth", "sklearn.cluster.AffinityPropagation", "sklearn.cluster.MeanShift", "numpy.random.seed", "sklearn.neighbors.kneighbors_graph", "sklearn.datasets.make_moons", "sklearn.cluster.DBSCAN", "sklearn.cluster.SpectralClustering", "sklearn.preprocessing.StandardScaler", "sklearn.cluster.AgglomerativeClustering", "sklearn.datasets.make_circles", "numpy.random.rand", "sklearn.cluster.Birch", "sklearn.cluster.MiniBatchKMeans", "sklearn.datasets.make_blobs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Jaikinator/dqc
[ "47c964c7d1323a35f4f69521d40476c41843810e", "47c964c7d1323a35f4f69521d40476c41843810e", "47c964c7d1323a35f4f69521d40476c41843810e" ]
[ "dqc/api/loadbasis.py", "dqc/hamilton/orbparams.py", "dqc/hamilton/hcgto.py" ]
[ "import os\r\nimport torch\r\nfrom typing import List\r\nfrom dqc.utils.datastruct import CGTOBasis\r\n\r\n__all__ = [\"loadbasis\"]\r\n\r\n_dtype = torch.double\r\n_device = torch.device(\"cpu\")\r\n\r\ndef loadbasis(cmd: str, dtype: torch.dtype = _dtype,\r\n device: torch.device = _device, requires_grad: bool = False) -> \\\r\n List[CGTOBasis]:\r\n \"\"\"\r\n Load basis from a file and return the list of CGTOBasis.\r\n\r\n Arguments\r\n ---------\r\n cmd: str\r\n This can be a file path where the basis is stored or a\r\n string in format ``\"atomz:basis\"``, e.g. ``\"1:6-311++G**\"``.\r\n dtype: torch.dtype\r\n Tensor data type for ``alphas`` and ``coeffs`` of the GTO basis\r\n device: torch.device\r\n Tensor device for ``alphas`` and ``coeffs``\r\n requires_grad: bool\r\n If ``True``, the ``alphas`` and ``coeffs`` tensors become differentiable\r\n\r\n Returns\r\n -------\r\n list of CGTOBasis\r\n List of GTO basis loaded from the given file\r\n \"\"\"\r\n res = []\r\n if not os.path.exists(cmd):\r\n file = _get_basis_file(cmd)\r\n else:\r\n file = cmd\r\n\r\n # read the content\r\n with open(file, \"r\") as f:\r\n lines = f.read().split(\"\\n\")\r\n\r\n # skip the header\r\n while True:\r\n line = lines.pop(0)\r\n if line == \"\":\r\n continue\r\n if line.startswith(\"!\"):\r\n continue\r\n break\r\n\r\n # now it is at the orbital description\r\n while len(lines) > 0:\r\n line = lines.pop(0)\r\n if line.startswith(\"**\"):\r\n break\r\n desc = line.split()\r\n nlines = int(desc[1])\r\n if nlines == 0:\r\n raise RuntimeError(\"Zero line on basis %s\" % file)\r\n\r\n # read the exponents and the coefficients\r\n alphas = []\r\n coeffsT = []\r\n for i in range(nlines):\r\n alphacoeff = [_read_float(f) for f in lines.pop(0).split()]\r\n alphas.append(alphacoeff[0])\r\n coeffsT.append(alphacoeff[1:])\r\n # coeffsT: list with shape (nbasis, ncontr)\r\n # coeffs: list with shape (ncontr, nbasis)\r\n coeffs = list(zip(*coeffsT))\r\n ncoeffs = len(coeffs)\r\n angmoms = _expand_angmoms(desc[0], ncoeffs)\r\n\r\n # convert to tensor\r\n alpha = torch.tensor(alphas, dtype=dtype, device=device, requires_grad=requires_grad)\r\n for i in range(ncoeffs):\r\n coeff = torch.tensor(coeffs[i], dtype=dtype, device=device, requires_grad=requires_grad)\r\n basis = CGTOBasis(angmom=angmoms[i], alphas=alpha, coeffs=coeff)\r\n basis.wfnormalize_()\r\n res.append(basis)\r\n return res\r\n\r\ndef _read_float(s: str) -> float:\r\n s = s.replace(\"D\", \"E\")\r\n return float(s)\r\n\r\ndef _get_basis_file(cmd: str) -> str:\r\n # parse the string command, check if the basis has already been downloaded\r\n # (download if not), and return the file name\r\n\r\n # parse to get the atomz and the basisname\r\n atomz_str, raw_basisname = cmd.split(\":\")\r\n raw_basisname = raw_basisname.strip()\r\n atomz = int(atomz_str)\r\n\r\n # get the path to the database\r\n basisname = _normalize_basisname(raw_basisname)\r\n thisdir = os.path.dirname(os.path.realpath(__file__))\r\n fname = \"%02d.gaussian94\" % atomz\r\n fdir = os.path.join(thisdir, \".database\", basisname)\r\n fpath = os.path.join(fdir, fname)\r\n\r\n # if the file does not exist, download it\r\n if not os.path.exists(fpath):\r\n print(\"The %s basis for atomz %d does not exist, but we will download it\" %\r\n (raw_basisname, atomz))\r\n if not os.path.exists(fdir):\r\n os.makedirs(fdir)\r\n _download_basis(fpath, atomz, raw_basisname)\r\n\r\n return fpath\r\n\r\ndef _normalize_basisname(basisname: str) -> str:\r\n b = basisname.lower()\r\n b = b.replace(\"+\", \"p\")\r\n b = b.replace(\"*\", \"s\")\r\n b = b.replace(\"(\", \"_\")\r\n b = b.replace(\")\", \"_\")\r\n b = b.replace(\",\", \"_\")\r\n return b\r\n\r\ndef _download_basis(fname: str, atomz: int, basisname: str) -> None:\r\n import basis_set_exchange as bse\r\n s = bse.get_basis(basisname, elements=[atomz], fmt=\"gaussian94\")\r\n with open(fname, \"w\") as f:\r\n f.write(s)\r\n print(\"Downloaded to %s\" % fname)\r\n\r\ndef _expand_angmoms(s: str, n: int) -> List[int]:\r\n # convert the angular momentum characters into angmom and returns a list\r\n # of n integer containing the angular momentums\r\n if len(s) == n:\r\n pass\r\n elif n % len(s) == 0:\r\n s = s * (n // len(s))\r\n else:\r\n raise RuntimeError(\"Do not know how to read orbital %s with %d coefficient columns\" %\r\n (s, n))\r\n s = s.lower()\r\n spdfmap = {\r\n \"s\": 0,\r\n \"p\": 1,\r\n \"d\": 2,\r\n \"f\": 3,\r\n \"g\": 4,\r\n \"h\": 5,\r\n \"i\": 6,\r\n }\r\n angmoms = [spdfmap[c] for c in s]\r\n return angmoms\r\n", "from typing import overload, Tuple\nimport torch\n\n__all__ = [\"BaseOrbParams\", \"QROrbParams\", \"MatExpOrbParams\"]\n\nclass BaseOrbParams(object):\n \"\"\"\n Class that provides free-parameterization of orthogonal orbitals.\n \"\"\"\n @overload\n @staticmethod\n def params2orb(params: torch.Tensor, coeffs: torch.Tensor, with_penalty: None) -> torch.Tensor:\n ...\n\n @overload\n @staticmethod\n def params2orb(params: torch.Tensor, coeffs: torch.Tensor, with_penalty: float) \\\n -> Tuple[torch.Tensor, torch.Tensor]:\n ...\n\n @staticmethod\n def params2orb(params, coeffs, with_penalty):\n \"\"\"\n Convert the parameters & coefficients to the orthogonal orbitals.\n ``params`` is the tensor to be optimized in variational method, while\n ``coeffs`` is a tensor that is needed to get the orbital, but it is not\n optimized in the variational method.\n \"\"\"\n pass\n\n @staticmethod\n def orb2params(orb: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Get the free parameters from the orthogonal orbitals. Returns ``params``\n and ``coeffs`` described in ``params2orb``.\n \"\"\"\n pass\n\nclass QROrbParams(BaseOrbParams):\n @overload\n @staticmethod\n def params2orb(params: torch.Tensor, coeffs: torch.Tensor, with_penalty: None) -> torch.Tensor:\n ...\n\n @overload\n @staticmethod\n def params2orb(params: torch.Tensor, coeffs: torch.Tensor, with_penalty: float) \\\n -> Tuple[torch.Tensor, torch.Tensor]:\n ...\n\n @staticmethod\n def params2orb(params, coeffs, with_penalty):\n orb, _ = torch.linalg.qr(params)\n if with_penalty is None:\n return orb\n else:\n # QR decomposition's solution is not unique in a way that every column\n # can be multiplied by -1 and it still a solution\n # So, to remove the non-uniqueness, we will make the sign of the sum\n # positive.\n s1 = torch.sign(orb.sum(dim=-2, keepdim=True)) # (*BD, 1, norb)\n s2 = torch.sign(params.sum(dim=-2, keepdim=True))\n penalty = torch.mean((orb * s1 - params * s2) ** 2) * with_penalty\n return orb, penalty\n\n @staticmethod\n def orb2params(orb: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n coeffs = torch.tensor([0], dtype=orb.dtype, device=orb.device)\n return orb, coeffs\n\nclass MatExpOrbParams(BaseOrbParams):\n \"\"\"\n Orthogonal orbital parameterization using matrix exponential.\n The orthogonal orbital is represented by:\n\n P = matrix_exp(Q) @ C\n\n where C is an orthogonal coefficient tensor, and Q is the parameters defining\n the rotation of the orthogonal tensor.\n \"\"\"\n @overload\n @staticmethod\n def params2orb(params: torch.Tensor, coeffs: torch.Tensor, with_penalty: None) -> torch.Tensor:\n ...\n\n @overload\n @staticmethod\n def params2orb(params: torch.Tensor, coeffs: torch.Tensor, with_penalty: float) \\\n -> Tuple[torch.Tensor, torch.Tensor]:\n ...\n\n @staticmethod\n def params2orb(params, coeffs, with_penalty):\n # params: (*, nparams)\n # coeffs: (*, nao, norb)\n nao = coeffs.shape[-2]\n norb = coeffs.shape[-1]\n nparams = params.shape[-1]\n bshape = params.shape[:-1]\n\n # construct the rotation parameters\n triu_idxs = torch.triu_indices(nao, nao, offset=1)[..., :nparams]\n rotmat = torch.zeros((*bshape, nao, nao), dtype=params.dtype, device=params.device)\n rotmat[..., triu_idxs[0], triu_idxs[1]] = params\n rotmat = rotmat - rotmat.transpose(-2, -1).conj()\n\n # calculate the orthogonal orbital\n ortho_orb = torch.matrix_exp(rotmat) @ coeffs\n\n if with_penalty:\n penalty = torch.zeros((1,), dtype=params.dtype, device=params.device)\n return ortho_orb, penalty\n else:\n return ortho_orb\n\n @staticmethod\n def orb2params(orb: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n # orb: (*, nao, norb)\n nao = orb.shape[-2]\n norb = orb.shape[-1]\n nparams = norb * (nao - norb) + norb * (norb - 1) // 2\n\n # the orbital becomes the coefficients while params is all zeros (no rotation)\n coeffs = orb\n params = torch.zeros((*orb.shape[:-2], nparams), dtype=orb.dtype, device=orb.device)\n return params, coeffs\n", "from typing import List, Optional, Union, overload, Tuple, Type\nimport warnings\nimport torch\nimport xitorch as xt\nimport dqc.hamilton.intor as intor\nfrom dqc.df.base_df import BaseDF\nfrom dqc.df.dfmol import DFMol\nfrom dqc.hamilton.base_hamilton import BaseHamilton\nfrom dqc.hamilton.orbconverter import OrbitalOrthogonalizer, IdentityOrbConverter\nfrom dqc.hamilton.orbparams import BaseOrbParams, QROrbParams, MatExpOrbParams\nfrom dqc.utils.datastruct import AtomCGTOBasis, ValGrad, SpinParam, DensityFitInfo\nfrom dqc.grid.base_grid import BaseGrid\nfrom dqc.xc.base_xc import BaseXC\nfrom dqc.utils.cache import Cache\nfrom dqc.utils.mem import chunkify, get_dtype_memsize\nfrom dqc.utils.config import config\nfrom dqc.utils.misc import logger\n\nclass HamiltonCGTO(BaseHamilton):\n \"\"\"\n Hamiltonian object of contracted Gaussian type-orbital.\n This class orthogonalizes the basis by taking the weighted eigenvectors of\n the overlap matrix, i.e. the eigenvectors divided by square root of the\n eigenvalues.\n The advantage of doing this is making the overlap matrix in Roothan's equation\n identity and it could handle overcomplete basis.\n \"\"\"\n def __init__(self, atombases: List[AtomCGTOBasis], spherical: bool = True,\n df: Optional[DensityFitInfo] = None,\n efield: Optional[Tuple[torch.Tensor, ...]] = None,\n vext: Optional[torch.Tensor] = None,\n cache: Optional[Cache] = None,\n orthozer: bool = True,\n aoparamzer: str = \"qr\") -> None:\n self.atombases = atombases\n self.spherical = spherical\n self.libcint_wrapper = intor.LibcintWrapper(atombases, spherical)\n self.dtype = self.libcint_wrapper.dtype\n self.device = self.libcint_wrapper.device\n\n # set up the orbital converter\n ovlp = intor.overlap(self.libcint_wrapper)\n if orthozer:\n self._orthozer = OrbitalOrthogonalizer(ovlp)\n else:\n self._orthozer = IdentityOrbConverter(ovlp)\n\n # set up the orbital parameterized\n if aoparamzer == \"qr\":\n self._orbparam: Type[BaseOrbParams] = QROrbParams\n elif aoparamzer == \"matexp\":\n warnings.warn(\"Parametrization with matrix exponential is still at the experimental stage.\")\n self._orbparam = MatExpOrbParams\n else:\n aoparam_opts = [\"qr\", \"matexp\"]\n raise RuntimeError(\n f\"Unknown ao parameterizer: {aoparamzer}. Available options are: {aoparam_opts}\")\n\n # set up the density matrix\n self._dfoptions = df\n if df is None:\n self._df: Optional[DFMol] = None\n else:\n self._df = DFMol(df, wrapper=self.libcint_wrapper, orthozer=self._orthozer)\n\n self._efield = efield\n self._vext = vext\n self.is_grid_set = False\n self.is_ao_set = False\n self.is_grad_ao_set = False\n self.is_lapl_ao_set = False\n self.xc: Optional[BaseXC] = None\n self.xcfamily = 1\n self.is_built = False\n\n # initialize cache\n self._cache = cache if cache is not None else Cache.get_dummy()\n self._cache.add_cacheable_params([\"overlap\", \"kinetic\", \"nuclattr\", \"efield0\"])\n if self._df is None:\n self._cache.add_cacheable_params([\"elrep\"])\n\n @property\n def nao(self) -> int:\n return self._orthozer.nao()\n\n @property\n def kpts(self) -> torch.Tensor:\n raise TypeError(\"Isolated molecule Hamiltonian does not have kpts property\")\n\n @property\n def df(self) -> Optional[BaseDF]:\n return self._df\n\n ############# setups #############\n def build(self) -> BaseHamilton:\n # get the matrices (all (nao, nao), except el_mat)\n # these matrices have already been normalized\n with self._cache.open():\n\n # check the signature\n self._cache.check_signature({\n \"atombases\": self.atombases,\n \"spherical\": self.spherical,\n \"dfoptions\": self._dfoptions,\n })\n\n logger.log(\"Calculating the overlap matrix\")\n self.olp_mat = self._cache.cache(\"overlap\", lambda: intor.overlap(self.libcint_wrapper))\n logger.log(\"Calculating the kinetic matrix\")\n kin_mat = self._cache.cache(\"kinetic\", lambda: intor.kinetic(self.libcint_wrapper))\n logger.log(\"Calculating the nuclear attraction matrix\")\n nucl_mat = self._cache.cache(\"nuclattr\", lambda: intor.nuclattr(self.libcint_wrapper))\n self.nucl_mat = nucl_mat\n self.kinnucl_mat = kin_mat + nucl_mat\n\n # electric field integral\n if self._efield is not None:\n # (ndim, nao, nao)\n fac: float = 1.0\n for i in range(len(self._efield)):\n fac *= i + 1\n intor_fcn = lambda: intor.int1e(\"r0\" * (i + 1), self.libcint_wrapper)\n efield_mat_f = self._cache.cache(f\"efield{i}\", intor_fcn)\n efield_mat = torch.einsum(\"dab,d->ab\", efield_mat_f, self._efield[i])\n self.kinnucl_mat = self.kinnucl_mat + efield_mat / fac\n\n if self._df is None:\n logger.log(\"Calculating the electron repulsion matrix\")\n self.el_mat = self._cache.cache(\"elrep\", lambda: intor.elrep(self.libcint_wrapper)) # (nao^4)\n # TODO: decide whether to precompute the 2-eris in the new basis\n # based on the memory\n self.el_mat = self._orthozer.convert4(self.el_mat)\n else:\n logger.log(\"Building the density fitting matrices\")\n self._df.build()\n self.is_built = True\n\n # orthogonalize the matrices\n self.olp_mat = self._orthozer.convert2(self.olp_mat) # (nao2, nao2)\n self.kinnucl_mat = self._orthozer.convert2(self.kinnucl_mat)\n self.nucl_mat = self._orthozer.convert2(self.nucl_mat)\n\n # external potential\n if self._vext is not None:\n vext_mat = self.get_vext(self._vext).fullmatrix()\n self.kinnucl_mat = self.kinnucl_mat + vext_mat\n\n logger.log(\"Setting up the Hamiltonian done\")\n\n return self\n\n def setup_grid(self, grid: BaseGrid, xc: Optional[BaseXC] = None) -> None:\n # save the family and save the xc\n self.xc = xc\n if xc is None:\n self.xcfamily = 1\n else:\n self.xcfamily = xc.family\n\n # save the grid\n self.grid = grid\n self.rgrid = grid.get_rgrid()\n assert grid.coord_type == \"cart\"\n\n # setup the basis as a spatial function\n logger.log(\"Calculating the basis values in the grid\")\n self.is_ao_set = True\n self.basis = intor.eval_gto(self.libcint_wrapper, self.rgrid, to_transpose=True) # (ngrid, nao)\n self.dvolume = self.grid.get_dvolume()\n self.basis_dvolume = self.basis * self.dvolume.unsqueeze(-1) # (ngrid, nao)\n\n if self.xcfamily == 1: # LDA\n return\n\n # setup the gradient of the basis\n logger.log(\"Calculating the basis gradient values in the grid\")\n self.is_grad_ao_set = True\n # (ndim, nao, ngrid)\n self.grad_basis = intor.eval_gradgto(self.libcint_wrapper, self.rgrid, to_transpose=True)\n if self.xcfamily == 2: # GGA\n return\n\n # setup the laplacian of the basis\n self.is_lapl_ao_set = True\n logger.log(\"Calculating the basis laplacian values in the grid\")\n self.lapl_basis = intor.eval_laplgto(self.libcint_wrapper, self.rgrid, to_transpose=True) # (nao, ngrid)\n\n ############ fock matrix components ############\n def get_nuclattr(self) -> xt.LinearOperator:\n # nucl_mat: (nao, nao)\n # return: (nao, nao)\n return xt.LinearOperator.m(self.nucl_mat, is_hermitian=True)\n\n def get_kinnucl(self) -> xt.LinearOperator:\n # kinnucl_mat: (nao, nao)\n # return: (nao, nao)\n return xt.LinearOperator.m(self.kinnucl_mat, is_hermitian=True)\n\n def get_overlap(self) -> xt.LinearOperator:\n # olp_mat: (nao, nao)\n # return: (nao, nao)\n return xt.LinearOperator.m(self.olp_mat, is_hermitian=True)\n\n def get_elrep(self, dm: torch.Tensor) -> xt.LinearOperator:\n # dm: (*BD, nao, nao)\n # elrep_mat: (nao, nao, nao, nao)\n # return: (*BD, nao, nao)\n if self._df is None:\n mat = torch.einsum(\"...ij,ijkl->...kl\", dm, self.el_mat)\n mat = (mat + mat.transpose(-2, -1)) * 0.5 # reduce numerical instability\n return xt.LinearOperator.m(mat, is_hermitian=True)\n else:\n elrep = self._df.get_elrep(dm)\n return elrep\n\n @overload\n def get_exchange(self, dm: torch.Tensor) -> xt.LinearOperator:\n ...\n\n @overload\n def get_exchange(self, dm: SpinParam[torch.Tensor]) -> SpinParam[xt.LinearOperator]:\n ...\n\n def get_exchange(self, dm):\n # get the exchange operator\n # dm: (*BD, nao, nao)\n # el_mat: (nao, nao, nao, nao)\n # return: (*BD, nao, nao)\n if self._df is not None:\n raise RuntimeError(\"Exact exchange cannot be computed with density fitting\")\n elif isinstance(dm, torch.Tensor):\n # the einsum form below is to hack PyTorch's bug #57121\n # mat = -0.5 * torch.einsum(\"...jk,ijkl->...il\", dm, self.el_mat) # slower\n mat = -0.5 * torch.einsum(\"...il,ijkl->...ijk\", dm, self.el_mat).sum(dim=-3) # faster\n\n mat = (mat + mat.transpose(-2, -1)) * 0.5 # reduce numerical instability\n return xt.LinearOperator.m(mat, is_hermitian=True)\n else: # dm is SpinParam\n # using the spin-scaling property of exchange energy\n return SpinParam(u=self.get_exchange(2 * dm.u),\n d=self.get_exchange(2 * dm.d))\n\n def get_vext(self, vext: torch.Tensor) -> xt.LinearOperator:\n # vext: (*BR, ngrid)\n if not self.is_ao_set:\n raise RuntimeError(\"Please call `setup_grid(grid, xc)` to call this function\")\n mat = torch.einsum(\"...r,rb,rc->...bc\", vext, self.basis_dvolume, self.basis) # (*BR, nao, nao)\n mat = self._orthozer.convert2(mat)\n mat = (mat + mat.transpose(-2, -1)) * 0.5 # ensure the symmetricity and reduce numerical instability\n return xt.LinearOperator.m(mat, is_hermitian=True)\n\n @overload\n def get_vxc(self, dm: SpinParam[torch.Tensor]) -> SpinParam[xt.LinearOperator]:\n ...\n\n @overload\n def get_vxc(self, dm: torch.Tensor) -> xt.LinearOperator:\n ...\n\n def get_vxc(self, dm):\n # dm: (*BD, nao, nao)\n assert self.xc is not None, \"Please call .setup_grid with the xc object\"\n\n densinfo = SpinParam.apply_fcn(\n lambda dm_: self._dm2densinfo(dm_), dm) # value: (*BD, nr)\n potinfo = self.xc.get_vxc(densinfo) # value: (*BD, nr)\n vxc_linop = SpinParam.apply_fcn(\n lambda potinfo_: self._get_vxc_from_potinfo(potinfo_), potinfo)\n return vxc_linop\n\n ############### interface to dm ###############\n def ao_orb2dm(self, orb: torch.Tensor, orb_weight: torch.Tensor) -> torch.Tensor:\n # convert the atomic orbital to the density matrix\n # in CGTO, it is U.W.U^T\n\n # orb: (*BO, nao, norb)\n # orb_weight: (*BW, norb)\n # return: (*BOW, nao, nao)\n\n orb_w = orb * orb_weight.unsqueeze(-2) # (*BOW, nao, norb)\n return torch.matmul(orb, orb_w.transpose(-2, -1)) # (*BOW, nao, nao)\n\n def aodm2dens(self, dm: torch.Tensor, xyz: torch.Tensor) -> torch.Tensor:\n # xyz: (*BR, ndim)\n # dm: (*BD, nao, nao)\n # returns: (*BRD)\n\n dm = self._orthozer.unconvert_dm(dm)\n\n nao = dm.shape[-1]\n xyzshape = xyz.shape\n # basis: (nao, *BR)\n basis = intor.eval_gto(self.libcint_wrapper, xyz.reshape(-1, xyzshape[-1])).reshape((nao, *xyzshape[:-1]))\n basis = torch.movedim(basis, 0, -1) # (*BR, nao)\n\n # torch.einsum(\"...ij,...i,...j->...\", dm, basis, basis)\n dens = torch.matmul(dm, basis.unsqueeze(-1)) # (*BRD, nao, 1)\n dens = torch.matmul(basis.unsqueeze(-2), dens).squeeze(-1).squeeze(-1) # (*BRD)\n return dens\n\n ############### energy of the Hamiltonian ###############\n def get_e_hcore(self, dm: torch.Tensor) -> torch.Tensor:\n # get the energy from one electron operator\n return torch.einsum(\"...ij,...ji->...\", self.kinnucl_mat, dm)\n\n def get_e_elrep(self, dm: torch.Tensor) -> torch.Tensor:\n # get the energy from two electron repulsion operator\n elrep_mat = self.get_elrep(dm).fullmatrix()\n return 0.5 * torch.einsum(\"...ij,...ji->...\", elrep_mat, dm)\n\n def get_e_exchange(self, dm: Union[torch.Tensor, SpinParam[torch.Tensor]]) -> torch.Tensor:\n # get the energy from two electron exchange operator\n exc_mat = self.get_exchange(dm)\n ene = SpinParam.apply_fcn(\n lambda exc_mat, dm: 0.5 * torch.einsum(\"...ij,...ji->...\", exc_mat.fullmatrix(), dm),\n exc_mat, dm)\n enetot = SpinParam.sum(ene)\n return enetot\n\n def get_e_xc(self, dm: Union[torch.Tensor, SpinParam[torch.Tensor]]) -> torch.Tensor:\n assert self.xc is not None, \"Please call .setup_grid with the xc object\"\n\n # obtain the energy density per unit volume\n densinfo = SpinParam.apply_fcn(\n lambda dm_: self._dm2densinfo(dm_), dm) # (spin) value: (*BD, nr)\n edens = self.xc.get_edensityxc(densinfo) # (*BD, nr)\n\n return torch.sum(self.grid.get_dvolume() * edens, dim=-1)\n\n ############### free parameters for variational method ###############\n @overload\n def ao_orb_params2dm(self, ao_orb_params: torch.Tensor, ao_orb_coeffs: torch.Tensor,\n orb_weight: torch.Tensor,\n with_penalty: None) -> torch.Tensor:\n ...\n\n @overload\n def ao_orb_params2dm(self, ao_orb_params: torch.Tensor, ao_orb_coeffs: torch.Tensor,\n orb_weight: torch.Tensor,\n with_penalty: float) -> Union[torch.Tensor, torch.Tensor]:\n ...\n\n def ao_orb_params2dm(self, ao_orb_params, ao_orb_coeffs, orb_weight, with_penalty=None):\n # convert from atomic orbital parameters to density matrix\n # the atomic orbital parameter is the inverse QR of the orbital\n # ao_orb_params: (*BD, nao, norb)\n out = self._orbparam.params2orb(ao_orb_params, ao_orb_coeffs, with_penalty=with_penalty)\n if with_penalty is None:\n ao_orbq = out\n else:\n ao_orbq, penalty = out\n\n ao_orb = self._orthozer.convert_ortho_orb(ao_orbq)\n dm = self.ao_orb2dm(ao_orb, orb_weight)\n if with_penalty is None:\n return dm\n else:\n return dm, penalty\n\n def dm2ao_orb_params(self, dm: torch.Tensor, norb: int) -> Tuple[torch.Tensor, torch.Tensor]:\n # convert back the density matrix to one solution in the parameters space\n # NOTE: this assumes that the orbital weights always decreasing in order\n mdmm = self._orthozer.unconvert_to_ortho_dm(dm)\n w, orbq = torch.linalg.eigh(mdmm)\n # w is ordered increasingly, so we take the last parts\n orbq_params = orbq[..., -norb:] # (nao, norb)\n orbq_params = torch.flip(orbq_params, dims=(-1,))\n return self._orbparam.orb2params(orbq_params)\n\n ################ misc ################\n def _dm2densinfo(self, dm: torch.Tensor) -> ValGrad:\n # dm: (*BD, nao, nao), Hermitian\n # family: 1 for LDA, 2 for GGA, 3 for MGGA\n # self.basis: (ngrid, nao)\n # self.grad_basis: (ndim, ngrid, nao)\n\n ngrid = self.basis.shape[-2]\n batchshape = dm.shape[:-2]\n\n # dm @ ao will be used in every case\n dmdmt = (dm + dm.transpose(-2, -1)) * 0.5 # (*BD, nao2, nao2)\n # convert it back to dm in the cgto basis\n dmdmt = self._orthozer.unconvert_dm(dmdmt)\n\n # prepare the densinfo components\n dens = torch.empty((*batchshape, ngrid), dtype=self.dtype, device=self.device)\n gdens: Optional[torch.Tensor] = None\n lapldens: Optional[torch.Tensor] = None\n kindens: Optional[torch.Tensor] = None\n if self.xcfamily == 2 or self.xcfamily == 4: # GGA or MGGA\n gdens = torch.empty((*dm.shape[:-2], 3, ngrid),\n dtype=self.dtype, device=self.device) # (..., ndim, ngrid)\n if self.xcfamily == 4: # MGGA\n lapldens = torch.empty((*batchshape, ngrid), dtype=self.dtype, device=self.device)\n kindens = torch.empty((*batchshape, ngrid), dtype=self.dtype, device=self.device)\n\n # It is faster to split into chunks than evaluating a single big chunk\n maxnumel = config.CHUNK_MEMORY // get_dtype_memsize(self.basis)\n for basis, ioff, iend in chunkify(self.basis, dim=0, maxnumel=maxnumel):\n # basis: (ngrid2, nao)\n\n dmao = torch.matmul(basis, dmdmt) # (ngrid2, nao)\n dens[..., ioff:iend] = torch.einsum(\"...ri,ri->...r\", dmao, basis)\n\n if self.xcfamily == 2 or self.xcfamily == 4: # GGA or MGGA\n assert gdens is not None\n if not self.is_grad_ao_set:\n msg = \"Please call `setup_grid(grid, gradlevel>=1)` to calculate the density gradient\"\n raise RuntimeError(msg)\n\n # summing it 3 times is faster than applying the d-axis directly\n grad_basis0 = self.grad_basis[0, ioff:iend, :] # (ngrid2, nao)\n grad_basis1 = self.grad_basis[1, ioff:iend, :]\n grad_basis2 = self.grad_basis[2, ioff:iend, :]\n\n gdens[..., 0, ioff:iend] = torch.einsum(\"...ri,ri->...r\", dmao, grad_basis0) * 2\n gdens[..., 1, ioff:iend] = torch.einsum(\"...ri,ri->...r\", dmao, grad_basis1) * 2\n gdens[..., 2, ioff:iend] = torch.einsum(\"...ri,ri->...r\", dmao, grad_basis2) * 2\n\n if self.xcfamily == 4:\n assert lapldens is not None\n assert kindens is not None\n # calculate the laplacian of the density and kinetic energy density at the grid\n if not self.is_lapl_ao_set:\n msg = \"Please call `setup_grid(grid, gradlevel>=2)` to calculate the density gradient\"\n raise RuntimeError(msg)\n\n lapl_basis_cat = self.lapl_basis[ioff:iend, :]\n lapl_basis = torch.einsum(\"...ri,ri->...r\", dmao, lapl_basis_cat)\n grad_grad = torch.einsum(\"...ri,ri->...r\", torch.matmul(grad_basis0, dmdmt), grad_basis0)\n grad_grad += torch.einsum(\"...ri,ri->...r\", torch.matmul(grad_basis1, dmdmt), grad_basis1)\n grad_grad += torch.einsum(\"...ri,ri->...r\", torch.matmul(grad_basis2, dmdmt), grad_basis2)\n # pytorch's \"...ij,ir,jr->...r\" is really slow for large matrix\n # grad_grad = torch.einsum(\"...ij,ir,jr->...r\", dmdmt, self.grad_basis[0], self.grad_basis[0])\n # grad_grad += torch.einsum(\"...ij,ir,jr->...r\", dmdmt, self.grad_basis[1], self.grad_basis[1])\n # grad_grad += torch.einsum(\"...ij,ir,jr->...r\", dmdmt, self.grad_basis[2], self.grad_basis[2])\n lapldens[..., ioff:iend] = (lapl_basis + grad_grad) * 2\n kindens[..., ioff:iend] = grad_grad * 0.5\n\n # dens: (*BD, ngrid)\n # gdens: (*BD, ndim, ngrid)\n res = ValGrad(value=dens, grad=gdens, lapl=lapldens, kin=kindens)\n return res\n\n def _get_vxc_from_potinfo(self, potinfo: ValGrad) -> xt.LinearOperator:\n # obtain the vxc operator from the potential information\n # potinfo.value: (*BD, nr)\n # potinfo.grad: (*BD, ndim, nr)\n # potinfo.lapl: (*BD, nr)\n # potinfo.kin: (*BD, nr)\n # self.basis: (nr, nao)\n # self.grad_basis: (ndim, nr, nao)\n\n # prepare the fock matrix component from vxc\n nao = self.basis.shape[-1]\n mat = torch.zeros((*potinfo.value.shape[:-1], nao, nao), dtype=self.dtype, device=self.device)\n\n # Split the r-dimension into several parts, it is usually faster than\n # evaluating all at once\n maxnumel = config.CHUNK_MEMORY // get_dtype_memsize(self.basis)\n for basis, ioff, iend in chunkify(self.basis, dim=0, maxnumel=maxnumel):\n # basis: (nr, nao)\n vb = potinfo.value[..., ioff:iend].unsqueeze(-1) * basis # (*BD, nr, nao)\n if self.xcfamily in [2, 4]: # GGA or MGGA\n assert potinfo.grad is not None # (..., ndim, nr)\n vgrad = potinfo.grad[..., ioff:iend] * 2\n grad_basis0 = self.grad_basis[0, ioff:iend, :] # (nr, nao)\n grad_basis1 = self.grad_basis[1, ioff:iend, :]\n grad_basis2 = self.grad_basis[2, ioff:iend, :]\n vb += torch.einsum(\"...r,ra->...ra\", vgrad[..., 0, :], grad_basis0)\n vb += torch.einsum(\"...r,ra->...ra\", vgrad[..., 1, :], grad_basis1)\n vb += torch.einsum(\"...r,ra->...ra\", vgrad[..., 2, :], grad_basis2)\n if self.xcfamily == 4: # MGGA\n assert potinfo.lapl is not None # (..., nrgrid)\n assert potinfo.kin is not None\n lapl = potinfo.lapl[..., ioff:iend]\n kin = potinfo.kin[..., ioff:iend]\n vb += 2 * lapl.unsqueeze(-1) * self.lapl_basis[ioff:iend, :]\n\n # calculating the matrix from multiplication with the basis\n mat += torch.matmul(self.basis_dvolume[ioff:iend, :].transpose(-2, -1), vb)\n\n if self.xcfamily == 4: # MGGA\n assert potinfo.lapl is not None # (..., nrgrid)\n assert potinfo.kin is not None\n lapl_kin_dvol = (2 * lapl + 0.5 * kin) * self.dvolume[..., ioff:iend]\n mat += torch.einsum(\"...r,rb,rc->...bc\", lapl_kin_dvol, grad_basis0, grad_basis0)\n mat += torch.einsum(\"...r,rb,rc->...bc\", lapl_kin_dvol, grad_basis1, grad_basis1)\n mat += torch.einsum(\"...r,rb,rc->...bc\", lapl_kin_dvol, grad_basis2, grad_basis2)\n\n # construct the Hermitian linear operator\n mat = self._orthozer.convert2(mat)\n mat = (mat + mat.transpose(-2, -1)) * 0.5\n vxc_linop = xt.LinearOperator.m(mat, is_hermitian=True)\n return vxc_linop\n\n def getparamnames(self, methodname: str, prefix: str = \"\") -> List[str]:\n if methodname == \"get_kinnucl\":\n return [prefix + \"kinnucl_mat\"]\n elif methodname == \"get_nuclattr\":\n return [prefix + \"nucl_mat\"]\n elif methodname == \"get_overlap\":\n return [prefix + \"olp_mat\"]\n elif methodname == \"get_elrep\":\n if self._df is None:\n return [prefix + \"el_mat\"]\n else:\n return self._df.getparamnames(\"get_elrep\", prefix=prefix + \"_df.\")\n elif methodname == \"get_exchange\":\n return [prefix + \"el_mat\"]\n elif methodname == \"ao_orb2dm\":\n return []\n elif methodname == \"ao_orb_params2dm\":\n return self.getparamnames(\"ao_orb2dm\", prefix=prefix) + \\\n self._orthozer.getparamnames(\"convert_ortho_orb\", prefix=prefix + \"_orthozer.\")\n elif methodname == \"get_e_hcore\":\n return [prefix + \"kinnucl_mat\"]\n elif methodname == \"get_e_elrep\":\n return self.getparamnames(\"get_elrep\", prefix=prefix)\n elif methodname == \"get_e_exchange\":\n return self.getparamnames(\"get_exchange\", prefix=prefix)\n elif methodname == \"get_e_xc\":\n assert self.xc is not None\n return self.getparamnames(\"_dm2densinfo\", prefix=prefix) + \\\n self.xc.getparamnames(\"get_edensityxc\", prefix=prefix + \"xc.\") + \\\n self.grid.getparamnames(\"get_dvolume\", prefix=prefix + \"grid.\")\n elif methodname == \"get_vext\":\n return [prefix + \"basis_dvolume\", prefix + \"basis\"] + \\\n self._orthozer.getparamnames(\"convert2\", prefix=prefix + \"_orthozer.\")\n elif methodname == \"get_grad_vext\":\n return [prefix + \"basis_dvolume\", prefix + \"grad_basis\"]\n elif methodname == \"get_lapl_kin_vext\":\n return [prefix + \"dvolume\", prefix + \"basis\", prefix + \"grad_basis\",\n prefix + \"lapl_basis\"]\n elif methodname == \"get_vxc\":\n assert self.xc is not None\n return self.getparamnames(\"_dm2densinfo\", prefix=prefix) + \\\n self.getparamnames(\"_get_vxc_from_potinfo\", prefix=prefix) + \\\n self.xc.getparamnames(\"get_vxc\", prefix=prefix + \"xc.\")\n elif methodname == \"_dm2densinfo\":\n params = [prefix + \"basis\"] + \\\n self._orthozer.getparamnames(\"unconvert_dm\", prefix=prefix + \"_orthozer.\")\n if self.xcfamily == 2 or self.xcfamily == 4:\n params += [prefix + \"grad_basis\"]\n if self.xcfamily == 4:\n params += [prefix + \"lapl_basis\"]\n return params\n elif methodname == \"_get_vxc_from_potinfo\":\n params = [prefix + \"basis\", prefix + \"basis_dvolume\"] + \\\n self._orthozer.getparamnames(\"convert2\", prefix=prefix + \"_orthozer.\")\n if self.xcfamily in [2, 4]:\n params += [prefix + \"grad_basis\"]\n if self.xcfamily == 4:\n params += [prefix + \"lapl_basis\", prefix + \"dvolume\"]\n return params\n else:\n raise KeyError(\"getparamnames has no %s method\" % methodname)\n # TODO: complete this\n" ]
[ [ "torch.device", "torch.tensor" ], [ "torch.mean", "torch.matrix_exp", "torch.zeros", "torch.tensor", "torch.linalg.qr", "torch.triu_indices" ], [ "torch.empty", "torch.zeros", "torch.einsum", "torch.movedim", "torch.linalg.eigh", "torch.matmul", "torch.flip" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
shivin7/pytorch-lightning
[ "9f2b29a7cd4b56c0d6afbbc4a1e0971d49c5f1d7" ]
[ "pytorch_lightning/callbacks/early_stopping.py" ]
[ "r\"\"\"\nEarly Stopping\n^^^^^^^^^^^^^^\n\nMonitor a validation metric and stop training when it stops improving.\n\n\"\"\"\nfrom copy import deepcopy\n\nimport numpy as np\nimport torch\nimport torch.distributed as dist\n\nfrom pytorch_lightning import _logger as log\nfrom pytorch_lightning.callbacks.base import Callback\nfrom pytorch_lightning.utilities import rank_zero_warn\n\ntorch_inf = torch.tensor(np.Inf)\n\ntry:\n import torch_xla\n import torch_xla.core.xla_model as xm\nexcept ImportError:\n XLA_AVAILABLE = False\nelse:\n XLA_AVAILABLE = True\n\n\nclass EarlyStopping(Callback):\n r\"\"\"\n\n Args:\n monitor: quantity to be monitored. Default: ``'val_loss'``.\n .. note:: Has no effect when using `EvalResult` or `TrainResult`\n min_delta: minimum change in the monitored quantity\n to qualify as an improvement, i.e. an absolute\n change of less than `min_delta`, will count as no\n improvement. Default: ``0.0``.\n patience: number of validation epochs with no improvement\n after which training will be stopped. Default: ``3``.\n verbose: verbosity mode. Default: ``False``.\n mode: one of {auto, min, max}. In `min` mode,\n training will stop when the quantity\n monitored has stopped decreasing; in `max`\n mode it will stop when the quantity\n monitored has stopped increasing; in `auto`\n mode, the direction is automatically inferred\n from the name of the monitored quantity. Default: ``'auto'``.\n strict: whether to crash the training if `monitor` is\n not found in the validation metrics. Default: ``True``.\n\n Example::\n\n >>> from pytorch_lightning import Trainer\n >>> from pytorch_lightning.callbacks import EarlyStopping\n >>> early_stopping = EarlyStopping('val_loss')\n >>> trainer = Trainer(early_stop_callback=early_stopping)\n \"\"\"\n mode_dict = {\n 'min': torch.lt,\n 'max': torch.gt,\n }\n\n def __init__(self, monitor: str = 'val_loss', min_delta: float = 0.0, patience: int = 3,\n verbose: bool = False, mode: str = 'auto', strict: bool = True):\n super().__init__()\n self.monitor = monitor\n self.patience = patience\n self.verbose = verbose\n self.strict = strict\n self.min_delta = min_delta\n self.wait_count = 0\n self.stopped_epoch = 0\n self.mode = mode\n\n if mode not in self.mode_dict:\n if self.verbose > 0:\n log.info(f'EarlyStopping mode {mode} is unknown, fallback to auto mode.')\n self.mode = 'auto'\n\n if self.mode == 'auto':\n if self.monitor == 'acc':\n self.mode = 'max'\n else:\n self.mode = 'min'\n if self.verbose > 0:\n log.info(f'EarlyStopping mode set to {self.mode} for monitoring {self.monitor}.')\n\n self.min_delta *= 1 if self.monitor_op == torch.gt else -1\n self.best_score = torch_inf if self.monitor_op == torch.lt else -torch_inf\n\n def _validate_condition_metric(self, logs):\n monitor_val = logs.get(self.monitor)\n error_msg = (f'Early stopping conditioned on metric `{self.monitor}`'\n f' which is not available. Either add `{self.monitor}` to the return of '\n f' validation_epoch end or modify your EarlyStopping callback to use any of the '\n f'following: `{\"`, `\".join(list(logs.keys()))}`')\n\n if monitor_val is None:\n if self.strict:\n raise RuntimeError(error_msg)\n if self.verbose > 0:\n rank_zero_warn(error_msg, RuntimeWarning)\n\n return False\n\n return True\n\n @property\n def monitor_op(self):\n return self.mode_dict[self.mode]\n\n def state_dict(self):\n return {\n 'wait_count': self.wait_count,\n 'stopped_epoch': self.stopped_epoch,\n 'best_score': self.best_score,\n 'patience': self.patience\n }\n\n def load_state_dict(self, state_dict):\n state_dict = deepcopy(state_dict)\n self.wait_count = state_dict['wait_count']\n self.stopped_epoch = state_dict['stopped_epoch']\n self.best_score = state_dict['best_score']\n self.patience = state_dict['patience']\n\n def on_validation_end(self, trainer, pl_module):\n self._run_early_stopping_check(trainer, pl_module)\n\n def on_validation_epoch_end(self, trainer, pl_module):\n val_es_key = 'val_early_stop_on'\n if trainer.callback_metrics.get(val_es_key) is not None:\n self.monitor = val_es_key\n\n # disable strict checking when using structured results\n if val_es_key in trainer.callback_metrics:\n self.strict = False\n\n self._validate_condition_metric(trainer.callback_metrics)\n\n def on_train_epoch_end(self, trainer, pl_module):\n # disable early stopping in train loop when there's a val loop\n if self.monitor == 'val_early_stop_on':\n return\n\n # early stopping can also work in the train loop when there is no val loop and when using structured results\n should_check_early_stop = False\n train_es_key = 'early_stop_on'\n if trainer.callback_metrics.get(train_es_key, None) is not None:\n self.monitor = train_es_key\n should_check_early_stop = True\n\n if should_check_early_stop:\n self._run_early_stopping_check(trainer, pl_module)\n\n def _run_early_stopping_check(self, trainer, pl_module):\n logs = trainer.callback_metrics\n\n if not self._validate_condition_metric(logs):\n return # short circuit if metric not present\n\n current = logs.get(self.monitor)\n\n # when in dev debugging\n trainer.dev_debugger.track_early_stopping_history(current)\n\n if not isinstance(current, torch.Tensor):\n current = torch.tensor(current, device=pl_module.device)\n\n if trainer.use_tpu and XLA_AVAILABLE:\n current = current.cpu()\n\n if self.monitor_op(current - self.min_delta, self.best_score):\n self.best_score = current\n self.wait_count = 0\n else:\n self.wait_count += 1\n should_stop = self.wait_count >= self.patience\n\n if bool(should_stop):\n self.stopped_epoch = trainer.current_epoch\n trainer.should_stop = True\n\n # stop every ddp process if any world process decides to stop\n self._stop_distributed_training(trainer, pl_module)\n\n def _stop_distributed_training(self, trainer, pl_module):\n\n # in ddp make sure all processes stop when one is flagged\n if trainer.use_ddp or trainer.use_ddp2:\n stop = torch.tensor(int(trainer.should_stop), device=pl_module.device)\n dist.all_reduce(stop, op=dist.reduce_op.SUM)\n dist.barrier()\n trainer.should_stop = stop == trainer.world_size\n\n if trainer.use_tpu:\n stop = torch.tensor(int(trainer.should_stop), device=pl_module.device, dtype=torch.int32)\n stop = xm.mesh_reduce(\"stop_signal\", stop, torch.cat)\n torch_xla.core.xla_model.rendezvous(\"pl.EarlyStoppingCallback.stop_distributed_training_check\")\n trainer.should_stop = int(stop.item()) == trainer.world_size\n\n def on_train_end(self, trainer, pl_module):\n if self.stopped_epoch > 0 and self.verbose > 0:\n rank_zero_warn('Displayed epoch numbers by `EarlyStopping` start from \"1\" until v0.6.x,'\n ' but will start from \"0\" in v0.8.0.', DeprecationWarning)\n log.info(f'Epoch {self.stopped_epoch + 1:05d}: early stopping triggered.')\n" ]
[ [ "torch.distributed.all_reduce", "torch.distributed.barrier", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aidanmontare-edu/pandas
[ "41aac9f2bccfc9b20cb2e9d0c839d8b7393e2b08", "41aac9f2bccfc9b20cb2e9d0c839d8b7393e2b08" ]
[ "pandas/core/arrays/period.py", "pandas/core/groupby/base.py" ]
[ "from datetime import timedelta\nimport operator\nfrom typing import Any, Callable, List, Optional, Sequence, Type, Union\n\nimport numpy as np\n\nfrom pandas._libs.tslibs import (\n NaT,\n NaTType,\n Timedelta,\n delta_to_nanoseconds,\n iNaT,\n period as libperiod,\n to_offset,\n)\nfrom pandas._libs.tslibs.dtypes import FreqGroup\nfrom pandas._libs.tslibs.fields import isleapyear_arr\nfrom pandas._libs.tslibs.offsets import Tick, delta_to_tick\nfrom pandas._libs.tslibs.period import (\n DIFFERENT_FREQ,\n IncompatibleFrequency,\n Period,\n PeriodMixin,\n get_period_field_arr,\n period_asfreq_arr,\n)\nfrom pandas._typing import AnyArrayLike\nfrom pandas.util._decorators import cache_readonly\n\nfrom pandas.core.dtypes.common import (\n TD64NS_DTYPE,\n ensure_object,\n is_datetime64_dtype,\n is_float_dtype,\n is_period_dtype,\n pandas_dtype,\n)\nfrom pandas.core.dtypes.dtypes import PeriodDtype\nfrom pandas.core.dtypes.generic import (\n ABCIndexClass,\n ABCPeriodIndex,\n ABCSeries,\n ABCTimedeltaArray,\n)\nfrom pandas.core.dtypes.missing import isna, notna\n\nimport pandas.core.algorithms as algos\nfrom pandas.core.arrays import datetimelike as dtl\nimport pandas.core.common as com\n\nfrom pandas.tseries.offsets import DateOffset\n\n\ndef _field_accessor(name: str, docstring=None):\n def f(self):\n base = self.freq._period_dtype_code\n result = get_period_field_arr(name, self.asi8, base)\n return result\n\n f.__name__ = name\n f.__doc__ = docstring\n return property(f)\n\n\nclass PeriodArray(PeriodMixin, dtl.DatetimeLikeArrayMixin, dtl.DatelikeOps):\n \"\"\"\n Pandas ExtensionArray for storing Period data.\n\n Users should use :func:`period_array` to create new instances.\n\n Parameters\n ----------\n values : Union[PeriodArray, Series[period], ndarray[int], PeriodIndex]\n The data to store. These should be arrays that can be directly\n converted to ordinals without inference or copy (PeriodArray,\n ndarray[int64]), or a box around such an array (Series[period],\n PeriodIndex).\n freq : str or DateOffset\n The `freq` to use for the array. Mostly applicable when `values`\n is an ndarray of integers, when `freq` is required. When `values`\n is a PeriodArray (or box around), it's checked that ``values.freq``\n matches `freq`.\n dtype : PeriodDtype, optional\n A PeriodDtype instance from which to extract a `freq`. If both\n `freq` and `dtype` are specified, then the frequencies must match.\n copy : bool, default False\n Whether to copy the ordinals before storing.\n\n Attributes\n ----------\n None\n\n Methods\n -------\n None\n\n See Also\n --------\n period_array : Create a new PeriodArray.\n PeriodIndex : Immutable Index for period data.\n\n Notes\n -----\n There are two components to a PeriodArray\n\n - ordinals : integer ndarray\n - freq : pd.tseries.offsets.Offset\n\n The values are physically stored as a 1-D ndarray of integers. These are\n called \"ordinals\" and represent some kind of offset from a base.\n\n The `freq` indicates the span covered by each element of the array.\n All elements in the PeriodArray have the same `freq`.\n \"\"\"\n\n # array priority higher than numpy scalars\n __array_priority__ = 1000\n _typ = \"periodarray\" # ABCPeriodArray\n _scalar_type = Period\n _recognized_scalars = (Period,)\n _is_recognized_dtype = is_period_dtype\n\n # Names others delegate to us\n _other_ops: List[str] = []\n _bool_ops = [\"is_leap_year\"]\n _object_ops = [\"start_time\", \"end_time\", \"freq\"]\n _field_ops = [\n \"year\",\n \"month\",\n \"day\",\n \"hour\",\n \"minute\",\n \"second\",\n \"weekofyear\",\n \"weekday\",\n \"week\",\n \"dayofweek\",\n \"dayofyear\",\n \"quarter\",\n \"qyear\",\n \"days_in_month\",\n \"daysinmonth\",\n ]\n _datetimelike_ops = _field_ops + _object_ops + _bool_ops\n _datetimelike_methods = [\"strftime\", \"to_timestamp\", \"asfreq\"]\n\n # --------------------------------------------------------------------\n # Constructors\n\n def __init__(self, values, freq=None, dtype=None, copy=False):\n freq = validate_dtype_freq(dtype, freq)\n\n if freq is not None:\n freq = Period._maybe_convert_freq(freq)\n\n if isinstance(values, ABCSeries):\n values = values._values\n if not isinstance(values, type(self)):\n raise TypeError(\"Incorrect dtype\")\n\n elif isinstance(values, ABCPeriodIndex):\n values = values._values\n\n if isinstance(values, type(self)):\n if freq is not None and freq != values.freq:\n raise raise_on_incompatible(values, freq)\n values, freq = values._data, values.freq\n\n values = np.array(values, dtype=\"int64\", copy=copy)\n self._data = values\n if freq is None:\n raise ValueError(\"freq is not specified and cannot be inferred\")\n self._dtype = PeriodDtype(freq)\n\n @classmethod\n def _simple_new(cls, values: np.ndarray, freq=None, **kwargs) -> \"PeriodArray\":\n # alias for PeriodArray.__init__\n assertion_msg = \"Should be numpy array of type i8\"\n assert isinstance(values, np.ndarray) and values.dtype == \"i8\", assertion_msg\n return cls(values, freq=freq, **kwargs)\n\n @classmethod\n def _from_sequence(\n cls: Type[\"PeriodArray\"],\n scalars: Union[Sequence[Optional[Period]], AnyArrayLike],\n dtype: Optional[PeriodDtype] = None,\n copy: bool = False,\n ) -> \"PeriodArray\":\n if dtype:\n freq = dtype.freq\n else:\n freq = None\n\n if isinstance(scalars, cls):\n validate_dtype_freq(scalars.dtype, freq)\n if copy:\n scalars = scalars.copy()\n return scalars\n\n periods = np.asarray(scalars, dtype=object)\n if copy:\n periods = periods.copy()\n\n freq = freq or libperiod.extract_freq(periods)\n ordinals = libperiod.extract_ordinals(periods, freq)\n return cls(ordinals, freq=freq)\n\n @classmethod\n def _from_sequence_of_strings(\n cls, strings, dtype=None, copy=False\n ) -> \"PeriodArray\":\n return cls._from_sequence(strings, dtype, copy)\n\n @classmethod\n def _from_datetime64(cls, data, freq, tz=None) -> \"PeriodArray\":\n \"\"\"\n Construct a PeriodArray from a datetime64 array\n\n Parameters\n ----------\n data : ndarray[datetime64[ns], datetime64[ns, tz]]\n freq : str or Tick\n tz : tzinfo, optional\n\n Returns\n -------\n PeriodArray[freq]\n \"\"\"\n data, freq = dt64arr_to_periodarr(data, freq, tz)\n return cls(data, freq=freq)\n\n @classmethod\n def _generate_range(cls, start, end, periods, freq, fields):\n periods = dtl.validate_periods(periods)\n\n if freq is not None:\n freq = Period._maybe_convert_freq(freq)\n\n field_count = len(fields)\n if start is not None or end is not None:\n if field_count > 0:\n raise ValueError(\n \"Can either instantiate from fields or endpoints, but not both\"\n )\n subarr, freq = _get_ordinal_range(start, end, periods, freq)\n elif field_count > 0:\n subarr, freq = _range_from_fields(freq=freq, **fields)\n else:\n raise ValueError(\"Not enough parameters to construct Period range\")\n\n return subarr, freq\n\n # -----------------------------------------------------------------\n # DatetimeLike Interface\n\n def _unbox_scalar(self, value: Union[Period, NaTType]) -> int:\n if value is NaT:\n return value.value\n elif isinstance(value, self._scalar_type):\n self._check_compatible_with(value)\n return value.ordinal\n else:\n raise ValueError(f\"'value' should be a Period. Got '{value}' instead.\")\n\n def _scalar_from_string(self, value: str) -> Period:\n return Period(value, freq=self.freq)\n\n def _check_compatible_with(self, other, setitem: bool = False):\n if other is NaT:\n return\n if self.freqstr != other.freqstr:\n raise raise_on_incompatible(self, other)\n\n # --------------------------------------------------------------------\n # Data / Attributes\n\n @cache_readonly\n def dtype(self) -> PeriodDtype:\n return self._dtype\n\n # error: Read-only property cannot override read-write property [misc]\n @property # type: ignore\n def freq(self) -> DateOffset:\n \"\"\"\n Return the frequency object for this PeriodArray.\n \"\"\"\n return self.dtype.freq\n\n def __array__(self, dtype=None) -> np.ndarray:\n if dtype == \"i8\":\n return self.asi8\n elif dtype == bool:\n return ~self._isnan\n\n # This will raise TypeError for non-object dtypes\n return np.array(list(self), dtype=object)\n\n def __arrow_array__(self, type=None):\n \"\"\"\n Convert myself into a pyarrow Array.\n \"\"\"\n import pyarrow\n from pandas.core.arrays._arrow_utils import ArrowPeriodType\n\n if type is not None:\n if pyarrow.types.is_integer(type):\n return pyarrow.array(self._data, mask=self.isna(), type=type)\n elif isinstance(type, ArrowPeriodType):\n # ensure we have the same freq\n if self.freqstr != type.freq:\n raise TypeError(\n \"Not supported to convert PeriodArray to array with different \"\n f\"'freq' ({self.freqstr} vs {type.freq})\"\n )\n else:\n raise TypeError(\n f\"Not supported to convert PeriodArray to '{type}' type\"\n )\n\n period_type = ArrowPeriodType(self.freqstr)\n storage_array = pyarrow.array(self._data, mask=self.isna(), type=\"int64\")\n return pyarrow.ExtensionArray.from_storage(period_type, storage_array)\n\n # --------------------------------------------------------------------\n # Vectorized analogues of Period properties\n\n year = _field_accessor(\n \"year\",\n \"\"\"\n The year of the period.\n \"\"\",\n )\n month = _field_accessor(\n \"month\",\n \"\"\"\n The month as January=1, December=12.\n \"\"\",\n )\n day = _field_accessor(\n \"day\",\n \"\"\"\n The days of the period.\n \"\"\",\n )\n hour = _field_accessor(\n \"hour\",\n \"\"\"\n The hour of the period.\n \"\"\",\n )\n minute = _field_accessor(\n \"minute\",\n \"\"\"\n The minute of the period.\n \"\"\",\n )\n second = _field_accessor(\n \"second\",\n \"\"\"\n The second of the period.\n \"\"\",\n )\n weekofyear = _field_accessor(\n \"week\",\n \"\"\"\n The week ordinal of the year.\n \"\"\",\n )\n week = weekofyear\n dayofweek = _field_accessor(\n \"weekday\",\n \"\"\"\n The day of the week with Monday=0, Sunday=6.\n \"\"\",\n )\n weekday = dayofweek\n dayofyear = day_of_year = _field_accessor(\n \"day_of_year\",\n \"\"\"\n The ordinal day of the year.\n \"\"\",\n )\n quarter = _field_accessor(\n \"quarter\",\n \"\"\"\n The quarter of the date.\n \"\"\",\n )\n qyear = _field_accessor(\"qyear\")\n days_in_month = _field_accessor(\n \"days_in_month\",\n \"\"\"\n The number of days in the month.\n \"\"\",\n )\n daysinmonth = days_in_month\n\n @property\n def is_leap_year(self) -> np.ndarray:\n \"\"\"\n Logical indicating if the date belongs to a leap year.\n \"\"\"\n return isleapyear_arr(np.asarray(self.year))\n\n @property\n def start_time(self):\n return self.to_timestamp(how=\"start\")\n\n @property\n def end_time(self):\n return self.to_timestamp(how=\"end\")\n\n def to_timestamp(self, freq=None, how=\"start\"):\n \"\"\"\n Cast to DatetimeArray/Index.\n\n Parameters\n ----------\n freq : str or DateOffset, optional\n Target frequency. The default is 'D' for week or longer,\n 'S' otherwise.\n how : {'s', 'e', 'start', 'end'}\n Whether to use the start or end of the time period being converted.\n\n Returns\n -------\n DatetimeArray/Index\n \"\"\"\n from pandas.core.arrays import DatetimeArray\n\n how = libperiod.validate_end_alias(how)\n\n end = how == \"E\"\n if end:\n if freq == \"B\" or self.freq == \"B\":\n # roll forward to ensure we land on B date\n adjust = Timedelta(1, \"D\") - Timedelta(1, \"ns\")\n return self.to_timestamp(how=\"start\") + adjust\n else:\n adjust = Timedelta(1, \"ns\")\n return (self + self.freq).to_timestamp(how=\"start\") - adjust\n\n if freq is None:\n freq = self._get_to_timestamp_base()\n base = freq\n else:\n freq = Period._maybe_convert_freq(freq)\n base = freq._period_dtype_code\n\n new_data = self.asfreq(freq, how=how)\n\n new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base)\n return DatetimeArray(new_data)._with_freq(\"infer\")\n\n # --------------------------------------------------------------------\n\n def _time_shift(self, periods, freq=None):\n \"\"\"\n Shift each value by `periods`.\n\n Note this is different from ExtensionArray.shift, which\n shifts the *position* of each element, padding the end with\n missing values.\n\n Parameters\n ----------\n periods : int\n Number of periods to shift by.\n freq : pandas.DateOffset, pandas.Timedelta, or str\n Frequency increment to shift by.\n \"\"\"\n if freq is not None:\n raise TypeError(\n \"`freq` argument is not supported for \"\n f\"{type(self).__name__}._time_shift\"\n )\n values = self.asi8 + periods * self.freq.n\n if self._hasnans:\n values[self._isnan] = iNaT\n return type(self)(values, freq=self.freq)\n\n @property\n def _box_func(self):\n return lambda x: Period._from_ordinal(ordinal=x, freq=self.freq)\n\n def asfreq(self, freq=None, how: str = \"E\") -> \"PeriodArray\":\n \"\"\"\n Convert the Period Array/Index to the specified frequency `freq`.\n\n Parameters\n ----------\n freq : str\n A frequency.\n how : str {'E', 'S'}\n Whether the elements should be aligned to the end\n or start within pa period.\n\n * 'E', 'END', or 'FINISH' for end,\n * 'S', 'START', or 'BEGIN' for start.\n\n January 31st ('END') vs. January 1st ('START') for example.\n\n Returns\n -------\n Period Array/Index\n Constructed with the new frequency.\n\n Examples\n --------\n >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='A')\n >>> pidx\n PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'],\n dtype='period[A-DEC]', freq='A-DEC')\n\n >>> pidx.asfreq('M')\n PeriodIndex(['2010-12', '2011-12', '2012-12', '2013-12', '2014-12',\n '2015-12'], dtype='period[M]', freq='M')\n\n >>> pidx.asfreq('M', how='S')\n PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01',\n '2015-01'], dtype='period[M]', freq='M')\n \"\"\"\n how = libperiod.validate_end_alias(how)\n\n freq = Period._maybe_convert_freq(freq)\n\n base1 = self.freq._period_dtype_code\n base2 = freq._period_dtype_code\n\n asi8 = self.asi8\n # self.freq.n can't be negative or 0\n end = how == \"E\"\n if end:\n ordinal = asi8 + self.freq.n - 1\n else:\n ordinal = asi8\n\n new_data = period_asfreq_arr(ordinal, base1, base2, end)\n\n if self._hasnans:\n new_data[self._isnan] = iNaT\n\n return type(self)(new_data, freq=freq)\n\n # ------------------------------------------------------------------\n # Rendering Methods\n\n def _formatter(self, boxed: bool = False):\n if boxed:\n return str\n return \"'{}'\".format\n\n def _format_native_types(self, na_rep=\"NaT\", date_format=None, **kwargs):\n \"\"\"\n actually format my specific types\n \"\"\"\n values = self.astype(object)\n\n if date_format:\n formatter = lambda dt: dt.strftime(date_format)\n else:\n formatter = lambda dt: str(dt)\n\n if self._hasnans:\n mask = self._isnan\n values[mask] = na_rep\n imask = ~mask\n values[imask] = np.array([formatter(dt) for dt in values[imask]])\n else:\n values = np.array([formatter(dt) for dt in values])\n return values\n\n # ------------------------------------------------------------------\n\n def astype(self, dtype, copy: bool = True):\n # We handle Period[T] -> Period[U]\n # Our parent handles everything else.\n dtype = pandas_dtype(dtype)\n\n if is_period_dtype(dtype):\n return self.asfreq(dtype.freq)\n return super().astype(dtype, copy=copy)\n\n # ------------------------------------------------------------------\n # Arithmetic Methods\n\n def _sub_datelike(self, other):\n assert other is not NaT\n return NotImplemented\n\n def _sub_period(self, other):\n # If the operation is well-defined, we return an object-Index\n # of DateOffsets. Null entries are filled with pd.NaT\n self._check_compatible_with(other)\n asi8 = self.asi8\n new_data = asi8 - other.ordinal\n new_data = np.array([self.freq * x for x in new_data])\n\n if self._hasnans:\n new_data[self._isnan] = NaT\n\n return new_data\n\n def _sub_period_array(self, other):\n \"\"\"\n Subtract a Period Array/Index from self. This is only valid if self\n is itself a Period Array/Index, raises otherwise. Both objects must\n have the same frequency.\n\n Parameters\n ----------\n other : PeriodIndex or PeriodArray\n\n Returns\n -------\n result : np.ndarray[object]\n Array of DateOffset objects; nulls represented by NaT.\n \"\"\"\n if self.freq != other.freq:\n msg = DIFFERENT_FREQ.format(\n cls=type(self).__name__, own_freq=self.freqstr, other_freq=other.freqstr\n )\n raise IncompatibleFrequency(msg)\n\n new_values = algos.checked_add_with_arr(\n self.asi8, -other.asi8, arr_mask=self._isnan, b_mask=other._isnan\n )\n\n new_values = np.array([self.freq.base * x for x in new_values])\n if self._hasnans or other._hasnans:\n mask = (self._isnan) | (other._isnan)\n new_values[mask] = NaT\n return new_values\n\n def _addsub_int_array(\n self, other: np.ndarray, op: Callable[[Any, Any], Any],\n ) -> \"PeriodArray\":\n \"\"\"\n Add or subtract array of integers; equivalent to applying\n `_time_shift` pointwise.\n\n Parameters\n ----------\n other : np.ndarray[integer-dtype]\n op : {operator.add, operator.sub}\n\n Returns\n -------\n result : PeriodArray\n \"\"\"\n assert op in [operator.add, operator.sub]\n if op is operator.sub:\n other = -other\n res_values = algos.checked_add_with_arr(self.asi8, other, arr_mask=self._isnan)\n res_values = res_values.view(\"i8\")\n res_values[self._isnan] = iNaT\n return type(self)(res_values, freq=self.freq)\n\n def _add_offset(self, other: DateOffset):\n assert not isinstance(other, Tick)\n\n if other.base != self.freq.base:\n raise raise_on_incompatible(self, other)\n\n # Note: when calling parent class's _add_timedeltalike_scalar,\n # it will call delta_to_nanoseconds(delta). Because delta here\n # is an integer, delta_to_nanoseconds will return it unchanged.\n result = super()._add_timedeltalike_scalar(other.n)\n return type(self)(result, freq=self.freq)\n\n def _add_timedeltalike_scalar(self, other):\n \"\"\"\n Parameters\n ----------\n other : timedelta, Tick, np.timedelta64\n\n Returns\n -------\n PeriodArray\n \"\"\"\n if not isinstance(self.freq, Tick):\n # We cannot add timedelta-like to non-tick PeriodArray\n raise raise_on_incompatible(self, other)\n\n if notna(other):\n # special handling for np.timedelta64(\"NaT\"), avoid calling\n # _check_timedeltalike_freq_compat as that would raise TypeError\n other = self._check_timedeltalike_freq_compat(other)\n\n # Note: when calling parent class's _add_timedeltalike_scalar,\n # it will call delta_to_nanoseconds(delta). Because delta here\n # is an integer, delta_to_nanoseconds will return it unchanged.\n return super()._add_timedeltalike_scalar(other)\n\n def _add_timedelta_arraylike(self, other):\n \"\"\"\n Parameters\n ----------\n other : TimedeltaArray or ndarray[timedelta64]\n\n Returns\n -------\n result : ndarray[int64]\n \"\"\"\n if not isinstance(self.freq, Tick):\n # We cannot add timedelta-like to non-tick PeriodArray\n raise TypeError(\n f\"Cannot add or subtract timedelta64[ns] dtype from {self.dtype}\"\n )\n\n if not np.all(isna(other)):\n delta = self._check_timedeltalike_freq_compat(other)\n else:\n # all-NaT TimedeltaIndex is equivalent to a single scalar td64 NaT\n return self + np.timedelta64(\"NaT\")\n\n ordinals = self._addsub_int_array(delta, operator.add).asi8\n return type(self)(ordinals, dtype=self.dtype)\n\n def _check_timedeltalike_freq_compat(self, other):\n \"\"\"\n Arithmetic operations with timedelta-like scalars or array `other`\n are only valid if `other` is an integer multiple of `self.freq`.\n If the operation is valid, find that integer multiple. Otherwise,\n raise because the operation is invalid.\n\n Parameters\n ----------\n other : timedelta, np.timedelta64, Tick,\n ndarray[timedelta64], TimedeltaArray, TimedeltaIndex\n\n Returns\n -------\n multiple : int or ndarray[int64]\n\n Raises\n ------\n IncompatibleFrequency\n \"\"\"\n assert isinstance(self.freq, Tick) # checked by calling function\n base_nanos = self.freq.base.nanos\n\n if isinstance(other, (timedelta, np.timedelta64, Tick)):\n nanos = delta_to_nanoseconds(other)\n\n elif isinstance(other, np.ndarray):\n # numpy timedelta64 array; all entries must be compatible\n assert other.dtype.kind == \"m\"\n if other.dtype != TD64NS_DTYPE:\n # i.e. non-nano unit\n # TODO: disallow unit-less timedelta64\n other = other.astype(TD64NS_DTYPE)\n nanos = other.view(\"i8\")\n else:\n # TimedeltaArray/Index\n nanos = other.asi8\n\n if np.all(nanos % base_nanos == 0):\n # nanos being added is an integer multiple of the\n # base-frequency to self.freq\n delta = nanos // base_nanos\n # delta is the integer (or integer-array) number of periods\n # by which will be added to self.\n return delta\n\n raise raise_on_incompatible(self, other)\n\n\ndef raise_on_incompatible(left, right):\n \"\"\"\n Helper function to render a consistent error message when raising\n IncompatibleFrequency.\n\n Parameters\n ----------\n left : PeriodArray\n right : None, DateOffset, Period, ndarray, or timedelta-like\n\n Returns\n -------\n IncompatibleFrequency\n Exception to be raised by the caller.\n \"\"\"\n # GH#24283 error message format depends on whether right is scalar\n if isinstance(right, (np.ndarray, ABCTimedeltaArray)) or right is None:\n other_freq = None\n elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period, DateOffset)):\n other_freq = right.freqstr\n else:\n other_freq = delta_to_tick(Timedelta(right)).freqstr\n\n msg = DIFFERENT_FREQ.format(\n cls=type(left).__name__, own_freq=left.freqstr, other_freq=other_freq\n )\n return IncompatibleFrequency(msg)\n\n\n# -------------------------------------------------------------------\n# Constructor Helpers\n\n\ndef period_array(\n data: Union[Sequence[Optional[Period]], AnyArrayLike],\n freq: Optional[Union[str, Tick]] = None,\n copy: bool = False,\n) -> PeriodArray:\n \"\"\"\n Construct a new PeriodArray from a sequence of Period scalars.\n\n Parameters\n ----------\n data : Sequence of Period objects\n A sequence of Period objects. These are required to all have\n the same ``freq.`` Missing values can be indicated by ``None``\n or ``pandas.NaT``.\n freq : str, Tick, or Offset\n The frequency of every element of the array. This can be specified\n to avoid inferring the `freq` from `data`.\n copy : bool, default False\n Whether to ensure a copy of the data is made.\n\n Returns\n -------\n PeriodArray\n\n See Also\n --------\n PeriodArray\n pandas.PeriodIndex\n\n Examples\n --------\n >>> period_array([pd.Period('2017', freq='A'),\n ... pd.Period('2018', freq='A')])\n <PeriodArray>\n ['2017', '2018']\n Length: 2, dtype: period[A-DEC]\n\n >>> period_array([pd.Period('2017', freq='A'),\n ... pd.Period('2018', freq='A'),\n ... pd.NaT])\n <PeriodArray>\n ['2017', '2018', 'NaT']\n Length: 3, dtype: period[A-DEC]\n\n Integers that look like years are handled\n\n >>> period_array([2000, 2001, 2002], freq='D')\n <PeriodArray>\n ['2000-01-01', '2001-01-01', '2002-01-01']\n Length: 3, dtype: period[D]\n\n Datetime-like strings may also be passed\n\n >>> period_array(['2000-Q1', '2000-Q2', '2000-Q3', '2000-Q4'], freq='Q')\n <PeriodArray>\n ['2000Q1', '2000Q2', '2000Q3', '2000Q4']\n Length: 4, dtype: period[Q-DEC]\n \"\"\"\n data_dtype = getattr(data, \"dtype\", None)\n\n if is_datetime64_dtype(data_dtype):\n return PeriodArray._from_datetime64(data, freq)\n if is_period_dtype(data_dtype):\n return PeriodArray(data, freq)\n\n # other iterable of some kind\n if not isinstance(data, (np.ndarray, list, tuple, ABCSeries)):\n data = list(data)\n\n data = np.asarray(data)\n\n dtype: Optional[PeriodDtype]\n if freq:\n dtype = PeriodDtype(freq)\n else:\n dtype = None\n\n if is_float_dtype(data) and len(data) > 0:\n raise TypeError(\"PeriodIndex does not allow floating point in construction\")\n\n data = ensure_object(data)\n\n return PeriodArray._from_sequence(data, dtype=dtype)\n\n\ndef validate_dtype_freq(dtype, freq):\n \"\"\"\n If both a dtype and a freq are available, ensure they match. If only\n dtype is available, extract the implied freq.\n\n Parameters\n ----------\n dtype : dtype\n freq : DateOffset or None\n\n Returns\n -------\n freq : DateOffset\n\n Raises\n ------\n ValueError : non-period dtype\n IncompatibleFrequency : mismatch between dtype and freq\n \"\"\"\n if freq is not None:\n freq = to_offset(freq)\n\n if dtype is not None:\n dtype = pandas_dtype(dtype)\n if not is_period_dtype(dtype):\n raise ValueError(\"dtype must be PeriodDtype\")\n if freq is None:\n freq = dtype.freq\n elif freq != dtype.freq:\n raise IncompatibleFrequency(\"specified freq and dtype are different\")\n return freq\n\n\ndef dt64arr_to_periodarr(data, freq, tz=None):\n \"\"\"\n Convert an datetime-like array to values Period ordinals.\n\n Parameters\n ----------\n data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]\n freq : Optional[Union[str, Tick]]\n Must match the `freq` on the `data` if `data` is a DatetimeIndex\n or Series.\n tz : Optional[tzinfo]\n\n Returns\n -------\n ordinals : ndarray[int]\n freq : Tick\n The frequency extracted from the Series or DatetimeIndex if that's\n used.\n\n \"\"\"\n if data.dtype != np.dtype(\"M8[ns]\"):\n raise ValueError(f\"Wrong dtype: {data.dtype}\")\n\n if freq is None:\n if isinstance(data, ABCIndexClass):\n data, freq = data._values, data.freq\n elif isinstance(data, ABCSeries):\n data, freq = data._values, data.dt.freq\n\n freq = Period._maybe_convert_freq(freq)\n\n if isinstance(data, (ABCIndexClass, ABCSeries)):\n data = data._values\n\n base = freq._period_dtype_code\n return libperiod.dt64arr_to_periodarr(data.view(\"i8\"), base, tz), freq\n\n\ndef _get_ordinal_range(start, end, periods, freq, mult=1):\n if com.count_not_none(start, end, periods) != 2:\n raise ValueError(\n \"Of the three parameters: start, end, and periods, \"\n \"exactly two must be specified\"\n )\n\n if freq is not None:\n freq = to_offset(freq)\n mult = freq.n\n\n if start is not None:\n start = Period(start, freq)\n if end is not None:\n end = Period(end, freq)\n\n is_start_per = isinstance(start, Period)\n is_end_per = isinstance(end, Period)\n\n if is_start_per and is_end_per and start.freq != end.freq:\n raise ValueError(\"start and end must have same freq\")\n if start is NaT or end is NaT:\n raise ValueError(\"start and end must not be NaT\")\n\n if freq is None:\n if is_start_per:\n freq = start.freq\n elif is_end_per:\n freq = end.freq\n else: # pragma: no cover\n raise ValueError(\"Could not infer freq from start/end\")\n\n if periods is not None:\n periods = periods * mult\n if start is None:\n data = np.arange(\n end.ordinal - periods + mult, end.ordinal + 1, mult, dtype=np.int64\n )\n else:\n data = np.arange(\n start.ordinal, start.ordinal + periods, mult, dtype=np.int64\n )\n else:\n data = np.arange(start.ordinal, end.ordinal + 1, mult, dtype=np.int64)\n\n return data, freq\n\n\ndef _range_from_fields(\n year=None,\n month=None,\n quarter=None,\n day=None,\n hour=None,\n minute=None,\n second=None,\n freq=None,\n):\n if hour is None:\n hour = 0\n if minute is None:\n minute = 0\n if second is None:\n second = 0\n if day is None:\n day = 1\n\n ordinals = []\n\n if quarter is not None:\n if freq is None:\n freq = to_offset(\"Q\")\n base = FreqGroup.FR_QTR\n else:\n freq = to_offset(freq)\n base = libperiod.freq_to_dtype_code(freq)\n if base != FreqGroup.FR_QTR:\n raise AssertionError(\"base must equal FR_QTR\")\n\n year, quarter = _make_field_arrays(year, quarter)\n for y, q in zip(year, quarter):\n y, m = libperiod.quarter_to_myear(y, q, freq)\n val = libperiod.period_ordinal(y, m, 1, 1, 1, 1, 0, 0, base)\n ordinals.append(val)\n else:\n freq = to_offset(freq)\n base = libperiod.freq_to_dtype_code(freq)\n arrays = _make_field_arrays(year, month, day, hour, minute, second)\n for y, mth, d, h, mn, s in zip(*arrays):\n ordinals.append(libperiod.period_ordinal(y, mth, d, h, mn, s, 0, 0, base))\n\n return np.array(ordinals, dtype=np.int64), freq\n\n\ndef _make_field_arrays(*fields):\n length = None\n for x in fields:\n if isinstance(x, (list, np.ndarray, ABCSeries)):\n if length is not None and len(x) != length:\n raise ValueError(\"Mismatched Period array lengths\")\n elif length is None:\n length = len(x)\n\n arrays = [\n np.asarray(x)\n if isinstance(x, (np.ndarray, list, ABCSeries))\n else np.repeat(x, length)\n for x in fields\n ]\n\n return arrays\n", "\"\"\"\nProvide basic components for groupby. These definitions\nhold the whitelist of methods that are exposed on the\nSeriesGroupBy and the DataFrameGroupBy objects.\n\"\"\"\nimport collections\n\nfrom pandas.core.dtypes.common import is_list_like, is_scalar\n\nOutputKey = collections.namedtuple(\"OutputKey\", [\"label\", \"position\"])\n\n\nclass GroupByMixin:\n \"\"\"\n Provide the groupby facilities to the mixed object.\n \"\"\"\n\n def _gotitem(self, key, ndim, subset=None):\n \"\"\"\n Sub-classes to define. Return a sliced object.\n\n Parameters\n ----------\n key : string / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on\n \"\"\"\n # create a new object to prevent aliasing\n if subset is None:\n subset = self.obj\n\n # we need to make a shallow copy of ourselves\n # with the same groupby\n kwargs = {attr: getattr(self, attr) for attr in self._attributes}\n\n # Try to select from a DataFrame, falling back to a Series\n try:\n groupby = self._groupby[key]\n except IndexError:\n groupby = self._groupby\n\n self = type(self)(subset, groupby=groupby, parent=self, **kwargs)\n self._reset_cache()\n if subset.ndim == 2:\n if is_scalar(key) and key in subset or is_list_like(key):\n self._selection = key\n return self\n\n\n# special case to prevent duplicate plots when catching exceptions when\n# forwarding methods from NDFrames\nplotting_methods = frozenset([\"plot\", \"hist\"])\n\ncommon_apply_whitelist = (\n frozenset(\n [\n \"quantile\",\n \"fillna\",\n \"mad\",\n \"take\",\n \"idxmax\",\n \"idxmin\",\n \"tshift\",\n \"skew\",\n \"corr\",\n \"cov\",\n \"diff\",\n ]\n )\n | plotting_methods\n)\n\nseries_apply_whitelist = (\n (\n common_apply_whitelist\n | {\n \"nlargest\",\n \"nsmallest\",\n \"is_monotonic_increasing\",\n \"is_monotonic_decreasing\",\n }\n )\n) | frozenset([\"dtype\", \"unique\"])\n\ndataframe_apply_whitelist = common_apply_whitelist | frozenset([\"dtypes\", \"corrwith\"])\n\n# cythonized transformations or canned \"agg+broadcast\", which do not\n# require postprocessing of the result by transform.\ncythonized_kernels = frozenset([\"cumprod\", \"cumsum\", \"shift\", \"cummin\", \"cummax\"])\n\ncython_cast_blacklist = frozenset([\"rank\", \"count\", \"size\", \"idxmin\", \"idxmax\"])\n\n# List of aggregation/reduction functions.\n# These map each group to a single numeric value\nreduction_kernels = frozenset(\n [\n \"all\",\n \"any\",\n \"corrwith\",\n \"count\",\n \"first\",\n \"idxmax\",\n \"idxmin\",\n \"last\",\n \"mad\",\n \"max\",\n \"mean\",\n \"median\",\n \"min\",\n \"ngroup\",\n \"nth\",\n \"nunique\",\n \"prod\",\n # as long as `quantile`'s signature accepts only\n # a single quantile value, it's a reduction.\n # GH#27526 might change that.\n \"quantile\",\n \"sem\",\n \"size\",\n \"skew\",\n \"std\",\n \"sum\",\n \"var\",\n ]\n)\n\n# List of transformation functions.\n# a transformation is a function that, for each group,\n# produces a result that has the same shape as the group.\ntransformation_kernels = frozenset(\n [\n \"backfill\",\n \"bfill\",\n \"cumcount\",\n \"cummax\",\n \"cummin\",\n \"cumprod\",\n \"cumsum\",\n \"diff\",\n \"ffill\",\n \"fillna\",\n \"pad\",\n \"pct_change\",\n \"rank\",\n \"shift\",\n \"tshift\",\n ]\n)\n\n# these are all the public methods on Grouper which don't belong\n# in either of the above lists\ngroupby_other_methods = frozenset(\n [\n \"agg\",\n \"aggregate\",\n \"apply\",\n \"boxplot\",\n # corr and cov return ngroups*ncolumns rows, so they\n # are neither a transformation nor a reduction\n \"corr\",\n \"cov\",\n \"describe\",\n \"dtypes\",\n \"expanding\",\n \"filter\",\n \"get_group\",\n \"groups\",\n \"head\",\n \"hist\",\n \"indices\",\n \"ndim\",\n \"ngroups\",\n \"ohlc\",\n \"pipe\",\n \"plot\",\n \"resample\",\n \"rolling\",\n \"tail\",\n \"take\",\n \"transform\",\n \"sample\",\n ]\n)\n# Valid values of `name` for `groupby.transform(name)`\n# NOTE: do NOT edit this directly. New additions should be inserted\n# into the appropriate list above.\ntransform_kernel_whitelist = reduction_kernels | transformation_kernels\n" ]
[ [ "numpy.asarray", "pandas.core.arrays._arrow_utils.ArrowPeriodType", "pandas.core.dtypes.missing.notna", "numpy.dtype", "numpy.all", "pandas.core.dtypes.common.is_datetime64_dtype", "pandas._libs.tslibs.period.IncompatibleFrequency", "pandas.core.dtypes.common.ensure_object", "pandas._libs.tslibs.period.freq_to_dtype_code", "pandas._libs.tslibs.to_offset", "pandas._libs.tslibs.period.Period._from_ordinal", "numpy.arange", "pandas._libs.tslibs.period.get_period_field_arr", "pandas._libs.tslibs.period.periodarr_to_dt64arr", "pandas.core.dtypes.common.is_float_dtype", "numpy.repeat", "pandas._libs.tslibs.period.extract_freq", "pandas._libs.tslibs.period.Period._maybe_convert_freq", "pandas._libs.tslibs.delta_to_nanoseconds", "pandas.core.dtypes.common.pandas_dtype", "pandas.core.algorithms.checked_add_with_arr", "pandas.core.dtypes.common.is_period_dtype", "pandas._libs.tslibs.period.Period", "pandas.core.arrays.DatetimeArray", "numpy.timedelta64", "pandas.core.dtypes.dtypes.PeriodDtype", "numpy.array", "pandas.core.common.count_not_none", "pandas._libs.tslibs.Timedelta", "pandas._libs.tslibs.period.validate_end_alias", "pandas._libs.tslibs.period.period_asfreq_arr", "pandas._libs.tslibs.period.quarter_to_myear", "pandas.core.dtypes.missing.isna", "pandas._libs.tslibs.period.period_ordinal", "pandas._libs.tslibs.period.extract_ordinals", "pandas.core.arrays.datetimelike.validate_periods" ], [ "pandas.core.dtypes.common.is_list_like", "pandas.core.dtypes.common.is_scalar" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "0.24", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cristi161/eecvf
[ "519c488bd47f697ef51e88823f7a751a52677b88", "519c488bd47f697ef51e88823f7a751a52677b88" ]
[ "Benchmarking/bsds500/bsds/thin.py", "Application/Jobs/kernel_convolution.py" ]
[ "import numpy as np\n\n# Thinning morphological operation applied using lookup tables.\n# We convert the 3x3 neighbourhood surrounding a pixel to an index\n# used to lookup the output in a lookup table.\n\n# Bit masks for each neighbour\n# 1 2 4\n# 8 16 32\n# 64 128 256\nNEIGH_MASK_EAST = 32\nNEIGH_MASK_NORTH_EAST = 4\nNEIGH_MASK_NORTH = 2\nNEIGH_MASK_NORTH_WEST = 1\nNEIGH_MASK_WEST = 8\nNEIGH_MASK_SOUTH_WEST = 64\nNEIGH_MASK_SOUTH = 128\nNEIGH_MASK_SOUTH_EAST = 256\nNEIGH_MASK_CENTRE = 16\n\n# Masks in a list\n# MASKS[0] = centre\n# MASKS[1..8] = start from east, counter-clockwise\nMASKS = [NEIGH_MASK_CENTRE,\n NEIGH_MASK_EAST, NEIGH_MASK_NORTH_EAST, NEIGH_MASK_NORTH, NEIGH_MASK_NORTH_WEST,\n NEIGH_MASK_WEST, NEIGH_MASK_SOUTH_WEST, NEIGH_MASK_SOUTH, NEIGH_MASK_SOUTH_EAST,\n ]\n\n# Constant listing all indices\n_LUT_INDS = np.arange(512)\n\n\ndef binary_image_to_lut_indices(x):\n \"\"\"\n Convert a binary image to an index image that can be used with a lookup table\n to perform morphological operations. Non-zero elements in the image are interpreted\n as 1, zero elements as 0\n\n :param x: a 2D NumPy array.\n :return: a 2D NumPy array, same shape as x\n \"\"\"\n if x.ndim != 2:\n raise ValueError('x should have 2 dimensions, not {}'.format(x.ndim))\n\n # If the dtype of x is not bool, convert\n if x.dtype != np.bool:\n x = x != 0\n\n # Add\n x = np.pad(x, [(1, 1), (1, 1)], mode='constant')\n\n # Convert to LUT indices\n lut_indices = x[:-2, :-2] * NEIGH_MASK_NORTH_WEST + \\\n x[:-2, 1:-1] * NEIGH_MASK_NORTH + \\\n x[:-2, 2:] * NEIGH_MASK_NORTH_EAST + \\\n x[1:-1, :-2] * NEIGH_MASK_WEST + \\\n x[1:-1, 1:-1] * NEIGH_MASK_CENTRE + \\\n x[1:-1, 2:] * NEIGH_MASK_EAST + \\\n x[2:, :-2] * NEIGH_MASK_SOUTH_WEST + \\\n x[2:, 1:-1] * NEIGH_MASK_SOUTH + \\\n x[2:, 2:] * NEIGH_MASK_SOUTH_EAST\n\n return lut_indices.astype(np.int32)\n\n\ndef apply_lut(x, lut):\n \"\"\"\n Perform a morphological operation on the binary image x using the supplied lookup table\n :param x:\n :param lut:\n :return:\n \"\"\"\n if lut.ndim != 1:\n raise ValueError('lut should have 1 dimension, not {}'.format(lut.ndim))\n\n if lut.shape[0] != 512:\n raise ValueError('lut should have 512 entries, not {}'.format(lut.shape[0]))\n\n lut_indices = binary_image_to_lut_indices(x)\n\n return lut[lut_indices]\n\n\ndef identity_lut():\n \"\"\"\n Create identity lookup tablef\n :return:\n \"\"\"\n lut = np.zeros((512,), dtype=bool)\n inds = np.arange(512)\n\n lut[(inds & NEIGH_MASK_CENTRE) != 0] = True\n\n return lut\n\n\ndef _lut_mutate_mask(lut):\n \"\"\"\n Get a mask that shows which neighbourhood shapes result in changes to the image\n :param lut: lookup table\n :return: mask indicating which lookup indices result in changes\n \"\"\"\n return lut != identity_lut()\n\n\ndef lut_masks_zero(neigh):\n \"\"\"\n Create a LUT index mask for which the specified neighbour is 0\n :param neigh: neighbour index; counter-clockwise from 1 staring at the eastern neighbour\n :return: a LUT index mask\n \"\"\"\n if neigh > 8:\n neigh -= 8\n return (_LUT_INDS & MASKS[neigh]) == 0\n\n\ndef lut_masks_one(neigh):\n \"\"\"\n Create a LUT index mask for which the specified neighbour is 1\n :param neigh: neighbour index; counter-clockwise from 1 staring at the eastern neighbour\n :return: a LUT index mask\n \"\"\"\n if neigh > 8:\n neigh -= 8\n return (_LUT_INDS & MASKS[neigh]) != 0\n\n\ndef _thin_cond_g1():\n \"\"\"\n Thinning morphological operation; condition G1\n :return: a LUT index mask\n \"\"\"\n b = np.zeros(512, dtype=int)\n for i in range(1, 5):\n b += lut_masks_zero(2 * i - 1) & (lut_masks_one(2 * i) | lut_masks_one(2 * i + 1))\n return b == 1\n\n\ndef _thin_cond_g2():\n \"\"\"\n Thinning morphological operation; condition G2\n :return: a LUT index mask\n \"\"\"\n n1 = np.zeros(512, dtype=int)\n n2 = np.zeros(512, dtype=int)\n for k in range(1, 5):\n n1 += (lut_masks_one(2 * k - 1) | lut_masks_one(2 * k))\n n2 += (lut_masks_one(2 * k) | lut_masks_one(2 * k + 1))\n m = np.minimum(n1, n2)\n return (m >= 2) & (m <= 3)\n\n\ndef _thin_cond_g3():\n \"\"\"\n Thinning morphological operation; condition G3\n :return: a LUT index mask\n \"\"\"\n return ((lut_masks_one(2) | lut_masks_one(3) | lut_masks_zero(8)) & lut_masks_one(1)) == 0\n\n\ndef _thin_cond_g3_prime():\n \"\"\"\n Thinning morphological operation; condition G3'\n :return: a LUT index mask\n \"\"\"\n return ((lut_masks_one(6) | lut_masks_one(7) | lut_masks_zero(4)) & lut_masks_one(5)) == 0\n\n\ndef _thin_iter_1_lut():\n \"\"\"\n Thinning morphological operation; lookup table for iteration 1\n :return: lookup table\n \"\"\"\n lut = identity_lut()\n cond = _thin_cond_g1() & _thin_cond_g2() & _thin_cond_g3()\n lut[cond] = False\n return lut\n\n\ndef _thin_iter_2_lut():\n \"\"\"\n Thinning morphological operation; lookup table for iteration 2\n :return: lookup table\n \"\"\"\n lut = identity_lut()\n cond = _thin_cond_g1() & _thin_cond_g2() & _thin_cond_g3_prime()\n lut[cond] = False\n return lut\n\n\ndef binary_thin(x, max_iter=None):\n \"\"\"\n Binary thinning morphological operation\n\n :param x: a binary image, or an image that is to be converted to a binary image\n :param max_iter: maximum number of iterations; default is `None` that results in an infinite\n number of iterations (note that `binary_thin` will automatically terminate when no more changes occur)\n :return:\n \"\"\"\n thin1 = _thin_iter_1_lut()\n thin2 = _thin_iter_2_lut()\n thin1_mut = _lut_mutate_mask(thin1)\n thin2_mut = _lut_mutate_mask(thin2)\n\n iter_count = 0\n while max_iter is None or iter_count < max_iter:\n # Iter 1\n lut_indices = binary_image_to_lut_indices(x)\n x_mut = thin1_mut[lut_indices]\n if x_mut.sum() == 0:\n break\n\n x = thin1[lut_indices]\n\n # Iter 2\n lut_indices = binary_image_to_lut_indices(x)\n x_mut = thin2_mut[lut_indices]\n if x_mut.sum() == 0:\n break\n\n x = thin2[lut_indices]\n\n iter_count += 1\n\n return x\n", "# noinspection PyPackageRequirements\nimport cv2\nimport numpy as np\n\n# noinspection PyUnresolvedReferences\nimport Application.Jobs.kernels\nfrom Application.Frame import transferJobPorts\nfrom Application.Frame.global_variables import JobInitStateReturn\nfrom Application.Frame.transferJobPorts import get_port_from_wave\nfrom scipy.ndimage.filters import convolve\nfrom cv2.ximgproc import GradientDericheX, GradientDericheY\n\nfrom Application.Utils.misc import rotate_around_center\nfrom Utils.log_handler import log_error_to_console\n\n\n\"\"\"\nModule handles kernel convolution image jobs for the APPL block.\n\"\"\"\n\n\ndef compute_gradients_frei_chen(port_in: transferJobPorts.Port, dilation_factor: int,\n port_out_name_g1: str, port_out_name_g2: str, port_out_name_g3: str,\n port_out_name_g4: str, port_out_name_g5: str, port_out_name_g6: str,\n port_out_name_g7: str, port_out_name_g8: str, port_out_name_g9: str) -> None:\n \"\"\"\n Adds to specific output ports the result of convolution the image with 9 frei-chen masks\n The function uses cv2.filter2D function\n :param port_in: image to apply convolution on\n :param dilation_factor: dilation_factor of kernel\n :param port_out_name_g1: image resulted after convolution with kernel g1 -> isotropic gradient\n :param port_out_name_g2: image resulted after convolution with kernel g2 -> isotropic gradient\n :param port_out_name_g3: image resulted after convolution with kernel g3 -> ripple\n :param port_out_name_g4: image resulted after convolution with kernel g4 -> ripple\n :param port_out_name_g5: image resulted after convolution with kernel g5 -> line\n :param port_out_name_g6: image resulted after convolution with kernel g6 -> line\n :param port_out_name_g7: image resulted after convolution with kernel g7 -> discrete laplacian\n :param port_out_name_g8: image resulted after convolution with kernel g8 -> discrete laplacian\n :param port_out_name_g9: image resulted after convolution with kernel g9 -> average\n :return: None\n \"\"\"\n port_out = [get_port_from_wave(name=port_out_name_g1), get_port_from_wave(name=port_out_name_g2),\n get_port_from_wave(name=port_out_name_g3), get_port_from_wave(name=port_out_name_g4),\n get_port_from_wave(name=port_out_name_g5), get_port_from_wave(name=port_out_name_g6),\n get_port_from_wave(name=port_out_name_g7), get_port_from_wave(name=port_out_name_g8),\n get_port_from_wave(name=port_out_name_g9)]\n\n for kernel in range(len(port_out)):\n result = np.zeros(shape=port_in.arr.shape, dtype=np.float32)\n\n if dilation_factor == 0:\n kernel_to_use = eval('Application.Jobs.kernels.' + 'frei_chen_v' + str(kernel + 1))\n elif dilation_factor == 1:\n kernel_to_use = eval('Application.Jobs.kernels.' + 'frei_chen_dilated_5x5_v' + str(kernel + 1))\n elif dilation_factor == 2:\n kernel_to_use = eval('Application.Jobs.kernels.' + 'frei_chen_dilated_7x7_v' + str(kernel + 1))\n # flip kernels for a real convolution to be done by cv2.filter2D\n kernel_to_use = kernel_to_use[::-1, ::-1]\n cv2.filter2D(src=port_in.arr, ddepth=cv2.CV_32F, kernel=kernel_to_use, dst=result, anchor=(-1, -1))\n result = result * result\n\n port_out[kernel].arr[:] = np.int32(result)\n port_out[kernel].set_valid()\n\n\ndef compute_gradients_navatia_babu(port_in: transferJobPorts.Port,\n port_out_name_g1: str, port_out_name_g2: str, port_out_name_g3: str,\n port_out_name_g4: str, port_out_name_g5: str, port_out_name_g6: str) -> None:\n \"\"\"\n Adds to specific output ports the result of convolution the image with 9 frei-chen masks\n The function uses cv2.filter2D function\n :param port_in: image to apply convolution on\n :param port_out_name_g1: image resulted after convolution with kernel g1\n :param port_out_name_g2: image resulted after convolution with kernel g2\n :param port_out_name_g3: image resulted after convolution with kernel g3\n :param port_out_name_g4: image resulted after convolution with kernel g4\n :param port_out_name_g5: image resulted after convolution with kernel g5\n :param port_out_name_g6: image resulted after convolution with kernel g6\n :return: None\n \"\"\"\n port_out = [get_port_from_wave(name=port_out_name_g1), get_port_from_wave(name=port_out_name_g2),\n get_port_from_wave(name=port_out_name_g3), get_port_from_wave(name=port_out_name_g4),\n get_port_from_wave(name=port_out_name_g5), get_port_from_wave(name=port_out_name_g6)]\n\n for kernel in range(len(port_out)):\n result = np.zeros(port_in.arr.shape, np.float32)\n kernel_to_use = eval('Application.Jobs.kernels.' + 'navatia_babu_5x5_g' + str(kernel + 1))\n # flip kernels for a real convolution to be done by cv2.filter2D\n kernel_to_use = kernel_to_use[::-1, ::-1]\n cv2.filter2D(src=port_in.arr, ddepth=cv2.CV_32F, kernel=kernel_to_use, dst=result, anchor=(-1, -1))\n\n port_out[kernel].arr[:] = np.int32(result)\n port_out[kernel].set_valid()\n\n\ndef compute_gradients_8_directions(port_in: transferJobPorts.Port,\n port_out_name_gn: str, port_out_name_gnw: str, port_out_name_gw: str, port_out_name_gsw: str,\n port_out_name_gs: str, port_out_name_gse: str, port_out_name_ge: str, port_out_name_gne: str,\n kernel: bytearray) -> None:\n \"\"\"\n Adds to specific output ports the result of convolution the image with 8 kernels directions: N, NW, W, SW, S, SE, E, and NE\n The function uses cv2.filter2D function\n :param port_in: image to apply convolution on\n :param port_out_name_gn: image resulted after convolution kernel for N direction and picture\n :param port_out_name_gnw: image resulted after convolution kernel for NW direction and picture\n :param port_out_name_gw: image resulted after convolution kernel for W direction and picture\n :param port_out_name_gsw: image resulted after convolution kernel for SW direction and picture\n :param port_out_name_gs: image resulted after convolution kernel for S direction and picture\n :param port_out_name_gse: image resulted after convolution kernel for SE direction and picture\n :param port_out_name_ge: image resulted after convolution kernel for E direction and picture\n :param port_out_name_gne: image resulted after convolution kernel for NE direction and picture\n :param kernel: kernel to use\n :return: None\n \"\"\"\n port_out = [get_port_from_wave(name=port_out_name_gn), get_port_from_wave(name=port_out_name_gnw),\n get_port_from_wave(name=port_out_name_gw), get_port_from_wave(name=port_out_name_gsw),\n get_port_from_wave(name=port_out_name_gs), get_port_from_wave(name=port_out_name_gse),\n get_port_from_wave(name=port_out_name_ge), get_port_from_wave(name=port_out_name_gne)]\n\n kernel_to_use = kernel\n\n for direction in range(len(port_out)):\n result = np.zeros(port_in.arr.shape, np.float32)\n # flip kernels for a real convolution to be done by cv2.filter2D\n kernel_to_use = kernel_to_use[::-1, ::-1]\n cv2.filter2D(src=port_in.arr, ddepth=cv2.CV_32F, kernel=kernel_to_use, dst=result, anchor=(-1, -1))\n port_out[direction].arr[:] = np.int32(result)\n port_out[direction].set_valid()\n kernel_to_use = rotate_around_center(mat=kernel_to_use)\n\n\ndef compute_gradient_filter_2d(port_in: transferJobPorts.Port, port_out_name_gx: str, port_out_name_gy: str,\n kernel_x: bytearray, kernel_y: bytearray) -> None:\n \"\"\"\n Adds to specific output ports the result of convolution the image with 2 kernels(x and y)\n The function uses cv2.filter2D function\n :param port_in: image to apply convolution on\n :param port_out_name_gx: image resulted after convolution kernel for x and picture\n :param port_out_name_gy: image resulted after convolution kernel for y and picture\n :param kernel_x: kernel for x direction\n :param kernel_y: kernel for y direction\n :return: None\n \"\"\"\n port_out_gx = get_port_from_wave(name=port_out_name_gx)\n port_out_gy = get_port_from_wave(name=port_out_name_gy)\n\n # Magnitude matrices for Ix/dx and Iy/dy\n magnitude_x = np.zeros(shape=port_in.arr.shape, dtype=np.float32)\n magnitude_y = np.zeros(shape=port_in.arr.shape, dtype=np.float32)\n # flip kernels for a real convolution to be done by cv2.filter2D\n kernel_x = kernel_x[::-1, ::-1]\n kernel_y = kernel_y[::-1, ::-1]\n\n cv2.filter2D(src=port_in.arr, ddepth=cv2.CV_32F, kernel=kernel_x, dst=magnitude_x, anchor=(-1, -1))\n cv2.filter2D(src=port_in.arr, ddepth=cv2.CV_32F, kernel=kernel_y, dst=magnitude_y, anchor=(-1, -1))\n\n # Convert to signed 16 bit integer values (normalization)\n port_out_gx.arr[:] = np.int32(magnitude_x)\n port_out_gx.set_valid()\n port_out_gy.arr[:] = np.int32(magnitude_y)\n port_out_gy.set_valid()\n\n\ndef compute_gradient_convolve(port_in: transferJobPorts.Port, port_out_name_gx: str, port_out_name_gy: str,\n kernel_x: bytearray, kernel_y: bytearray) -> None:\n \"\"\"\n Adds to specific output ports the result of convolution the image with 2 kernels(x and y)\n The function uses cv2.filter2D function\n :param port_in: image to apply convolution on\n :param port_out_name_gx: image resulted after convolution kernel for x and picture\n :param port_out_name_gy: image resulted after convolution kernel for y and picture\n :param kernel_x: kernel for x direction\n :param kernel_y: kernel for y direction\n :return: None\n \"\"\"\n port_out_gx = get_port_from_wave(name=port_out_name_gx)\n port_out_gy = get_port_from_wave(name=port_out_name_gy)\n\n img = np.float64(port_in.arr)\n\n port_out_gx.arr[:] = convolve(input=img, weights=kernel_x)\n port_out_gy.arr[:] = convolve(input=img, weights=kernel_y)\n\n # Convert to signed 16 bit integer values (normalization)\n port_out_gx.set_valid()\n port_out_gy.set_valid()\n\n\ndef init_func_global() -> JobInitStateReturn:\n \"\"\"\n Init function for the job\n :return: INIT or NOT_INIT state for the job\n \"\"\"\n return JobInitStateReturn(True)\n\n\ndef main_func_convolution(param_list: list = None) -> bool:\n \"\"\"\n Main function for gradient calculation job.\n :param param_list: Param needed to respect the following list:\n [port_in name: str, port_out_name_gx name: str, port_out_name_gy name: str, sobel_x name: str, sobel_y name: str]\n :return: True if the job executed OK.\n \"\"\"\n # noinspection PyPep8Naming\n INPUT_PORT_POS = 0\n # noinspection PyPep8Naming\n PORT_IN_WAVE_IMG = 1\n # noinspection PyPep8Naming\n OUTPUT_GX_POS = 2\n # noinspection PyPep8Naming\n OUTPUT_GY_POS = 3\n # noinspection PyPep8Naming\n KERNEL_X_POS = 4\n # noinspection PyPep8Naming\n KERNEL_Y_POS = 5\n\n if len(param_list) != 6:\n log_error_to_console(\"KERNEL CONVOLUTION JOB MAIN FUNCTION PARAM NOK\", str(len(param_list)))\n return False\n else:\n port_in = get_port_from_wave(name=param_list[INPUT_PORT_POS], wave_offset=param_list[PORT_IN_WAVE_IMG])\n\n if 'x' in param_list[KERNEL_X_POS] or 'y' in param_list[KERNEL_Y_POS]:\n kernel_x = eval('Application.Jobs.kernels.' + param_list[KERNEL_X_POS])\n kernel_y = eval('Application.Jobs.kernels.' + param_list[KERNEL_Y_POS])\n else:\n kernel_x = np.array(eval(param_list[KERNEL_X_POS]))\n kernel_y = np.array(eval(param_list[KERNEL_Y_POS]))\n\n if port_in.is_valid() is True:\n try:\n compute_gradient_filter_2d(port_in=port_in, port_out_name_gx=param_list[OUTPUT_GX_POS],\n port_out_name_gy=param_list[OUTPUT_GY_POS], kernel_x=kernel_x, kernel_y=kernel_y)\n except BaseException as error:\n log_error_to_console(\"KERNEL CONVOLUTION JOB NOK: \", str(error))\n pass\n else:\n return False\n\n return True\n\n\ndef main_func_deriche_convolution(param_list: list = None) -> bool:\n \"\"\"\n Main function for deriche gradient calculation job.\n :param param_list: Param needed to respect the following list:\n [port_in name: str, port_out_name_gx name: str, port_out_name_gy name: str, sobel_x name: str, sobel_y name: str]\n :return: True if the job executed OK.\n \"\"\"\n # noinspection PyPep8Naming\n INPUT_PORT_POS = 0\n # noinspection PyPep8Naming\n PORT_IN_WAVE_IMG = 1\n # noinspection PyPep8Naming\n KERNEL_ALPHA = 2\n # noinspection PyPep8Naming\n KERNEL_OMEGA = 3\n # noinspection PyPep8Naming\n OUTPUT_GX_POS = 4\n # noinspection PyPep8Naming\n OUTPUT_GY_POS = 5\n\n if len(param_list) != 6:\n log_error_to_console(\"KERNEL CONVOLUTION DERICHE JOB MAIN FUNCTION PARAM NOK\", str(len(param_list)))\n return False\n else:\n port_in = get_port_from_wave(name=param_list[INPUT_PORT_POS], wave_offset=param_list[PORT_IN_WAVE_IMG])\n\n if port_in.is_valid() is True:\n try:\n port_out_gx = get_port_from_wave(name=param_list[OUTPUT_GX_POS])\n port_out_gy = get_port_from_wave(name=param_list[OUTPUT_GY_POS])\n\n magnitude_x = GradientDericheX(op=port_in.arr.copy(), alpha=param_list[KERNEL_ALPHA], omega=param_list[KERNEL_OMEGA])\n magnitude_y = GradientDericheY(op=port_in.arr.copy(), alpha=param_list[KERNEL_ALPHA], omega=param_list[KERNEL_OMEGA])\n\n # Convert to signed 16 bit integer values (normalization)\n port_out_gx.arr[:] = np.int16(magnitude_x)\n port_out_gx.set_valid()\n port_out_gy.arr[:] = np.int16(magnitude_y)\n port_out_gy.set_valid()\n except BaseException as error:\n log_error_to_console(\"KERNEL CONVOLUTION DERICHE JOB NOK: \", str(error))\n pass\n else:\n return False\n\n return True\n\n\ndef main_func_alternative(param_list: list = None) -> bool:\n \"\"\"\n Main function for gradient calculation job.\n :param param_list: Param needed to respect the following list:\n [port_in name: str, port_out_name_gx name: str, port_out_name_gy name: str,\n sobel_x name: str, sobel_y name: str]\n :return: True if the job executed OK.\n \"\"\"\n # noinspection PyPep8Naming\n INPUT_PORT_POS = 0\n # noinspection PyPep8Naming\n OUTPUT_GX_POS = 1\n # noinspection PyPep8Naming\n OUTPUT_GY_POS = 2\n # noinspection PyPep8Naming\n KERNEL_X_POS = 3\n # noinspection PyPep8Naming\n KERNEL_Y_POS = 4\n\n if len(param_list) != 5:\n log_error_to_console(\"KERNEL CONVOLUTION JOB MAIN FUNCTION PARAM NOK\", str(len(param_list)))\n return False\n else:\n port_in = get_port_from_wave(param_list[INPUT_PORT_POS])\n\n if port_in.is_valid() is True:\n compute_gradient_convolve(port_in=port_in,\n port_out_name_gx=param_list[OUTPUT_GX_POS], port_out_name_gy=param_list[OUTPUT_GY_POS],\n kernel_x=eval('Application.Jobs.kernels.' + param_list[KERNEL_X_POS]),\n kernel_y=eval('Application.Jobs.kernels.' + param_list[KERNEL_Y_POS]))\n else:\n return False\n\n return True\n\n\ndef main_func_cross(param_list: list = None) -> bool:\n \"\"\"\n Main function for gradient calculation job.\n :param param_list: Param needed to respect the following list:\n [port_in name: str,\n port_out_name_gn: str, port_out_name_gnw: str, port_out_name_gw: str, port_out_name_gsw: str,\n port_out_name_gs: str, port_out_name_gse: str, port_out_name_ge: str, port_out_name_gne: str,\n kernel name: str]\n :return: True if the job executed OK.\n \"\"\"\n # noinspection PyPep8Naming\n INPUT_PORT_POS = 0\n # noinspection PyPep8Naming\n PORT_IN_WAVE_IMG = 1\n # noinspection PyPep8Naming\n OUTPUT_G1_POS = 2\n # noinspection PyPep8Naming\n OUTPUT_G2_POS = 3\n # noinspection PyPep8Naming\n OUTPUT_G3_POS = 4\n # noinspection PyPep8Naming\n OUTPUT_G4_POS = 5\n # noinspection PyPep8Naming\n OUTPUT_G5_POS = 6\n # noinspection PyPep8Naming\n OUTPUT_G6_POS = 7\n # noinspection PyPep8Naming\n OUTPUT_G7_POS = 8\n # noinspection PyPep8Naming\n OUTPUT_G8_POS = 9\n # noinspection PyPep8Naming\n KERNEL_POS = 10\n\n if len(param_list) != 11:\n log_error_to_console(\"KERNEL CROSS CONVOLUTION JOB MAIN FUNCTION PARAM NOK\", str(len(param_list)))\n return False\n else:\n port_in = get_port_from_wave(param_list[INPUT_PORT_POS], param_list[PORT_IN_WAVE_IMG])\n\n if 'x' in param_list[KERNEL_POS] or 'y' in param_list[KERNEL_POS]:\n kernel = eval('Application.Jobs.kernels.' + param_list[KERNEL_POS])\n else:\n kernel = np.array(eval(param_list[KERNEL_POS]))\n\n if port_in.is_valid() is True:\n try:\n compute_gradients_8_directions(port_in=port_in,\n port_out_name_gn=param_list[OUTPUT_G1_POS], port_out_name_gnw=param_list[OUTPUT_G2_POS],\n port_out_name_gw=param_list[OUTPUT_G3_POS], port_out_name_gsw=param_list[OUTPUT_G4_POS],\n port_out_name_gs=param_list[OUTPUT_G5_POS], port_out_name_gse=param_list[OUTPUT_G6_POS],\n port_out_name_ge=param_list[OUTPUT_G7_POS], port_out_name_gne=param_list[OUTPUT_G8_POS],\n kernel=kernel)\n except BaseException as error:\n log_error_to_console(\"KERNEL CROSS CONVOLUTION JOB NOK: \", str(error))\n pass\n\n else:\n return False\n\n return True\n\n\ndef main_func_frei_chen(param_list: list = None) -> bool:\n \"\"\"\n Main function for gradient calculation job.\n :param param_list: Param needed to respect the following list:\n [port_in name: str, wave_offset,\n port_out_name_g1: str, port_out_name_g2: str, port_out_name_g3: str,\n port_out_name_g4: str, port_out_name_g5: str, port_out_name_g6: str,\n port_out_name_g7: str, port_out_name_g8: str, port_out_name_g9: str]\n :return: True if the job executed OK.\n \"\"\"\n # noinspection PyPep8Naming\n INPUT_PORT_POS = 0\n # noinspection PyPep8Naming\n PORT_IN_WAVE_IMG = 1\n # noinspection PyPep8Naming\n PORT_IN_KENEL_DILATION = 2\n # noinspection PyPep8Naming\n OUTPUT_G1_POS = 3\n # noinspection PyPep8Naming\n OUTPUT_G2_POS = 4\n # noinspection PyPep8Naming\n OUTPUT_G3_POS = 5\n # noinspection PyPep8Naming\n OUTPUT_G4_POS = 6\n # noinspection PyPep8Naming\n OUTPUT_G5_POS = 7\n # noinspection PyPep8Naming\n OUTPUT_G6_POS = 8\n # noinspection PyPep8Naming\n OUTPUT_G7_POS = 9\n # noinspection PyPep8Naming\n OUTPUT_G8_POS = 10\n # noinspection PyPep8Naming\n OUTPUT_G9_POS = 11\n\n if len(param_list) != 12:\n log_error_to_console(\"KERNEL CONVOLUTION JOB MAIN FUNCTION PARAM NOK\", str(len(param_list)))\n return False\n else:\n port_in = get_port_from_wave(param_list[INPUT_PORT_POS], param_list[PORT_IN_WAVE_IMG])\n\n if port_in.is_valid() is True:\n try:\n compute_gradients_frei_chen(port_in=port_in, dilation_factor=param_list[PORT_IN_KENEL_DILATION],\n port_out_name_g1=param_list[OUTPUT_G1_POS], port_out_name_g2=param_list[OUTPUT_G2_POS],\n port_out_name_g3=param_list[OUTPUT_G3_POS], port_out_name_g4=param_list[OUTPUT_G4_POS],\n port_out_name_g5=param_list[OUTPUT_G5_POS], port_out_name_g6=param_list[OUTPUT_G6_POS],\n port_out_name_g7=param_list[OUTPUT_G7_POS], port_out_name_g8=param_list[OUTPUT_G8_POS],\n port_out_name_g9=param_list[OUTPUT_G9_POS])\n except BaseException as error:\n log_error_to_console(\"KERNEL CONVOLUTION JOB NOK: \", str(error))\n pass\n else:\n return False\n\n return True\n\n\ndef main_func_navatia_babu(param_list: list = None) -> bool:\n \"\"\"\n Main function for gradient calculation job.\n :param param_list: Param needed to respect the following list:\n [port_in name: str, wave_offset,\n port_out_name_g1: str, port_out_name_g2: str, port_out_name_g3: str,\n port_out_name_g4: str, port_out_name_g5: str, port_out_name_g6: str,\n port_out_name_g7: str, port_out_name_g8: str, port_out_name_g9: str]\n :return: True if the job executed OK.\n \"\"\"\n # noinspection PyPep8Naming\n INPUT_PORT_POS = 0\n # noinspection PyPep8Naming\n PORT_IN_WAVE_IMG = 1\n # noinspection PyPep8Naming\n OUTPUT_G1_POS = 2\n # noinspection PyPep8Naming\n OUTPUT_G2_POS = 3\n # noinspection PyPep8Naming\n OUTPUT_G3_POS = 4\n # noinspection PyPep8Naming\n OUTPUT_G4_POS = 5\n # noinspection PyPep8Naming\n OUTPUT_G5_POS = 6\n # noinspection PyPep8Naming\n OUTPUT_G6_POS = 7\n\n if len(param_list) != 8:\n log_error_to_console(\"KERNEL CONVOLUTION NAVATIA-BABU JOB MAIN FUNCTION PARAM NOK\", str(len(param_list)))\n return False\n else:\n port_in = get_port_from_wave(param_list[INPUT_PORT_POS], param_list[PORT_IN_WAVE_IMG])\n\n if port_in.is_valid() is True:\n try:\n compute_gradients_navatia_babu(port_in=port_in,\n port_out_name_g1=param_list[OUTPUT_G1_POS], port_out_name_g2=param_list[OUTPUT_G2_POS],\n port_out_name_g3=param_list[OUTPUT_G3_POS], port_out_name_g4=param_list[OUTPUT_G4_POS],\n port_out_name_g5=param_list[OUTPUT_G5_POS], port_out_name_g6=param_list[OUTPUT_G6_POS])\n except BaseException as error:\n log_error_to_console(\"KERNEL CONVOLUTION NAVATIA-BABU JOB NOK: \", str(error))\n pass\n else:\n return False\n\n return True\n\n\nif __name__ == \"__main__\":\n pass\n" ]
[ [ "numpy.arange", "numpy.minimum", "numpy.zeros", "numpy.pad" ], [ "numpy.int32", "numpy.int16", "numpy.float64", "scipy.ndimage.filters.convolve", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "1.6", "0.14", "0.15", "1.4", "0.16", "1.0", "0.19", "1.5", "0.18", "1.2", "1.7", "0.12", "0.10", "0.17", "1.3" ], "tensorflow": [] } ]
HS-YN/PanoAVQA
[ "657b83421ce64ea18b3e79fb580afc7034403ccc" ]
[ "code/optimizer/schedulers.py" ]
[ "from torch.optim.lr_scheduler import LambdaLR\r\nfrom transformers import get_linear_schedule_with_warmup\r\n\r\nfrom exp import ex\r\n\r\n\r\ndef get_no_scheduler(optimizer, num_warmup_steps, num_training_steps):\r\n def lr_lambda(current_step):\r\n return 1\r\n\r\n return LambdaLR(optimizer, lr_lambda)\r\n\r\n\r\nsched_dict = {\r\n 'linear': get_linear_schedule_with_warmup,\r\n 'none': get_no_scheduler\r\n}\r\n\r\n\r\[email protected]()\r\ndef get_scheduler(optimizer, t_total, warmup, scheduler_name, grad_acc_steps):\r\n warmup_steps = int(t_total * warmup)\r\n scheduler = sched_dict[scheduler_name](optimizer, warmup_steps, t_total)\r\n scheduler.accumulated = 0\r\n scheduler.grad_acc_steps = grad_acc_steps\r\n return scheduler" ]
[ [ "torch.optim.lr_scheduler.LambdaLR" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yycho0108/monovo
[ "9f2b5cf15f97e467c8e6e94ee16bb785ed6c7edd", "9f2b5cf15f97e467c8e6e94ee16bb785ed6c7edd" ]
[ "core/track.py", "core/vmap.py" ]
[ "import time\nimport cv2\nimport numpy as np\nfrom collections import defaultdict\n\nclass Tracker(object):\n def __init__(self, pLK=None):\n if pLK is None:\n # default LK param\n pLK = self.pLK0()\n self.lk_ = cv2.SparsePyrLKOpticalFlow_create(\n **pLK)\n self.tmp_ = defaultdict(lambda:None)\n\n def pLK0(self):\n \"\"\"\n Default LK Params.\n \"\"\"\n return dict(\n winSize = (12,6),\n maxLevel = 4, # == effective winsize up to 32*(2**4) = 512x256\n crit= (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 100, 0.03),\n flags = 0,\n minEigThreshold = 1e-3 # TODO : disable eig?\n )\n\n def __call__(self, \n img1, img2,\n pt1, pt2=None,\n thresh=2.0,\n return_msk=False\n ):\n \"\"\"\n Arguments:\n img1(np.ndarray) : previous image. (color/mono) (HxWx?)\n img2(np.ndarray) : current image (color/mono) (HxWx?)\n pt1(np.ndarray) : previous points. (Mx2)\n pt2(np.ndarray) : [Optional] current points estimate (Mx2)\n thresh(float) : Flow Back-projection Error threshold\n\n Returns:\n pt2(np.ndarray) : current points. (Mx2)\n idx(np.ndarray) : valid tracked indices from pt1 & pt2.\n \"\"\"\n if pt1.size <= 0:\n # soft fail\n pt2 = np.empty([0,2], dtype=np.float32)\n if return_msk:\n msk = np.empty([0], dtype=np.bool)\n return pt2, msk\n idx = np.empty([0], dtype=np.int32)\n return pt2, idx\n\n # stat img\n h, w = np.shape(img2)[:2]\n\n # convert to grayscale\n # TODO : check if already gray/mono\n\n if (np.ndim(img1) == 2) or img1.shape[2] == 1:\n # already monochromatic\n img1_gray = img1\n img2_gray = img2\n else:\n # handle image # 1 + pre-allocated data cache\n if self.tmp_['img1g'] is not None:\n cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY, self.tmp_['img1g'])\n img1_gray = self.tmp_['img1g']\n else:\n img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n self.tmp_['img1g'] = np.empty_like(img1_gray)\n\n # handle image # 2 + pre-allocated data cache\n if self.tmp_['img2g'] is not None:\n cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY, self.tmp_['img2g'])\n img2_gray = self.tmp_['img2g']\n else:\n img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n self.tmp_['img2g'] = np.empty_like(img2_gray)\n\n # forward flow\n if pt2 is not None:\n # set initial flow flags\n self.lk_.setFlags(self.lk_.getFlags() | cv2.OPTFLOW_USE_INITIAL_FLOW )\n pt2, st, _ = self.lk_.calc(\n img1_gray, img2_gray, pt1, pt2\n )\n else:\n pt2, st, _ = self.lk_.calc(\n img1_gray, img2_gray, pt1, None\n )\n st_fw = st[:,0].astype(np.bool)\n\n # backward flow\n # unset initial flow flags\n self.lk_.setFlags(self.lk_.getFlags() & ~cv2.OPTFLOW_USE_INITIAL_FLOW )\n pt1_r, st, _ = self.lk_.calc(\n img2_gray, img1_gray, pt2, None\n )\n st_bw = st[:,0].astype(np.bool)\n\n # override error with reprojection error\n # (default error doesn't make much sense anyways)\n err = np.linalg.norm(pt1 - pt1_r, axis=-1)\n\n # apply mask\n msk = np.logical_and.reduce([\n # error check\n err < thresh,\n # bounds check\n 0 <= pt2[:,0],\n 0 <= pt2[:,1],\n pt2[:,0] < w,\n pt2[:,1] < h,\n # status check\n st_fw,\n st_bw,\n ])\n\n if return_msk:\n return pt2, msk\n else:\n idx = np.where(msk)[0]\n return pt2, idx\n\ndef main():\n from matplotlib import pyplot as plt\n # params\n w = 2*640\n h = 2*480\n n = 2*1024\n di = 8\n dj = 32\n\n track = Tracker()\n\n img1 = np.random.randint(0, 255, size=(h,w,3), dtype=np.uint8)\n #img2 = np.random.randint(0, 255, size=(480,640,3), dtype=np.uint8)\n img2 = np.roll(img1, di, axis=0)\n img2 = np.roll(img2, dj, axis=1)\n\n #img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n #img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n\n pt1 = np.random.uniform((0,0), (w,h), size=(n,2)).astype(np.float32)\n pt2, idx = track(img1, img2, pt1)\n #pt2, idx = track(img1, img2, pt1, pt2)\n\n fig, ax = plt.subplots(1,2)\n ax[0].imshow(img1, alpha=0.5)\n ax[0].plot(pt1[:,0], pt1[:,1], 'r+')\n\n ax[1].imshow(img2, alpha=0.5)\n ax[1].plot(pt1[:,0], pt1[:,1], 'bx')\n ax[1].plot(pt2[:,0], pt2[:,1], 'r+')\n plt.show()\n\nif __name__ == \"__main__\":\n main()\n", "import numpy as np\nimport cv2\nfrom sklearn.neighbors import NearestNeighbors\nfrom utils import vmath as M\n\n# TODO : currently in the process\n# of refactoring with accord to the new parametrization,\n# lmk = src + d * vec.\n\nclass VMap(object):\n \"\"\"\n Visual Landmarks management.\n\n Supported Methods:\n \"\"\"\n def __init__(self, cvt, descriptor):\n # Conversions() proc handle\n self.cvt_ = cvt\n\n # == auto unroll descriptor parameters ==\n n_des = descriptor.descriptorSize()\n # Not 100% sure, but don't want to take risks with unsigned math\n t_des = (np.uint8 if descriptor.descriptorType() == cv2.CV_8U\n else np.float32)\n s_fac = descriptor.getScaleFactor()\n n_lvl = descriptor.getNLevels()\n # =======================================\n\n # define datatype\n self.lmk_t_ = np.dtype([\n # Positional data\n ('fid', np.int32), # source frame index\n ('src', np.float32, 3), # source pose (may change)\n ('idp', np.float32), # inverse depth\n ('vec', np.float32, 3), # view-vector\n\n # Landmark Health\n ('var', np.float32), # Depth variance\n ('cnt', np.int32), # Number of Total observations\n\n # Feature Information\n ('des', np.float32, n_des),\n ('oct', np.int32),\n ('rsp', np.float32),\n\n # Tracking Information\n ('kpt', np.float32, 2),\n ('trk', np.bool),\n\n # Query Cache / Logging\n ('ang', np.float32),\n ('col', np.uint8, 3),\n\n # derived data (cache)\n ('mnd', np.float32),\n ('mxd', np.float32),\n ('dpt', np.float32), # depth, (1.0 / idp)\n ('pos', np.float32, 3) # position, computed from\n ])\n\n # container management ...\n self.capacity_ = c = 1024\n self.size_ = s = 0\n self.data_ = np.empty(c, dtype=self.lmk_t_)\n\n # query filtering\n # NOTE : maxd/mind scale filtering may be ORB-specific.\n self.s_fac_ = s_fac\n self.n_lvl_ = n_lvl\n self.s_pyr_ = np.power(self.s_fac_, np.arange(self.n_lvl_))\n\n # store index for efficient pruning\n self.pidx_ = 0\n\n def resize(self, c_new):\n print('-------landmarks resizing : {} -> {}'.format(self.capacity_, c_new))\n d_new = np.empty(c_new, dtype=self.lmk_t_)\n d_new[:self.size_] = self.data_[:self.size_]\n self.data_ = d_new\n self.capacity_ = c_new\n\n def compute_pt3(self, src,\n ray=None,\n vec=None,\n idp=None,\n dpt=None,\n ):\n \"\"\"\n Compute pt3 from the following combinations:\n src + ray=(dpt=(1/idp)*vec)\n \"\"\"\n if ray is None:\n if dpt is None:\n dpt = (1.0 / idp)\n ray = dpt[:,None] * vec\n\n pt3 = self.cvt_.cam_to_map(ray, src)\n return pt3\n\n def append(self,\n fid, pos, src,\n kpt, des, col):\n \"\"\"\n Append with minimal information.\n All derived quantities will be computed from the provided data.\n\n fid = Source frame Id (required for graph lookup)\n pos = Landmark position in `src` frame\n src = Source frame pose, p3 parametrization (x,y,h)\n kpt = cv2.KeyPoint() object for feature description/tracking\n des = Feature Descriptor\n col = Landmark Color (right now, for visualization only)\n \"\"\"\n # compute derived quantities\n dpt = pos[:, 2]\n idp = (1.0 / dpt)\n vec = pos * idp[:, None]\n var = 0.1 * dpt # since variance is a weighting parameter, kept at dpt\n cnt = 1 # will be broadcasted\n oct = [e.octave for e in kpt]\n rsp = [e.response for e in kpt]\n kpt = [e.pt for e in kpt] # NOTE : shadows previous kpt\n trk = True\n ang = src[2] # will be broadcasted\n\n pos = self.compute_pt3(src, ray=pos) # NOTE : shadows previous pos\n lsf = np.float32([self.s_pyr_[e] for e in oct])\n mxd = dpt * lsf\n mnd = mxd / self.s_pyr_[-1]\n\n # _append should not be called outside of this class\n # since the argument order is required to be very specific.\n # HACK : pass vars() to avoid repeating names\n self._append(vars())\n\n def _append(self, v):\n n = len(v['pos'])\n if self.size_ + n > self.capacity_:\n self.resize(self.capacity_ * 2)\n # retry append after resize\n self._append(v)\n else:\n # assign\n i = np.s_[self.size_:self.size_+n]\n for k in self.data_.dtype.names:\n self.data_[k][i] = v[k]\n # update size\n self.size_ += n\n\n def query(self, src,\n atol = np.deg2rad(30.0),\n dtol = 1.2,\n trk=False\n ):\n cvt = self.cvt_\n\n # unroll map query source (base frame)\n src_x, src_y, src_h = np.ravel(src)\n\n # filter : by view angle\n a_dif = np.abs((self['ang'] - src_h + np.pi)\n % (2*np.pi) - np.pi)\n a_msk = np.less(a_dif, atol) # TODO : kind-of magic number\n\n # filter : by min/max ORB distance\n pt3_s = cvt.map_to_cam(self['pos'], src)\n d_msk = np.logical_and.reduce([\n self['mnd'] / dtol <= pt3_s[:, 2],\n pt3_s[:, 2] <= self['mxd'] * dtol\n ])\n \n # filter : by visibility\n if self.size <= 0:\n # no data : soft fail\n pt2 = np.empty((0,2), dtype=np.float32)\n v_msk = np.empty((0,), dtype=np.bool)\n else:\n pt2, v_msk = cvt.pt3_pose_to_pt2_msk(\n self['pos'], src)\n\n # merge filters\n msk = np.logical_and.reduce([\n v_msk,\n a_msk,\n d_msk\n ])\n\n if trk:\n msk &= self.trk[:,0]\n idx = np.where(msk)[0]\n\n # collect results + return\n pt2 = pt2[idx]\n pos = self['pos'][idx]\n des = self['des'][idx]\n var = self['var'][idx]\n cnt = self['cnt'][idx]\n return (pt2, pos, des, var, cnt, idx)\n\n def _update_cache(self, idx=None):\n \"\"\"\n Assuming self.idp / self.src had been modified,\n updates the following derived parameters:\n [dpt, pos, mxd, mnd]\n \"\"\"\n if idx is None:\n idx = np.s_[:self.size]\n\n idp = self['idp'][idx]\n dpt = (1.0 / idp)\n\n # update derived parameters cache\n self['dpt'][idx] = dpt\n self['pos'][idx] = self.compute_pt3(\n src=self['src'][idx],\n vec=self['vec'][idx],\n idp=self['idp'][idx])\n\n lsf = np.float32([self.s_pyr_[e] for e in self['oct'][idx]])\n mxd = dpt * lsf\n mnd = mxd / self.s_pyr_[-1]\n self['mxd'][idx] = mxd\n self['mnd'][idx] = mnd\n\n def update(self, idx,\n src_new=None,\n dpt_new=None,\n var_new=None,\n hard=False):\n\n if src_new is not None:\n # This will usually happen after BA\n self['src'][idx] = src_new\n\n if var_new is 'auto':\n var_new = 0.1 * dpt_new\n\n if hard:\n # total overwrite, {idp,var}\n self['idp'][idx] = (1.0 / dpt_new)\n if var_new is not None:\n self['var'][idx] = var_new\n else:\n # incorporate previous information\n # requires var_new != None\n\n idp_old = self['idp'][idx]\n var_old = self['var'][idx]\n\n idp_new = (1.0 / dpt_new)\n vsum = var_old + var_new\n\n # apply standard gaussian product\n idp = (idp_old * var_new + idp_new * var_old) / (vsum)\n var = (var_old * var_new) / (vsum)\n\n self['idp'][idx] = idp\n self['var'][idx] = var\n\n self['cnt'][idx] += 1\n\n self._update_cache()\n\n def prune(self, k=8, radius=0.05, keep_last=512):\n \"\"\"\n Non-max suppression based pruning.\n set k=1 to disable nmx. --> TODO: verify this\n \"\"\"\n # TODO : Tune keep_last parameter\n # TODO : sometimes pruning can be too aggressive\n # and get rid of desirable landmarks.\n # TODO : if(num_added_landmarks_since_last > x) == lots of new info\n # search_and_add_keyframe()\n\n # NOTE: choose value to suppress with\n v = self['rsp']\n # v = 1.0 / self['var']\n\n neigh = NearestNeighbors(n_neighbors=k)\n neigh.fit(self['pos'])\n d, i = neigh.kneighbors(return_distance=True)\n # filter results by non-max suppression radius\n msk_d = np.min(d, axis=1) < radius\n\n # neighborhood count TODO : or np.sum() < 2?\n msk_v = np.all(v[i] <= v[:,None], axis=1)\n\n # protect recent observations.\n # keep latest N landmarks\n msk_t = np.arange(self.size_) > (self.size_ - keep_last)\n # and keep all landmarks added after last prune\n msk_t |= np.arange(self.size_) >= self.pidx_\n # also keep all currently tracked landmarks\n msk_t |= self['trk']\n\n # strong responses are preferrable and will be kept\n msk_r = np.greater(self['rsp'], 48) # TODO : somewhat magical\n\n # non-max results + response filter\n msk_n = (msk_d & msk_v) | (~msk_d & msk_r)\n\n # below expression describes the following heuristic:\n # if (new_landmark) keep;\n # else if (passed_non_max) keep;\n # else if (strong_descriptor) keep;\n #msk = msk_t | (msk_d & msk_v | ~msk_d) | (msk_r & ~msk_d)\n #msk = msk_t | ~msk_d | msk_v\n # msk = msk_t | (msk_n & (np.linalg.norm(self.pos) < 30.0)) \n\n msk = msk_t | (msk_n & ( (self['dpt'] < 30.0) ) ) # +enforce landmark bounds\n\n sz = msk.sum() # new size\n print('Landmarks Pruning : {}->{}'.format(msk.size, sz))\n\n self.data_[:sz] = self.data_[:self.size_][msk]\n\n self.size_ = sz\n self.pidx_ = self.size_\n\n # return pruned indices\n return np.where(msk)[0]\n\n def get_track(self):\n t_idx = np.where(self['trk'])[0]\n return t_idx, self['kpt'][t_idx]\n\n def untrack(self, idx):\n self['trk'][idx] = False\n\n def __getitem__(self, k):\n return self.data_[k][:self.size_]\n\n def __setitem__(self, k, v):\n self.data_[k][:self.size_] = v\n\n @property\n def size(self):\n return self.size_\n\n def draw(self, ax, *args, **kwargs):\n pt3_m = M.tx3(self.cvt_.T_c2b_, self['pos'])\n ax.plot(pt3_m[:,0], pt3_m[:,1], *args, **kwargs)\n\ndef main():\n \"\"\"\n VMap() Unit Test.\n\n Tests the following methods:\n .append()\n .update()\n .query()\n .prune()\n .get_track()\n .untrack()\n .draw()\n \"\"\"\n\n from utils.conversions import Conversions\n from utils import defaults as D\n from matplotlib import pyplot as plt\n\n fig = plt.figure()\n ax = fig.gca()\n\n orb = cv2.ORB_create(\n nfeatures=1024,\n scaleFactor=1.2,\n nlevels=8,\n # NOTE : scoretype here influences response-based filters.\n scoreType=cv2.ORB_FAST_SCORE,\n #scoreType=cv2.ORB_HARRIS_SCORE,\n )\n cvt = Conversions(\n D.K,\n D.D,\n D.T_c2b,\n det=orb,\n des=orb\n )\n cvt.initialize( (480, 640) )\n\n vmap = VMap(\n cvt=cvt,\n descriptor=orb\n )\n # test append\n src = np.random.uniform(size=3)\n dst = np.random.uniform(size=3)\n\n # generate random image + forge data\n img = np.random.uniform(low=0, high=255,\n size=(480,640,3)).astype(np.uint8)\n kpt = orb.detect(img)\n kpt, des = orb.compute(img, kpt)\n kpt = np.asarray(kpt, dtype=cv2.KeyPoint)\n\n ki = np.random.randint(0, len(des), size=32)\n kpt = kpt[ki]\n des = des[ki]\n\n dpt = np.random.uniform(0, 10, size=len(kpt))\n vec = np.einsum('ab,...b->...a',\n D.Ki, M.to_h([k.pt for k in kpt]))\n\n # pt3 is in src coord\n pt3 = dpt[:,None] * vec\n pt3_g = np.random.normal(dpt[:,None], scale=1.0) * vec\n # pt3_c0 is in camera odom coord\n pt3_c0 = cvt.cam_to_map(pt3, src)\n # pt3_m is in base_link map coord\n pt3_m = M.tx3(cvt.T_c2b_, pt3_c0)\n\n print('pt3-gt', pt3_c0[0])\n ax.plot(pt3_m[:,0], pt3_m[:,1], 'go', label='true')\n col = [img[int(k.pt[1]), int(k.pt[0])] for k in kpt]\n\n vmap.append(0, pt3_g, src,\n kpt, des, col)\n vmap.draw(ax, 'r^', label='pre')\n\n q = vmap.query(src=dst)\n #(pt2, pt3, des, var, cnt, idx) = q\n idx = q[-1]\n dpt = cvt.map_to_cam(pt3_c0[idx], dst)[:, 2]\n var = 0.01 * dpt\n vmap.update(idx,\n dpt_new = np.random.normal(dpt, scale=0.0),\n var_new = var)\n vmap.draw(ax, 'bx', label='post')\n\n vmap.prune(keep_last=0)\n vmap.untrack( np.random.randint(0, 32, 16) )\n #print vmap.get_track()\n\n vmap.prune(keep_last=0)\n vmap.draw(ax, 'c.', label='post-prune')\n\n ax.legend()\n plt.show()\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.empty_like", "numpy.logical_and.reduce", "matplotlib.pyplot.subplots", "numpy.linalg.norm", "numpy.ndim", "numpy.shape", "numpy.random.uniform", "matplotlib.pyplot.show", "numpy.where", "numpy.roll", "numpy.empty", "numpy.random.randint" ], [ "numpy.asarray", "numpy.dtype", "numpy.all", "numpy.where", "numpy.random.randint", "numpy.greater", "numpy.less", "numpy.arange", "numpy.logical_and.reduce", "numpy.float32", "numpy.ravel", "sklearn.neighbors.NearestNeighbors", "matplotlib.pyplot.figure", "numpy.min", "numpy.deg2rad", "matplotlib.pyplot.show", "numpy.abs", "numpy.random.normal", "numpy.random.uniform", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
multimodalspectroscopy/hypothermia-bayescmd
[ "94307593de7697140f7563f1b449f1f6165cd79b" ]
[ "results_processing/ABC/csv_processing.py" ]
[ "import os\nimport pandas as pd\nimport re\n\n\ndef sort_human(l):\n \"\"\"Sort a list of strings by numerical.\"\"\"\n def convert(text): return float(text) if text.isdigit() else text\n\n def alphanum(key): return [convert(c)\n for c in re.split('([-+]?[0-9]*\\.?[0-9]*)', key)]\n l.sort(key=alphanum)\n return l\n\n\ndef data_merge_by_batch(parent_directory, verbose=True):\n \"\"\"Merge a set of parameters.csv files into one.\n\n This is intended for use with batch processes from Legion, with each batch\n being 1000 runs longand numbered with integer values.\n\n Parameters\n ----------\n parent_directory : :obj:`list` of :obj:`str`\n Parent directory to a set of directories each containing model runs and\n a parameters.csv file.\n verbose : :obj:`boolean`, optional\n Boolean indicator of whether to print extra information.\n\n Returns\n -------\n None\n Concatenated will be written to file in `parent_directory`\n\n \"\"\"\n dirs = [os.path.abspath(os.path.join(parent_directory, d))\n for d in os.listdir(parent_directory)\n if os.path.isdir(os.path.abspath(\n os.path.join(parent_directory, d))) and d != 'archives']\n dirs = sort_human(dirs)\n if verbose:\n print(dirs)\n dfs = []\n for d in dirs:\n try:\n dfs.append(pd.read_csv(os.path.join(d, 'parameters.csv')))\n ii = len(dfs) - 1\n print(\"Processing parameter file {}\".format(ii))\n if ii is not 0:\n dfs[ii]['ix'] = dfs[ii].index.values + \\\n dfs[ii - 1]['ix'].values[-1] + 1\n else:\n dfs[ii]['ix'] = dfs[ii].index.values\n\n if os.path.split(d)[1].split('_')[-1].isdigit():\n print(os.path.split(d)[1].split('_')[-1])\n dfs[ii]['Batch'] = int(os.path.split(d)[1].split('_')[-1])\n else:\n print(\"Batch number not found for {}\".format(d))\n continue\n except FileNotFoundError:\n print(\"No parameters file in {}\".format(d))\n continue\n if verbose:\n print(\"{} dataframes to be joined\".format(len(dfs)))\n # for ii in range(len(dfs)):\n # if ii is not 0:\n # dfs[ii]['ix'] = dfs[ii].index.values + dfs[ii - 1]['ix'].values[-1]\n # else:\n # dfs[ii]['ix'] = dfs[ii].index.values\n # if os.path.split(dirs[ii])[1][:4].isdigit():\n # print(os.path.split(dirs[ii])[1][:4])\n # dfs[ii]['Start Time'] = os.path.split(dirs[ii])[1][:4]\n # else:\n # continue\n df = pd.concat(dfs)\n df.index = range(len(df))\n output_file = os.path.join(parent_directory,\n 'all_parameters.csv')\n df.to_csv(output_file, index=False)\n\n return output_file\n" ]
[ [ "pandas.concat" ] ]
[ { "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": [] } ]
DanielTakeshi/baselines-fork
[ "7ac6f52ff21f43c519e01179740c019bbe1c55bf" ]
[ "baselines/imit/memory.py" ]
[ "\"\"\"Similar to DDPG except we only need obs and act, not the reward, etc.\n\"\"\"\nimport numpy as np\n\n\nclass RingBuffer(object):\n\n def __init__(self, maxlen, shape, dtype='float32'):\n self.maxlen = maxlen\n self.start = 0\n self.length = 0\n if dtype == 'uint8':\n # Daniel: special case with our XP replay. Force memory allocation\n # right away by the += 0 op, to check that system has enough RAM.\n # Might not be good for speed so we'll have to time it.\n self.data = np.zeros((maxlen,) + shape, dtype=np.uint8)\n print(\"Allocating data of size {} ...\".format(self.data.shape))\n self.data += 0\n else:\n self.data = np.zeros((maxlen,) + shape).astype(dtype)\n # Daniel: avoid over-writing teacher samples.\n self.teach_idx = 0\n\n def __len__(self):\n return self.length\n\n def __getitem__(self, idx):\n # Daniel: we shouldn't be calling this if it's using our DDPG/IMIT.\n assert self.teach_idx == 0, \\\n 'Something went wrong, why are we calling this method?'\n if idx < 0 or idx >= self.length:\n raise KeyError()\n return self.data[(self.start + idx) % self.maxlen]\n\n def get_batch(self, idxs):\n #return self.data[(self.start + idxs) % self.maxlen]\n # Daniel: seems like it's just fine to do this. It's the responsibility\n # of the caller to call a valid set of indices. And we do that with\n # randint in the memory class later. Here we avoid headaches with\n # `self.start` because I restrict it to be at least the teach_idx.\n return self.data[idxs]\n\n def append(self, v, is_teacher=False):\n if self.length < self.maxlen:\n # We have space, simply increase the length.\n self.length += 1\n if is_teacher:\n self.teach_idx += 1\n elif self.length == self.maxlen:\n # No space, \"remove\" the first item.\n #self.start = (self.start + 1) % self.maxlen\n self.start = max(self.teach_idx, (self.start + 1) % self.maxlen)\n else:\n # This should never happen.\n raise RuntimeError()\n self.data[(self.start + self.length - 1) % self.maxlen] = v\n\n\ndef array_min2d(x):\n x = np.array(x)\n if x.ndim >= 2:\n return x\n return x.reshape(-1, 1)\n\n\nclass Memory(object):\n\n def __init__(self, limit, action_shape, observation_shape, dtype='float32',\n do_valid=False):\n \"\"\"Daniel: careful about RAM usage. See:\n https://github.com/BerkeleyAutomation/baselines-fork/issues/9\n\n For this we can assume that in the replay buffer, the teacher samples\n come first, and are fixed ahead of time, so our 'starting' index for\n adding into the replay buffer should be offset by this quantity.\n \"\"\"\n self.limit = limit\n self.do_valid = do_valid\n if self.do_valid:\n self.valid_frac = 0.2\n self.nb_valid_items = 0 # will adjust later\n self.observations0 = RingBuffer(limit, shape=observation_shape, dtype=dtype)\n self.actions = RingBuffer(limit, shape=action_shape)\n self.nb_teach = 0\n self.done_adding_teach = False\n\n def sample(self, batch_size):\n # Draw such that we always have a proceeding element.\n # TODO(Daniel): the -2 doesn't make sense, we don't need a proceeding\n # element because the next observation is in a separate ring buffer?? I\n # think it should be nb_entries, so we are in practice not sampling the\n # last two items in this replay buffer. I'm switching to -1, should do\n # 0 later if I'm confident we're not ignoring anything else ...\n if self.do_valid:\n # If we're doing validation, which should NOT normally be true,\n # ignore the first few items, which we assign to be in validation.\n batch_idxs = np.random.randint(self.nb_valid_items,\n self.nb_entries-1,\n size=batch_size)\n else:\n batch_idxs = np.random.randint(self.nb_entries-1, size=batch_size)\n\n obs0_batch = self.observations0.get_batch(batch_idxs)\n action_batch = self.actions.get_batch(batch_idxs)\n\n # Assume `x < self.nb_teach` (not equality!) is a teacher sample.\n flag_teacher = (batch_idxs < self.nb_teach).astype(np.float32)\n\n result = {\n 'obs0': array_min2d(obs0_batch),\n 'actions': array_min2d(action_batch),\n 'flag_teacher': array_min2d(flag_teacher),\n }\n return result\n\n def append(self, obs0, action, is_teacher=False, training=True):\n \"\"\"Keep separate copies of obs0, obs1. So it's not memory efficient.\n \"\"\"\n if not training:\n return\n if is_teacher:\n assert not self.done_adding_teach, self.nb_teach\n assert self.nb_teach < self.limit, self.nb_teach\n self.nb_teach += 1\n self.observations0.append(obs0, is_teacher)\n self.actions.append(action, is_teacher)\n\n def set_teacher_idx(self):\n \"\"\"Call from IMIT so we do not over-write teacher data.\n \"\"\"\n self.done_adding_teach = True\n\n def set_valid_idx(self):\n \"\"\"Set the validation index.\n \"\"\"\n assert self.done_adding_teach\n self.nb_valid_items = int(self.valid_frac * self.nb_entries)\n\n @property\n def nb_entries(self):\n return len(self.observations0)\n\n @property\n def nb_teach_entries(self):\n return self.nb_teach\n\n @property\n def nb_valid(self):\n return self.nb_valid_items\n\n def get_valid_obs(self, s_idx, e_idx):\n \"\"\"Get a validation minibatch with fixed starting and ending indices.\n \"\"\"\n assert self.do_valid\n batch_idxs = np.arange(s_idx, e_idx)\n obs0_batch = self.observations0.get_batch(batch_idxs)\n action_batch = self.actions.get_batch(batch_idxs)\n result = {\n 'obs0': array_min2d(obs0_batch),\n 'actions': array_min2d(action_batch),\n }\n return result\n" ]
[ [ "numpy.arange", "numpy.array", "numpy.zeros", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
nishaero/wifi-userseg-ryu
[ "1132f2c813b79eff755bdd1a9e73e7ad3980af7c" ]
[ "lib/python2.7/site-packages/networkx/algorithms/centrality/current_flow_betweenness_subset.py" ]
[ "\"\"\"\nCurrent-flow betweenness centrality measures for subsets of nodes.\n\"\"\"\n# Copyright (C) 2010-2011 by \n# Aric Hagberg <[email protected]>\n# Dan Schult <[email protected]>\n# Pieter Swart <[email protected]>\n# All rights reserved.\n# BSD license.\n__author__ = \"\"\"Aric Hagberg ([email protected])\"\"\"\n\n__all__ = ['current_flow_betweenness_centrality_subset',\n 'edge_current_flow_betweenness_centrality_subset']\n\nimport itertools\nimport networkx as nx\nfrom networkx.algorithms.centrality.flow_matrix import *\n\n\ndef current_flow_betweenness_centrality_subset(G,sources,targets,\n normalized=True,\n weight='weight',\n dtype=float, solver='lu'):\n r\"\"\"Compute current-flow betweenness centrality for subsets of nodes.\n\n Current-flow betweenness centrality uses an electrical current\n model for information spreading in contrast to betweenness\n centrality which uses shortest paths.\n\n Current-flow betweenness centrality is also known as\n random-walk betweenness centrality [2]_.\n\n Parameters\n ----------\n G : graph\n A NetworkX graph \n\n sources: list of nodes\n Nodes to use as sources for current\n\n targets: list of nodes\n Nodes to use as sinks for current\n\n normalized : bool, optional (default=True)\n If True the betweenness values are normalized by b=b/(n-1)(n-2) where\n n is the number of nodes in G.\n\n weight : string or None, optional (default='weight')\n Key for edge data used as the edge weight.\n If None, then use 1 as each edge weight.\n\n dtype: data type (float)\n Default data type for internal matrices.\n Set to np.float32 for lower memory consumption.\n\n solver: string (default='lu')\n Type of linear solver to use for computing the flow matrix.\n Options are \"full\" (uses most memory), \"lu\" (recommended), and \n \"cg\" (uses least memory).\n\n Returns\n -------\n nodes : dictionary\n Dictionary of nodes with betweenness centrality as the value.\n \n See Also\n --------\n approximate_current_flow_betweenness_centrality\n betweenness_centrality\n edge_betweenness_centrality\n edge_current_flow_betweenness_centrality\n\n Notes\n -----\n Current-flow betweenness can be computed in `O(I(n-1)+mn \\log n)`\n time [1]_, where `I(n-1)` is the time needed to compute the \n inverse Laplacian. For a full matrix this is `O(n^3)` but using\n sparse methods you can achieve `O(nm{\\sqrt k})` where `k` is the\n Laplacian matrix condition number. \n\n The space required is `O(nw) where `w` is the width of the sparse\n Laplacian matrix. Worse case is `w=n` for `O(n^2)`.\n\n If the edges have a 'weight' attribute they will be used as \n weights in this algorithm. Unspecified weights are set to 1.\n\n References\n ----------\n .. [1] Centrality Measures Based on Current Flow. \n Ulrik Brandes and Daniel Fleischer,\n Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05). \n LNCS 3404, pp. 533-544. Springer-Verlag, 2005. \n http://www.inf.uni-konstanz.de/algo/publications/bf-cmbcf-05.pdf\n\n .. [2] A measure of betweenness centrality based on random walks,\n M. E. J. Newman, Social Networks 27, 39-54 (2005).\n \"\"\"\n from networkx.utils import reverse_cuthill_mckee_ordering \n try:\n import numpy as np\n except ImportError:\n raise ImportError('current_flow_betweenness_centrality requires NumPy ',\n 'http://scipy.org/')\n try:\n import scipy \n except ImportError:\n raise ImportError('current_flow_betweenness_centrality requires SciPy ',\n 'http://scipy.org/')\n if G.is_directed():\n raise nx.NetworkXError('current_flow_betweenness_centrality() ',\n 'not defined for digraphs.')\n if not nx.is_connected(G):\n raise nx.NetworkXError(\"Graph not connected.\")\n n = G.number_of_nodes()\n ordering = list(reverse_cuthill_mckee_ordering(G))\n # make a copy with integer labels according to rcm ordering\n # this could be done without a copy if we really wanted to\n mapping=dict(zip(ordering,range(n)))\n H = nx.relabel_nodes(G,mapping)\n betweenness = dict.fromkeys(H,0.0) # b[v]=0 for v in H\n for row,(s,t) in flow_matrix_row(H, weight=weight, dtype=dtype, \n solver=solver):\n for ss in sources:\n i=mapping[ss]\n for tt in targets:\n j=mapping[tt]\n betweenness[s]+=0.5*np.abs(row[i]-row[j]) \n betweenness[t]+=0.5*np.abs(row[i]-row[j]) \n if normalized:\n nb=(n-1.0)*(n-2.0) # normalization factor\n else:\n nb=2.0\n for v in H:\n betweenness[v]=betweenness[v]/nb+1.0/(2-n)\n return dict((ordering[k],v) for k,v in betweenness.items())\n\n\ndef edge_current_flow_betweenness_centrality_subset(G, sources, targets,\n normalized=True, \n weight='weight',\n dtype=float, solver='lu'):\n \"\"\"Compute current-flow betweenness centrality for edges using subsets \n of nodes.\n\n Current-flow betweenness centrality uses an electrical current\n model for information spreading in contrast to betweenness\n centrality which uses shortest paths.\n\n Current-flow betweenness centrality is also known as\n random-walk betweenness centrality [2]_.\n\n Parameters\n ----------\n G : graph\n A NetworkX graph \n\n sources: list of nodes\n Nodes to use as sources for current\n\n targets: list of nodes\n Nodes to use as sinks for current\n\n normalized : bool, optional (default=True)\n If True the betweenness values are normalized by b=b/(n-1)(n-2) where\n n is the number of nodes in G.\n\n weight : string or None, optional (default='weight')\n Key for edge data used as the edge weight.\n If None, then use 1 as each edge weight.\n\n dtype: data type (float)\n Default data type for internal matrices.\n Set to np.float32 for lower memory consumption.\n\n solver: string (default='lu')\n Type of linear solver to use for computing the flow matrix.\n Options are \"full\" (uses most memory), \"lu\" (recommended), and \n \"cg\" (uses least memory).\n\n Returns\n -------\n nodes : dictionary\n Dictionary of edge tuples with betweenness centrality as the value.\n \n See Also\n --------\n betweenness_centrality\n edge_betweenness_centrality\n current_flow_betweenness_centrality\n\n Notes\n -----\n Current-flow betweenness can be computed in `O(I(n-1)+mn \\log n)`\n time [1]_, where `I(n-1)` is the time needed to compute the \n inverse Laplacian. For a full matrix this is `O(n^3)` but using\n sparse methods you can achieve `O(nm{\\sqrt k})` where `k` is the\n Laplacian matrix condition number. \n\n The space required is `O(nw) where `w` is the width of the sparse\n Laplacian matrix. Worse case is `w=n` for `O(n^2)`.\n\n If the edges have a 'weight' attribute they will be used as \n weights in this algorithm. Unspecified weights are set to 1.\n\n References\n ----------\n .. [1] Centrality Measures Based on Current Flow. \n Ulrik Brandes and Daniel Fleischer,\n Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05). \n LNCS 3404, pp. 533-544. Springer-Verlag, 2005. \n http://www.inf.uni-konstanz.de/algo/publications/bf-cmbcf-05.pdf\n\n .. [2] A measure of betweenness centrality based on random walks, \n M. E. J. Newman, Social Networks 27, 39-54 (2005).\n \"\"\"\n from networkx.utils import reverse_cuthill_mckee_ordering \n try:\n import numpy as np\n except ImportError:\n raise ImportError('current_flow_betweenness_centrality requires NumPy ',\n 'http://scipy.org/')\n try:\n import scipy \n except ImportError:\n raise ImportError('current_flow_betweenness_centrality requires SciPy ',\n 'http://scipy.org/')\n if G.is_directed():\n raise nx.NetworkXError('edge_current_flow_betweenness_centrality ',\n 'not defined for digraphs.')\n if not nx.is_connected(G):\n raise nx.NetworkXError(\"Graph not connected.\")\n n = G.number_of_nodes()\n ordering = list(reverse_cuthill_mckee_ordering(G))\n # make a copy with integer labels according to rcm ordering\n # this could be done without a copy if we really wanted to\n mapping=dict(zip(ordering,range(n)))\n H = nx.relabel_nodes(G,mapping)\n betweenness=(dict.fromkeys(H.edges(),0.0))\n if normalized:\n nb=(n-1.0)*(n-2.0) # normalization factor\n else:\n nb=2.0\n for row,(e) in flow_matrix_row(H, weight=weight, dtype=dtype, \n solver=solver):\n for ss in sources:\n i=mapping[ss]\n for tt in targets:\n j=mapping[tt]\n betweenness[e]+=0.5*np.abs(row[i]-row[j]) \n betweenness[e]/=nb\n return dict(((ordering[s],ordering[t]),v) \n for (s,t),v in betweenness.items())\n\n\n# fixture for nose tests\ndef setup_module(module):\n from nose import SkipTest\n try:\n import numpy\n import scipy\n except:\n raise SkipTest(\"NumPy not available\")\n\n" ]
[ [ "numpy.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ptrbortolotti/pCrunch
[ "df2488891d8a0d884cb90edd5bb0412ac0af248f", "df2488891d8a0d884cb90edd5bb0412ac0af248f" ]
[ "runBatch/run_FlapGainSweep_BAR.py", "pCrunch/pdTools.py" ]
[ "\"\"\"\nA python script to run a parameter sweep\n\"\"\"\n# Python tools\nimport numpy as np\nimport yaml\nimport os\n# WISDEM tools\nfrom wisdem.aeroelasticse import runFAST_pywrapper, CaseGen_General\nfrom wisdem.aeroelasticse.Util import FileTools\n# ROSCO tools\nfrom ROSCO_toolbox import controller as ROSCO_controller\nfrom ROSCO_toolbox import turbine as ROSCO_turbine\nfrom ROSCO_toolbox import utilities as ROSCO_utilities\nfrom pCrunch import CaseGen_Control, Analysis, Processing\n\n# FLAGS\neagle = True\nmulti = False\n\n# Controller tuning yaml\nif eagle:\n parameter_filename = '/home/nabbas/Documents/TurbineModels/ControllerYamls/BAR.yaml'\nelse: \n parameter_filename = '../../Turbine_Tuning/BAR/BAR.yaml'\n\n# Generate case inputs for control related stuff\ninput_params = ['zeta_flp', 'omega_flp']\nDISCON_params = ['Flp_Kp', 'Flp_Ki']\n# values = [[0.7], [2.73]]\nvalues = [np.around(np.arange(0.5, 2.5, 0.05), decimals=3), # use np.around to avoid precision issues\n np.around(np.arange(2.2, 3.5, 0.05) , decimals=3)]\ngroup = 1\n\n# Some path specifics/\nif eagle:\n FAST_InputFile = 'BAR_10p_75s.fst' # FAST input file (ext=.fst)\n FAST_directory = '/projects/bar/nabbas/TurbineModels/BAR_10p_75s'\n FAST_runDirectory = '/projects/bar/nabbas/batch_GainSweep_10p_75s_2'\n wind_dir = '/projects/bar/nabbas/TurbineModels/wind'\n dll_filename = '/home/nabbas/ROSCO_toolbox/ROSCO/build/libdiscon.so'\n Turbsim_exe = 'turbsim'\n FAST_exe = 'openfast'\nelse:\n FAST_InputFile = 'OpenFAST_BAR_10.fst' # FAST input file (ext=.fst)\n FAST_directory = '/Users/nabbas/Documents/TurbineModels/BAR/OpenFAST_Models/BAR_10/'\n FAST_runDirectory = 'temp' \n wind_dir = '/Users/nabbas/Documents/TurbineModels/BAR/wind'\n dll_filename = '/Users/nabbas/Documents/TurbineModels/TurbineControllers/FortranControllers/ROSCO/build/libdiscon.dylib'\n Turbsim_exe = 'turbsim_dev'\n FAST_exe = 'openfast_dev'\n\ncase_name_base = 'BAR_10p_75s'\ndebug_level = 2\n\n\n# Wind\nWindType = [3]\nUref = [8.25, 10.25]\nseeds = [13428, 1524]\n\n# Time\nTMax = 330\n\n# Turbine Definition\nD = 206 # Rotor Diameter\nz_hub = 137 # Tower Height\n\n# Multiprocessing/Eagle related\nif eagle:\n cores = 36\nelse:\n cores = 4\n\n# Initialize CaseGen\ncgc = CaseGen_Control.CaseGen_Control(parameter_filename)\n\n# Modify some parameters\ncgc.path_params['FAST_InputFile'] = FAST_InputFile\ncgc.path_params['FAST_directory'] = FAST_directory\ncgc.AnalysisTime = TMax\ncgc.case_name_base = case_name_base\ncgc.D = D\ncgc.z_hub = z_hub\ncgc.debug_level = debug_level\n\ncgc.overwrite = True\n# Generate wind speeds\ncgc.seeds = seeds\ncgc.wind_dir = wind_dir\ncgc.Turbsim_exe = Turbsim_exe\nwind_file, wind_file_type = cgc.gen_turbwind(Uref)\n\n\n# Generate control case inputs\n# NOTE: Usually, group=1 is easiest. Then some baseline characteristics in group 0, etc...\ncase_inputs, tuning_inputs = cgc.gen_control_cases(input_params, DISCON_params, values, group)\n\n# Add time specification if group 0\nif group == 0:\n ci_key = list(case_inputs.keys())[0]\n TMax_list = [TMax]*len(case_inputs[ci_key]['vals'])\n case_inputs[(\"Fst\", \"TMax\")] = {'vals': TMax_list, 'group': 0}\nelse:\n case_inputs[(\"Fst\", \"TMax\")] = {'vals': [TMax], 'group': 0}\n\n# DISCON\ncase_inputs[('ServoDyn', 'DLL_FileName')] = {'vals': [dll_filename], 'group': 0}\n\n# Wind\ncase_inputs[(\"InflowWind\", \"WindType\")] = {'vals': [wind_file_type], 'group': 0}\ncase_inputs[(\"InflowWind\", \"Filename\")] = {'vals': [wind_file], 'group': 0}\n\n# FAST details\nfastBatch = runFAST_pywrapper.runFAST_pywrapper_batch(FAST_ver='OpenFAST', dev_branch=True)\nfastBatch.FAST_exe = FAST_exe # Path to executable\nfastBatch.FAST_InputFile = FAST_InputFile\nfastBatch.FAST_directory = FAST_directory\nfastBatch.FAST_runDirectory = FAST_runDirectory\nfastBatch.debug_level = debug_level\n\n# Generate cases\ncase_list, case_name_list = CaseGen_General.CaseGen_General(\n case_inputs, dir_matrix=fastBatch.FAST_runDirectory, namebase=case_name_base)\n\n# Append case matrix with controller tuning parameters\nfor file in os.listdir(fastBatch.FAST_runDirectory):\n if file.endswith(\".yaml\"):\n yfile = file\n yamldata = FileTools.load_yaml(os.path.join(fastBatch.FAST_runDirectory, yfile), package=1)\n\nCaseGen_Control.append_case_matrix_yaml(\n fastBatch.FAST_runDirectory, yfile, tuning_inputs, 'tuning_inputs')\n\n# Make sure flags are on\nvar_out = [\n # ElastoDyn\n \"BldPitch1\", \"BldPitch2\", \"BldPitch3\", \"Azimuth\", \"RotSpeed\", \"GenSpeed\", \"NacYaw\",\n \"OoPDefl1\", \"IPDefl1\", \"TwstDefl1\", \"OoPDefl2\", \"IPDefl2\", \"TwstDefl2\", \"OoPDefl3\",\n \"IPDefl3\", \"TwstDefl3\", \"TwrClrnc1\", \"TwrClrnc2\", \"TwrClrnc3\", \"NcIMUTAxs\", \"NcIMUTAys\",\n \"NcIMUTAzs\", \"TTDspFA\", \"TTDspSS\", \"TTDspTwst\", \"PtfmSurge\", \"PtfmSway\", \"PtfmHeave\",\n \"PtfmRoll\", \"PtfmPitch\", \"PtfmYaw\", \"PtfmTAxt\", \"PtfmTAyt\", \"PtfmTAzt\", \"RootFxc1\",\n \"RootFyc1\", \"RootFzc1\", \"RootMxc1\", \"RootMyc1\", \"RootMzc1\", \"RootFxc2\", \"RootFyc2\",\n \"RootFzc2\", \"RootMxc2\", \"RootMyc2\", \"RootMzc2\", \"RootFxc3\", \"RootFyc3\", \"RootFzc3\",\n \"RootMxc3\", \"RootMyc3\", \"RootMzc3\", \"Spn1MLxb1\", \"Spn1MLyb1\", \"Spn1MLzb1\", \"Spn1MLxb2\",\n \"Spn1MLyb2\", \"Spn1MLzb2\", \"Spn1MLxb3\", \"Spn1MLyb3\", \"Spn1MLzb3\", \"RotThrust\", \"LSSGagFya\",\n \"LSSGagFza\", \"RotTorq\", \"LSSGagMya\", \"LSSGagMza\", \"YawBrFxp\", \"YawBrFyp\", \"YawBrFzp\",\n \"YawBrMxp\", \"YawBrMyp\", \"YawBrMzp\", \"TwrBsFxt\", \"TwrBsFyt\", \"TwrBsFzt\", \"TwrBsMxt\",\n \"TwrBsMyt\", \"TwrBsMzt\", \"TwHt1MLxt\", \"TwHt1MLyt\", \"TwHt1MLzt\",\n # ServoDyn\n \"GenPwr\", \"GenTq\",\n # AeroDyn15\n \"RtArea\", \"RtVAvgxh\", \"B1N3Clrnc\", \"B2N3Clrnc\", \"B3N3Clrnc\",\n \"RtAeroCp\", 'RtAeroCq', 'RtAeroCt', 'RtTSR',\n # InflowWind\n \"Wind1VelX\", \"Wind1VelY\", \"Wind1VelZ\",\n # FLAPS\n # \"BLFLAP1\", \"BLFLAP2\", \"BLFLAP3\", \"RtVAvgxh\", \"OoPDefl1\")\n]\nchannels = {}\nfor var in var_out:\n channels[var] = True\nfastBatch.channels = channels\n\nfastBatch.case_list = case_list\nfastBatch.case_name_list = case_name_list\n\nif multi:\n fastBatch.run_multi(cores)\n # fastBatch.run_mpi()\nelse:\n fastBatch.run_serial()\n\n\n\n# Post processing\ncase_info = FileTools.load_yaml(FAST_runDirectory + '/case_matrix.yaml', package=1)\noutfiles = [FAST_runDirectory + fname + '.outb' for fname in case_info['Case_Name']]\n\nfp = Processing.FAST_Processing()\nfp.OpenFAST_outfile_list = outfiles\nfp.t0 = 30\nfp.parallel_analysis = True\nfp.verbose=True\nfp.results_dir = os.path.join(run_dir,'stats') \nfp.save_LoadRanking = True\nfp.save_SummaryStats = True\nstats, load_ranking = fp.batch_processing()\n", "'''\nSome tools to ease management of batch analysis data in pandas\n'''\nimport pandas as pd\nfrom pCrunch import Processing\n\ndef dict2df(sumstats, names=None):\n '''\n Build pandas datafrom from list of summary statistics\n\n Inputs:\n -------\n sumstats: list\n List of the dictionaries loaded from post_process.load_yaml\n names: list, optional\n List of names for each run. len(sumstats)=len(names)\n\n Returns:\n --------\n df: pd.DataFrame\n pandas dataframe \n '''\n if isinstance(sumstats, list):\n if not names:\n names = ['dataset_' + str(i) for i in range(len(sumstats))]\n data_dict = {(name, outerKey, innerKey): values \n for name, sumdata in zip(names, sumstats)\n for outerKey, innerDict in sumdata.items() \n for innerKey, values in innerDict.items()}\n else:\n data_dict = {(outerKey, innerKey): values \n for outerKey, innerDict in sumstats.items()\n for innerKey, values in innerDict.items()}\n\n # Make dataframe\n df = pd.DataFrame(data_dict)\n\n return df\n\n\ndef df2dict(df):\n '''\n Build dictionary from pandas dataframe\n\n Parameters:\n -----------\n df: DataFrame\n DataFrame with summary stats (probably). Cannot have len(multiindex) > 3\n\n Returns:\n --------\n dfd: dict\n dictionary containing re-structured dataframe inputs\n '''\n if len(df.columns[0]) == 3:\n dfd = [{level: df.xs(dset, axis=1).xs(level, axis=1).to_dict('list')\n for level in df.columns.levels[1]} \n for dset in df.columns.levels[0]]\n elif len(df.columns[0]) == 2:\n dfd = {level: df.xs(dset, axis=1).xs(level, axis=1).to_dict('list')\n for level in df.columns.levels[0]} \n elif len(df.columns[0]) == 1:\n dfd = df.to_dict('list')\n else:\n raise TypeError('Converting DataFrames with multiindex > 3 to dictionaries is not supported')\n\n return dfd\n\ndef yaml2df(filename, names=[]):\n '''\n Read yaml containing summary stats into dataframe\n\n Parameters:\n -------\n filename:\n Name of yaml file to load. \n\n '''\n\n data_dict = Processing.load_yaml('test.yaml', package=0)\n\n level = data_dict\n li = 0 # level index\n while isinstance(level, dict):\n li = li + 1\n if isinstance(level, dict):\n level = level[list(level.keys())[0]]\n\n data_list = []\n if li == 3:\n for key in data_dict.keys():\n data_list.append(data_dict[key])\n if not names:\n names = ['dataset_' + str(i) for i in range(len(data_list))]\n\n elif li == 2:\n data_list.append(data_dict)\n names = []\n else:\n raise TypeError('{} is improperly structured for yaml2df.'.format(filename))\n\n df = dict2df(data_list, names=names)\n\n return df\n" ]
[ [ "numpy.arange" ], [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
lphxx6222712/MSAN_Retina
[ "7723fbfe7c6fcd4e310beb8b776a9057af62a2f1" ]
[ "utils/FocalLoss.py" ]
[ "import torch\nimport torch.nn as nn\n\ndef clip_by_tensor(t, t_min, t_max):\n\n result = (t>=t_min)*t+(t<t_min)*t_min\n result = (result<=t_max)*result+(result>t_max)*t_max\n return result\n\nclass FocalLoss(nn.Module):\n\n def __init__(self, gamma=2, alpha=0.25):\n super(FocalLoss, self).__init__()\n self.gamma = gamma\n self.alpha = alpha\n\n def forward(self, prediction_tensor, target_tensor):\n alpha = self.alpha\n gamma = self.gamma\n # input:size is M*2. M is the batch number\n\n \"\"\"Compute focal loss for predictions.\n Multi-labels Focal loss formula:\n FL = -alpha * (z-p)^gamma * log(p) -(1-alpha) * p^gamma * log(1-p)\n ,which alpha = 0.25, gamma = 2, p = sigmoid(x), z = target_tensor.\n Args:\n prediction_tensor: A float tensor of shape [batch_size, num_anchors,\n num_classes] representing the predicted logits for each class\n target_tensor: A float tensor of shape [batch_size, num_anchors,\n num_classes] representing one-hot encoded classification targets\n weights: A float tensor of shape [batch_size, num_anchors]\n alpha: A scalar tensor for focal loss alpha hyper-parameter\n gamma: A scalar tensor for focal loss gamma hyper-parameter\n Returns:\n loss: A (scalar) tensor representing the value of the loss function\n \"\"\"\n sigmoid_p = torch.sigmoid(prediction_tensor)\n zeros = torch.zeros_like(sigmoid_p, dtype=sigmoid_p.dtype)\n\n # For poitive prediction, only need consider front part loss, back part is 0;\n # target_tensor > zeros <=> z=1, so poitive coefficient = z - p.\n pos_p_sub = torch.where(target_tensor > zeros, target_tensor - sigmoid_p, zeros)\n\n # For negative prediction, only need consider back part loss, front part is 0;\n # target_tensor > zeros <=> z=1, so negative coefficient = 0.\n neg_p_sub = torch.where(target_tensor > zeros, zeros, sigmoid_p)\n per_entry_cross_ent = - alpha * (pos_p_sub ** gamma) * torch.log(clip_by_tensor(sigmoid_p, 1e-8, 1.0)) \\\n - (1 - alpha) * (neg_p_sub ** gamma) * torch.log(clip_by_tensor(1.0 - sigmoid_p, 1e-8, 1.0))\n return per_entry_cross_ent.mean()" ]
[ [ "torch.sigmoid", "torch.zeros_like", "torch.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MTC-ETH/RecommenderSystems
[ "ede5aa961740348a68210f271397e1924c5f7cf6" ]
[ "preprocessing.py" ]
[ "# Copyright 2021 ETH Zurich, Media Technology Center\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 datetime\nimport os\n\nimport pandas as pd\n\"\"\"\nThis module is mainly used to transform the data from the partners into our desired format.\nIn the and only load_data and get_metadata is used in the algorithms.\n\"\"\"\n\n\ndef load_data(folder, input_path='user_item', cut=40,high_cut=1000000, seed=None):\n \"\"\"\n loads the training,validation,test set from the folder, restricts the users with at least \"cut\" read articles and\n returns the sets. The Format of the sets is pd.Series with index the UserID and value a list of ArticleIDs\n :param folder/input_path: {folder}/{input_path} is the path to look for the *_train.pkl files\n :param cut: value to cut off users with less than \"cut\" read articles\n :return: three pd.Series. Index of each series is the UserID. The value is a list of ArticleIDs.\n (look in create_split to see how the split is defines)\n \"\"\"\n # cut cuts off users that read less than cut articles\n\n user_item_train, user_item_test, user_item_validation = pd.read_pickle(\n f'{folder}/{input_path}_train.pkl'), pd.read_pickle(f'{folder}/{input_path}_test.pkl'), pd.read_pickle(\n f'{folder}/{input_path}_validation.pkl')\n\n user_item_train = user_item_train[user_item_train.str.len() > cut * 0.7]\n user_item_train = user_item_train[user_item_train.str.len() < high_cut * 0.7]\n user_item_test = user_item_test.loc[user_item_train.index]\n user_item_validation = user_item_validation.loc[user_item_train.index]\n\n return user_item_train, user_item_test, user_item_validation\n\ndef load_data_vertical(folder, input_path='user_item_vertical', cut=40):\n \"\"\"\n loads the training,validation,test set from the folder, restricts the users with at least \"cut\" read articles and\n returns the sets. The Format of the sets is pd.Series with index the UserID and value a list of ArticleIDs\n :param folder/input_path: {folder}/{input_path} is the path to look for the *_train.pkl files\n :param cut: value to cut off users with less than \"cut\" read articles\n :return: three pd.Series. Index of each series is the UserID. The value is a list of ArticleIDs.\n (look in create_split to see how the split is defines)\n \"\"\"\n # cut cuts off users that read less than cut articles\n\n user_item_train, user_item_test, user_item_validation = pd.read_parquet(\n f'{folder}/{input_path}_train.pq'), pd.read_parquet(f'{folder}/{input_path}_test.pq'), pd.read_parquet(\n f'{folder}/{input_path}_validation.pq')\n\n user_item_train = user_item_train[user_item_train['count'] >cut]\n user_item_test =user_item_test[user_item_test['count'] >cut]\n user_item_validation = user_item_validation[user_item_validation['count'] >cut]\n user_item_train['resource_id']=user_item_train['article_id']\n user_item_test['resource_id']=user_item_test['article_id']\n user_item_validation['resource_id']=user_item_validation['article_id']\n return user_item_train, user_item_test, user_item_validation\n\n\n\ndef load_data_cv(folder, input_path='user_item', cut=40, high_cut=100000,seed=1):\n \"\"\"\n Same as load_data but only returns random 80% of the training set\n \"\"\"\n # cut cuts off users that read less than cut articles\n user_item_train, user_item_test, user_item_validation = load_data(folder, input_path=input_path, cut=cut,high_cut=high_cut)\n user_item_train = user_item_train.sample(frac=0.8,random_state=seed)\n user_item_test = user_item_test.sample(frac=1, random_state=seed)\n return user_item_train, user_item_test, user_item_validation\n\ndef load_data_vertical_cv(folder, input_path='user_item_vertical', cut=40, high_cut=100000,seed=1):\n \"\"\"\n Same as load_data but only returns random 80% of the training set\n \"\"\"\n # cut cuts off users that read less than cut articles\n user_item_train, user_item_test, user_item_validation = load_data_vertical(folder, input_path=input_path, cut=cut)\n user_item_train = user_item_train.sample(frac=0.8,random_state=seed)\n user_item_test = user_item_test.sample(frac=1, random_state=seed)\n return user_item_train, user_item_test, user_item_validation\n\ndef get_metadata(folder, usecols=[]):\n \"\"\"\n Loads and returns the article metadata.\n The algorithms expect the format to be a Dataframe with two columns:\n - \"resource_id\": unique id for the article\n - \"text\": full text of the article (without html tags)\n \"\"\"\n if not usecols:\n usecols = ['text', 'resource_id']\n\n metadata = pd.read_csv(f\"{folder}/meta.csv\", usecols=usecols)\n\n return metadata.dropna(subset=['text'])\n\n\n\ndef transform_item_matrix_to_horizontal_format(folder, output_path='user_item_matrix.pkl',\n input_path='user_item_matrix_vertical.pq', sortby='ts'):\n \"\"\"\n Transforms vertical User-Item matrix where ich row is one click into a horizontal User-item matrix where we have\n one row for each user and each row contains a (sorted) list of articles she/he clicked on.\n :param folder: Input folder\n :param output_path: Filename/path for outputfile\n :param input_path: Filename/path for inputfile. This pickled file contains a DataFrame with three columns:\n \"user_ix\": the UserID and \"article_id\" the ArticleID and \"<sortby>\" which should be timestamp\n to sort by. Each UserID ArticleID pair indicates a click of the user on the article at a time.\n :param sortby: Columnname of the timestamp column to sort by\n :return: returns a Series where the index is the UserID and values is the by timestamp\n sorted list of clicked ArticleIDs\n \"\"\"\n now = datetime.datetime.now()\n matrices = pd.read_parquet(f\"{folder}/{input_path}\")\n grouped = matrices.sort_values(sortby).groupby(['user_ix']).apply(lambda x: list(x['article_id']))\n\n grouped.to_pickle(f\"{folder}/{output_path}\")\n print(f\"Data transformed {datetime.datetime.now() - now}\")\n\n\ndef create_split(folder, input_path='user_item_matrix.pkl', ouput_path='user_item', cut_dump=10):\n \"\"\"\n Loads the horizontal user item data from folder and creates a user-wise a 70% train, 20% validation, 10% test split.\n This means for each user the first 70% read articles are in the train the next 20% in validation and the last 10%\n read articles in the test set. We remove users with less than 10 clicked articles.\n This is the data that is loaded to train/test the models in the end.\n \"\"\"\n now = datetime.datetime.now()\n user_item = pd.read_pickle(f\"{folder}/{input_path}\")\n\n user_item = user_item[user_item.str.len() > (cut_dump)]\n\n user_item_train = user_item.apply(lambda x: x[:int(len(x) * 0.7)])\n user_item_test = user_item.apply(lambda x: x[int(len(x) * 0.7):int(len(x) * 0.9)])\n user_item_validation = user_item.apply(lambda x: x[int(len(x) * 0.9):])\n\n user_item_train.name = 'article_id'\n user_item_test.name = 'article_id'\n user_item_validation.name = 'article_id'\n\n user_item_train.to_pickle(f'{folder}/{ouput_path}_train.pkl')\n user_item_test.to_pickle(f'{folder}/{ouput_path}_test.pkl')\n user_item_validation.to_pickle(f'{folder}/{ouput_path}_validation.pkl')\n\n print(f\"Split created {datetime.datetime.now() - now}\")\n\ndef create_split_vertical(folder, input_path='user_item_matrix_vertical.pq', ouput_path='user_item_vertical', cut_dump=10,time_column='ts'):\n \"\"\"\n Loads the horizontal user item data from folder and creates a user-wise a 70% train, 20% validation, 10% test split.\n This means for each user the first 70% read articles are in the train the next 20% in validation and the last 10%\n read articles in the test set. We remove users with less than 10 clicked articles.\n This is the data that is loaded to train/test the models in the end.\n \"\"\"\n now = datetime.datetime.now()\n user_item = pd.read_parquet(f\"{folder}/{input_path}\").sort_values(time_column)\n user_item['count']=user_item.groupby(['user_ix']).article_id.transform('count')\n user_item = user_item[user_item['count']>cut_dump]\n grouped = user_item.groupby(['user_ix'])\n user_item['percentile'] = (grouped.article_id.cumcount() + 1) / grouped.article_id.transform('count')\n\n user_item_train = user_item[user_item['percentile']<=0.7]\n user_item_test = user_item[(user_item['percentile']>0.7) & (user_item['percentile']<0.9)]\n user_item_validation = user_item[user_item['percentile']>0.9]\n\n user_item_train.to_parquet(f'{folder}/{ouput_path}_train.pq')\n user_item_test.to_parquet(f'{folder}/{ouput_path}_test.pq')\n user_item_validation.to_parquet(f'{folder}/{ouput_path}_validation.pq')\n\n print(f\"Split created {datetime.datetime.now() - now}\")\n\n\n\ndef transform_horizontal_to_vertical(df):\n \"\"\"\n Transforms the horizontal format into vertical format\n :param df:\n :return:\n \"\"\"\n return df.explode().reset_index()\n\n\n\nif __name__ == \"__main__\":\n\n import pandas as pd\n folder = os.getenv('DATA_FOLDER','processed')\n # Transforms the user-item-matrix into a user-series. For each user we store the articles read as one sorted list.\n # Save the new format.\n # This format is more convenient for creating the split and for training some of the algorithms.\n transform_item_matrix_to_horizontal_format(folder=folder)\n # Create a train,test,validation split. 70%,10%,20% and save it\n create_split(folder=folder, cut_dump=10)\n create_split_vertical(folder=folder, cut_dump=10)\n\n # loads the saved train,validation,test split\n train, test, validation = load_data(folder=folder, cut=40)\n # # if you wish to transform into normal user-item-format\n # train_vertical = transform_horizontal_to_vertical(train)\n" ]
[ [ "pandas.read_parquet", "pandas.read_csv", "pandas.read_pickle" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
ranbir/tensorflow
[ "46924b2f7bc4262b2c4b36841d393741113594ca", "46924b2f7bc4262b2c4b36841d393741113594ca", "46924b2f7bc4262b2c4b36841d393741113594ca" ]
[ "tensorflow/python/autograph/impl/conversion_test.py", "tensorflow/python/keras/engine/distributed_training_utils.py", "tensorflow/python/autograph/impl/api_test.py" ]
[ "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for conversion module.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gast\n\nfrom tensorflow.python.autograph import utils\nfrom tensorflow.python.autograph.core import converter\nfrom tensorflow.python.autograph.impl import api\nfrom tensorflow.python.autograph.impl import conversion\nfrom tensorflow.python.autograph.pyct import compiler\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.keras.engine import training\nfrom tensorflow.python.platform import test\n\n\nclass ConversionTest(test.TestCase):\n\n def _simple_program_ctx(self):\n return converter.ProgramContext(\n options=converter.ConversionOptions(recursive=True),\n autograph_module=api)\n\n def test_is_whitelisted_for_graph(self):\n\n def test_fn():\n return constant_op.constant(1)\n\n self.assertFalse(conversion.is_whitelisted_for_graph(test_fn))\n self.assertTrue(conversion.is_whitelisted_for_graph(utils))\n self.assertTrue(conversion.is_whitelisted_for_graph(constant_op.constant))\n\n def test_entity_to_graph_unsupported_types(self):\n with self.assertRaises(NotImplementedError):\n program_ctx = self._simple_program_ctx()\n conversion.entity_to_graph('dummy', program_ctx, None, None)\n\n def test_entity_to_graph_callable(self):\n b = 2\n def f(a):\n return a + b\n\n program_ctx = self._simple_program_ctx()\n nodes, name, ns = conversion.entity_to_graph(f, program_ctx, None, None)\n fn_node, _ = nodes\n self.assertIsInstance(fn_node, gast.FunctionDef)\n self.assertEqual('tf__f', name)\n self.assertIs(ns['b'], b)\n\n def test_entity_to_graph_function_with_defaults(self):\n b = 2\n c = 1\n def f(a, d=c + 1):\n return a + b + d\n\n program_ctx = self._simple_program_ctx()\n nodes, name, _ = conversion.entity_to_graph(f, program_ctx, None, None)\n fn_node, _ = nodes\n self.assertIsInstance(fn_node, gast.FunctionDef)\n self.assertEqual('tf__f', name)\n self.assertEqual(\n compiler.ast_to_source(fn_node.args.defaults[0]).strip(), 'None')\n\n def test_entity_to_graph_call_tree(self):\n\n def g(a):\n return a\n\n def f(a):\n return g(a)\n\n program_ctx = self._simple_program_ctx()\n nodes, _, _ = conversion.entity_to_graph(f, program_ctx, None, None)\n f_node = nodes[0]\n self.assertEqual('tf__f', f_node.name)\n\n def test_entity_to_graph_class_hierarchy(self):\n\n class TestBase(object):\n\n def __init__(self, x='base'):\n self.x = x\n\n def foo(self):\n return self.x\n\n def bar(self):\n return self.x\n\n class TestSubclass(TestBase):\n\n def __init__(self, y):\n super(TestSubclass, self).__init__('sub')\n self.y = y\n\n def foo(self):\n return self.y\n\n def baz(self):\n return self.y\n\n program_ctx = self._simple_program_ctx()\n with self.assertRaisesRegex(NotImplementedError, 'classes.*whitelisted'):\n conversion.entity_to_graph(TestSubclass, program_ctx, None, None)\n\n def test_entity_to_graph_class_hierarchy_whitelisted(self):\n\n class TestSubclass(training.Model):\n\n def __init__(self, y):\n super(TestSubclass, self).__init__()\n self.built = False\n\n def call(self, x):\n return 3 * x\n\n program_ctx = self._simple_program_ctx()\n nodes, name, _ = conversion.entity_to_graph(TestSubclass, program_ctx, None,\n None)\n class_node = nodes[-2] # TODO(mdan): This is brittle.\n\n self.assertEqual(name, 'TfTestSubclass')\n self.assertEqual(class_node.name, 'TfTestSubclass')\n\n def test_entity_to_graph_lambda(self):\n b = 2\n f = lambda x: b * x if x > 0 else -x\n\n program_ctx = self._simple_program_ctx()\n nodes, name, ns = conversion.entity_to_graph(f, program_ctx, None, None)\n fn_node, _ = nodes\n self.assertIsInstance(fn_node, gast.Assign)\n self.assertIsInstance(fn_node.value, gast.Lambda)\n self.assertEqual('tf__lambda', name)\n self.assertIs(ns['b'], b)\n\n def test_entity_to_graph_multiple_lambdas(self):\n a, b = 1, 2\n f, _ = (lambda x: a * x, lambda y: b * y)\n\n program_ctx = self._simple_program_ctx()\n nodes, name, ns = conversion.entity_to_graph(f, program_ctx, None, None)\n fn_node, _ = nodes\n self.assertIsInstance(fn_node, gast.Assign)\n self.assertIsInstance(fn_node.value, gast.Lambda)\n self.assertEqual('tf__lambda', name)\n self.assertIs(ns['a'], a)\n\n def test_entity_to_graph_multiple_lambdas_ambiguous_definitions(self):\n a, b = 1, 2\n f, _ = (lambda x: a * x, lambda x: b * x)\n\n program_ctx = self._simple_program_ctx()\n with self.assertRaises(ValueError):\n conversion.entity_to_graph(f, program_ctx, None, None)\n\n def test_entity_to_graph_lambda_code_with_garbage(self):\n # pylint:disable=g-long-lambda\n f = ( # intentional wrap\n lambda x: (x # intentional wrap\n + 1),)[0]\n # pylint:enable=g-long-lambda\n\n program_ctx = self._simple_program_ctx()\n nodes, name, _ = conversion.entity_to_graph(f, program_ctx, None, None)\n fn_node, _ = nodes\n self.assertIsInstance(fn_node, gast.Assign)\n self.assertIsInstance(fn_node.value, gast.Lambda)\n self.assertEqual('tf__lambda', name)\n\n def test_entity_to_graph_nested_functions(self):\n b = 2\n\n def f(x):\n def g(x):\n return b * x\n return g(x)\n\n program_ctx = self._simple_program_ctx()\n nodes, name, ns = conversion.entity_to_graph(f, program_ctx, None, None)\n fn_node, _ = nodes\n self.assertIsInstance(fn_node, gast.FunctionDef)\n self.assertEqual(fn_node.name, 'tf__f')\n self.assertEqual('tf__f', name)\n self.assertIs(ns['b'], b)\n\n def test_ag_module_cached(self):\n def callee():\n return range(3)\n\n def caller(a):\n return a()\n\n program_ctx = self._simple_program_ctx()\n _, _, callee_ns = conversion.entity_to_graph(callee, program_ctx, None,\n None)\n _, _, caller_ns = conversion.entity_to_graph(caller, program_ctx, None,\n None)\n\n self.assertTrue(callee_ns['ag__'] is caller_ns['ag__'])\n\n\nif __name__ == '__main__':\n test.main()\n", "# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Utilities related to distributed training.\"\"\"\n# pylint:disable=protected-access\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.data.ops import iterator_ops\nfrom tensorflow.python.distribute import distribute_coordinator_context as dc_context\nfrom tensorflow.python.distribute import reduce_util\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras import callbacks\nfrom tensorflow.python.keras import metrics as metrics_module\nfrom tensorflow.python.keras import optimizers\nfrom tensorflow.python.keras.engine import training_utils\nfrom tensorflow.python.keras.optimizer_v2 import optimizer_v2\nfrom tensorflow.python.keras.utils.mode_keys import ModeKeys\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.util import tf_contextlib\n\n\ndef set_weights(distribution_strategy, dist_model, weights):\n \"\"\"Sets the weights of the replicated models.\n\n The weights of the replicated models are set to the weights of the original\n model. The weights of the replicated model are Mirrored variables and hence\n we need to use the `update` call within a DistributionStrategy scope.\n\n Args:\n distribution_strategy: DistributionStrategy used to distribute training\n and validation.\n dist_model: The replicated models on the different devices.\n weights: The weights of the original model.\n \"\"\"\n assign_ops = []\n for layer in dist_model.layers:\n num_param = len(layer.weights)\n layer_weights = weights[:num_param]\n for sw, w in zip(layer.weights, layer_weights):\n if ops.executing_eagerly_outside_functions():\n sw.assign(w)\n else:\n assign_ops.append(distribution_strategy.unwrap(sw.assign(w)))\n weights = weights[num_param:]\n\n if not ops.executing_eagerly_outside_functions():\n K.get_session(assign_ops).run(assign_ops)\n\n\ndef unwrap_values(distribution_strategy, grouped_inputs, grouped_outputs,\n grouped_updates=None, grouped_session_args=None,\n with_loss_tensor=False):\n \"\"\"Unwrap and return the list of values contained in the PerDevice parameters.\n\n This function calls `flatten_perdevice_values` to parse each of the input\n parameters into a list of values on the different devices. If we set\n `with_loss_tensor` to be True, we also call `reduce` on the list of losses on\n the different devices to give us one loss tensor.\n\n Args:\n distribution_strategy: DistributionStrategy used to distribute training and\n validation.\n grouped_inputs: PerDevice inputs returned from the train or test function\n that we ran on each device.\n grouped_outputs: PerDevice outputs returned from the train or test function\n that we ran on each device.\n grouped_updates: PerDevice updates returned from the train or test function\n that we ran on each device.\n grouped_session_args: PerDevice session args returned from the train or\n test function that we ran on each device.\n with_loss_tensor: Boolean that indicates if we need to add the reduced loss\n tensor as one of the outputs.\n\n Returns:\n Values of each of the PerDevice parameters.\n\n \"\"\"\n # Unwrap per device values returned from each model's train function.\n # This will be used to construct the main train function.\n all_inputs = flatten_perdevice_values(distribution_strategy,\n grouped_inputs)\n if with_loss_tensor:\n # reduce loss tensor before adding it to the list of fetches\n loss = distribution_strategy.reduce(reduce_util.ReduceOp.SUM,\n grouped_outputs[0])\n all_outputs = flatten_perdevice_values(distribution_strategy,\n grouped_outputs[1:])\n all_outputs = [loss] + all_outputs\n else:\n all_outputs = flatten_perdevice_values(distribution_strategy,\n grouped_outputs)\n\n if grouped_updates:\n all_updates = flatten_perdevice_values(distribution_strategy,\n grouped_updates)\n else:\n all_updates = None\n\n all_session_args = {}\n if grouped_session_args:\n grouped_feed_dict = grouped_session_args.get('feed_dict')\n if grouped_feed_dict:\n all_session_args['feed_dict'] = flatten_perdevice_values(\n distribution_strategy, grouped_feed_dict)\n\n grouped_fetches = grouped_session_args.get('fetches')\n if grouped_fetches:\n all_session_args['fetches'] = flatten_perdevice_values(\n distribution_strategy, grouped_fetches)\n\n # TODO(priyag): Return only non empty/None values\n return all_inputs, all_outputs, all_updates, all_session_args\n\n\ndef flatten_perdevice_values(distribution_strategy, perdevice_values):\n \"\"\"Unwraps and flattens a nest of PerDevice parameters.\n\n PerDevice values have one value associated with each device. Each entry in\n the PerDevice dict has a device `key` and the corresponding value on the\n device as the `value`. In this function we take a PerDevice value or a list of\n PerDevice values and return all the values in the PerDevice dict.\n\n Args:\n distribution_strategy: DistributionStrategy used to distribute training and\n validation.\n perdevice_values: List of PerDevice object or a single PerDevice object.\n\n Returns:\n List of values of all the PerDevice objects.\n\n \"\"\"\n # This function takes a PerDevice object or a list of PerDevice objects and\n # returns all the values associated with it.\n return [e for flattened in nest.flatten(perdevice_values)\n for e in distribution_strategy.unwrap(flattened)]\n\n\ndef validate_callbacks(input_callbacks, optimizer):\n \"\"\"Validate whether given callbacks are supported by DistributionStrategy.\n\n Args:\n input_callbacks: List of callbacks passed by the user to fit.\n optimizer: Optimizer instance used to train the model.\n\n Raises:\n ValueError: If `LearningRateScheduler` or `ReduceLROnPlateau` is one of the\n callbacks passed.\n ValueError: If `histogram_freq` or `write_grads` is one of the parameters\n passed as part of the TensorBoard callback.\n \"\"\"\n if input_callbacks:\n for callback in input_callbacks:\n if callback not in [callbacks.TensorBoard, callbacks.ReduceLROnPlateau,\n callbacks.LearningRateScheduler, callbacks.CSVLogger,\n callbacks.EarlyStopping, callbacks.ModelCheckpoint,\n callbacks.TerminateOnNaN, callbacks.ProgbarLogger,\n callbacks.History, callbacks.RemoteMonitor]:\n logging.warning('Your input callback is not one of the predefined '\n 'Callbacks that supports DistributionStrategy. You '\n 'might encounter an error if you access one of the '\n 'model\\'s attributes as part of the callback since '\n 'these attributes are not set. You can access each of '\n 'the individual distributed models using the '\n '`_grouped_model` attribute of your original model.')\n if isinstance(callback, (callbacks.LearningRateScheduler,\n callbacks.ReduceLROnPlateau)):\n\n if not isinstance(optimizer, optimizer_v2.OptimizerV2):\n raise ValueError('You must specify a Keras Optimizer V2 when using '\n '%s callback with DistributionStrategy.' % callback)\n\n # If users want to use the TensorBoard callback they cannot use certain\n # features of the callback that involve accessing model attributes and\n # running ops.\n if isinstance(callback, callbacks.TensorBoard):\n if getattr(callback, 'histogram_freq', False):\n logging.warning(\n UserWarning(\n '`histogram_freq` in the TensorBoard callback is not '\n 'supported when using DistributionStrategy. Setting '\n '`histogram_freq` to `0`.'))\n callback.histogram_freq = 0\n if getattr(callback, 'write_grads', False):\n logging.warning(\n UserWarning(\n '`write_grads` in the TensorBoard callback is not supported '\n 'when using DistributionStrategy. Setting `write_grads` '\n 'to `False`.'))\n callback.histogram_freq = False\n\n\ndef validate_distributed_dataset_inputs(distribution_strategy, x, y,\n sample_weights=None):\n \"\"\"Validate all the components of a DistributedValue Dataset input.\n\n Args:\n distribution_strategy: The current DistributionStrategy used to call\n `fit`/`evaluate`.\n x: Input Dataset DistributedValue object. For example, when we use\n `MirroredStrategy` this is a PerDevice object with a tensor for each\n device set in the dict. x can also be a tuple or dict. The keys of the\n dict should match the names of the input layers of the model.\n y: Target Dataset DistributedValue object. For example, when we use\n `MirroredStrategy` this is a PerDevice object with a tensor for each\n device set in the dict. y can also be a tuple or dict. The keys of the\n dict should match the names of the output layers of the model.\n sample_weights: Sample weights Dataset DistributedValue object. For example,\n when we use `MirroredStrategy` this is a PerDevice object with a tensor\n for each device set in the dict.\n\n Returns:\n The unwrapped values list of the x and y DistributedValues inputs.\n\n Raises:\n ValueError: If x and y do not have support for being evaluated as tensors.\n or if x and y contain elements that are not tensors or if x and y\n contain elements that have a shape or dtype mismatch.\n \"\"\"\n # If the input and target used to call the model are not dataset tensors,\n # we need to raise an error. When using a DistributionStrategy, the input\n # and targets to a model should be from a `tf.data.Dataset`.\n\n # If each element of x and y are not tensors, we cannot standardize and\n # validate the input and targets.\n x_values_list = validate_per_device_inputs(distribution_strategy, x)\n\n if y is not None:\n y_values_list = validate_per_device_inputs(distribution_strategy, y)\n else:\n y_values_list = None\n\n if sample_weights is not None:\n sample_weights_list = validate_per_device_inputs(distribution_strategy,\n sample_weights)\n else:\n sample_weights_list = None\n\n # Return the unwrapped values to avoid calling `unwrap` a second time.\n return x_values_list, y_values_list, sample_weights_list\n\n\ndef validate_per_device_inputs(distribution_strategy, x):\n \"\"\"Validates PerDevice dataset input list.\n\n Args:\n distribution_strategy: The current DistributionStrategy used to call\n `fit`, `evaluate` and `predict`.\n x: A list of PerDevice objects that represent the input or\n target values.\n\n Returns:\n List containing the first element of each of the PerDevice objects in\n the input list.\n\n Raises:\n ValueError: If any of the objects in the `per_device_list` is not a tensor.\n\n \"\"\"\n # Convert the inputs and targets into a list of PerDevice objects.\n per_device_list = nest.flatten(x)\n x_values_list = []\n for x in per_device_list:\n if not tensor_util.is_tensor(x):\n raise ValueError('Dataset input to the model should be tensors instead '\n 'they are of type {}'.format(type(x)))\n\n # At this point both x and y contain tensors in the `DistributedValues`\n # structure.\n x_values = distribution_strategy.unwrap(x)\n\n # Validate that the shape and dtype of all the elements in x are the same.\n validate_all_tensor_shapes(x, x_values)\n validate_all_tensor_types(x, x_values)\n\n x_values_list.append(x_values[0])\n return x_values_list\n\n\ndef validate_all_tensor_types(x, x_values):\n x_dtype = x_values[0].dtype\n for i in range(1, len(x_values)):\n if x_dtype != x_values[i].dtype:\n raise ValueError('Input tensor dtypes do not match for distributed tensor'\n ' inputs {}'.format(x))\n\n\ndef validate_all_tensor_shapes(x, x_values):\n # Validate that the shape of all the elements in x have the same shape\n x_shape = x_values[0].get_shape().as_list()\n for i in range(1, len(x_values)):\n if x_shape != x_values[i].get_shape().as_list():\n raise ValueError('Input tensor shapes do not match for distributed tensor'\n ' inputs {}'.format(x))\n\n\ndef _wait_for_variable_initialization(session):\n \"\"\"Utility to wait for variables to be initialized.\"\"\"\n all_variables = K._get_variables(K.get_graph()) # pylint: disable=protected-access\n candidate_vars = []\n for v in all_variables:\n if not getattr(v, '_keras_initialized', False):\n candidate_vars.append(v)\n\n if not candidate_vars:\n return\n\n while True:\n is_initialized = session.run(\n [variables.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 # pylint: disable=protected-access\n if not uninitialized_vars:\n break\n\n\ndef init_restore_or_wait_for_variables():\n \"\"\"Initialize or restore variables or wait for variables to be initialized.\"\"\"\n session = K._get_session() # pylint: disable=protected-access\n worker_context = dc_context.get_current_worker_context()\n if not worker_context or worker_context.experimental_should_init:\n # TODO(yuefengz): if checkpoints exist, restore from checkpoint.\n K._initialize_variables(session) # pylint: disable=protected-access\n else:\n _wait_for_variable_initialization(session)\n\n\ndef validate_inputs(x, y, distribution_strategy, allow_partial_batch=False):\n \"\"\"Validate inputs when using DistributionStrategy.\n\n Args:\n x: Model Inputs.\n y: Model Targets.\n distribution_strategy: The DistributionStrategy with which the model is\n compiled.\n allow_partial_batch: Boolean. If false, datasets must have fully\n defined shapes.\n\n Raises:\n ValueError: if input is not a Dataset or a numpy array(when we use\n MirroredStrategy).\n \"\"\"\n if (isinstance(x, iterator_ops.Iterator) or\n isinstance(y, iterator_ops.Iterator)):\n raise ValueError('`DistributionStrategy` does not support inputs of type '\n 'Iterator. You must pass a `tf.data.Dataset` object or a '\n 'numpy array as input.')\n\n if is_tpu_strategy(distribution_strategy):\n for i in [x, y]:\n if (isinstance(i, dataset_ops.DatasetV2) and not allow_partial_batch):\n if not is_dataset_shape_fully_defined(i):\n raise ValueError(\n 'Using TPUs currently requires fully defined shapes. Either use '\n 'set_shape() on the input tensors or use '\n 'dataset.batch(..., drop_remainder=True).'\n 'Found unknown shape in input {}.'.format(i))\n\n\n# TODO(b/118776054): Currently we support global batch size for TPUStrategy and\n# core MirroredStrategy only. Remove this check when contrib MirroredStrategy is\n# no longer needed.\ndef global_batch_size_supported(distribution_strategy):\n return distribution_strategy.extended._global_batch_size # pylint: disable=protected-access\n\n\n# TODO(sourabhbajaj): Remove this once we use the same API for all strategies.\ndef is_tpu_strategy(strategy):\n \"\"\"We're executing TPU Strategy.\"\"\"\n return strategy is not None and strategy.__class__.__name__ == 'TPUStrategy'\n\n\ndef is_dataset_shape_fully_defined(dataset):\n \"\"\"Returns whether a dataset contains a final partial batch.\"\"\"\n shapes = nest.flatten(dataset_ops.get_legacy_output_shapes(dataset))\n unknown_shapes = [s for s in shapes if not s.is_fully_defined()]\n return not unknown_shapes\n\n\ndef get_input_params(distribution_strategy, first_x_value, steps, batch_size,\n mode=None):\n \"\"\"Calculate the number of batches and steps/steps_per_epoch.\n\n Args:\n distribution_strategy: The DistributionStrategy used to compile the model.\n first_x_value: This is the first input numpy array that is passed in as the\n model input.\n steps: The specified number of steps.\n batch_size: The specified batch_size.\n mode: ModeKey representing whether input will be used for training,\n evaluation, or prediction. This is used to relax the constraints on\n consuming all the training samples to keep compatibility till we\n support partial batches. If none, then partial batches are not allowed.\n\n Returns:\n steps: The steps or steps_per_epoch argument depending on if a user is\n calling `fit`, `evaluate` or `predict`. If the is_training flag is set\n we don't require the number of samples to be used completely.\n batch_size: The batch size to be used in model iterations.\n\n Raises:\n ValueError: If the number of batches or steps evaluates to 0.\n\n \"\"\"\n num_samples = first_x_value.shape[0]\n # TODO(b/118776054): Use global batch size for Keras/DS support.\n # Currently this is only supported in TPUStrategy and CoreMirroredStrategy.\n use_per_replica_batch = not global_batch_size_supported(\n distribution_strategy)\n\n # Partial batches are allowed for training as we repeat the\n # dataset when converting numpy arrays into a dataset.\n # For other modes uneven batch sizes are not allowed except\n # for `predict()` on TPUStrategy.\n allow_partial_batch = (mode == ModeKeys.TRAIN or\n (mode == ModeKeys.PREDICT\n and is_tpu_strategy(distribution_strategy)))\n\n if steps is None:\n if batch_size is None:\n # If neither the batch size or number of steps are set. We choose the\n # global batch size as the minimum of number of samples and 32. 32 is\n # chosen to provide backward compatibility.\n global_batch_size = min(num_samples, 32)\n else:\n # If the user provided the batch size we need to handle the case\n # between different strategies that use the global/per-replica batch size\n global_batch_size = batch_size\n if use_per_replica_batch:\n global_batch_size *= distribution_strategy.num_replicas_in_sync\n if allow_partial_batch:\n steps = np.ceil(num_samples / global_batch_size).astype(int)\n else:\n if num_samples % global_batch_size:\n raise ValueError('The number of samples %s is not divisible by '\n 'batch size %s.' % (num_samples, global_batch_size))\n steps = num_samples // global_batch_size\n else:\n if batch_size is None:\n # We calculate the batch size based on the number of steps specified\n if num_samples % steps:\n raise ValueError('The number of samples %s is not divisible by '\n 'steps %s. Please change the number of steps to a '\n 'value that can consume all the samples' % (\n num_samples, steps))\n global_batch_size = num_samples // steps\n else:\n # If the user provided the batch size we need to handle the case\n # between different strategies that use the global/per-replica batch size\n global_batch_size = batch_size\n if use_per_replica_batch:\n global_batch_size *= distribution_strategy.num_replicas_in_sync\n\n min_num_samples = global_batch_size * steps\n if allow_partial_batch:\n min_num_samples = global_batch_size * (steps-1) + 1 if steps > 1 else 0\n\n if num_samples < min_num_samples:\n raise ValueError('Number of samples %s is less than samples required '\n 'for specified batch_size %s and steps %s' % (\n num_samples, global_batch_size, steps))\n\n # We need to return the per replica or global batch size based on the strategy\n if use_per_replica_batch:\n if global_batch_size % distribution_strategy.num_replicas_in_sync:\n raise ValueError(\n 'The batch size (%s) could not be sharded evenly across the sync '\n 'replicas (%s) in the distribution strategy.' % (\n global_batch_size, distribution_strategy.num_replicas_in_sync))\n batch_size = global_batch_size // distribution_strategy.num_replicas_in_sync\n else:\n batch_size = global_batch_size\n\n return steps, batch_size\n\n\ndef get_batch_dimension(iterator):\n shapes = nest.flatten(dataset_ops.get_legacy_output_shapes(iterator))\n # Take the batch size from the first element, as it should be the same for\n # all.\n dims = shapes[0].dims\n return dims[0] if dims else None\n\n\ndef list_to_tuple(maybe_list):\n \"\"\"Datasets treat lists specially, so switch them to tuples.\"\"\"\n if isinstance(maybe_list, list):\n return tuple(maybe_list)\n return maybe_list\n\n\ndef get_iterator(dataset, distribution_strategy):\n with distribution_strategy.scope():\n iterator = distribution_strategy.make_dataset_iterator(dataset)\n initialize_iterator(iterator, distribution_strategy)\n return iterator\n\n\ndef initialize_iterator(iterator, distribution_strategy):\n with distribution_strategy.scope():\n init_op = control_flow_ops.group(iterator.initialize())\n if not context.executing_eagerly():\n K.get_session((init_op,)).run(init_op)\n\n\ndef _get_input_from_iterator(iterator, model):\n \"\"\"Get elements from the iterator and verify the input shape and type.\"\"\"\n next_element = iterator.get_next()\n\n if len(nest.flatten(next_element)) == len(model.inputs):\n x = next_element\n y = None\n sample_weights = None\n elif len(nest.flatten(next_element)) == (len(model.inputs) +\n len(model.outputs)):\n x, y = next_element\n sample_weights = None\n else:\n x, y, sample_weights = next_element\n\n # Validate that all the elements in x and y are of the same type and shape.\n validate_distributed_dataset_inputs(\n model._distribution_strategy, x, y, sample_weights)\n return x, y, sample_weights\n\n\ndef _prepare_feed_values(model, inputs, targets, sample_weights, mode):\n \"\"\"Prepare feed values to the model execution function.\n\n Arguments:\n model: Model to prepare feed values for.\n inputs: List or dict of model inputs.\n targets: Optional list of model targets.\n sample_weights: Optional list of sample weight arrays.\n mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT.\n\n Returns:\n Feed values for the model in the given mode.\n \"\"\"\n strategy = model._distribution_strategy\n inputs, targets, sample_weights = _get_input_from_iterator(inputs, model)\n inputs = flatten_perdevice_values(strategy, inputs)\n targets = flatten_perdevice_values(strategy, targets)\n # Expand 1-dimensional inputs.\n # TODO(b/124535720): Remove once this standarize data logic is shared with\n # main flow.\n inputs, targets = nest.map_structure(training_utils.standardize_single_array,\n (inputs, targets))\n if mode == ModeKeys.PREDICT:\n sample_weights = []\n targets = []\n else:\n sample_weights = [\n None for _ in range(len(model.outputs) * strategy.num_replicas_in_sync)\n ]\n ins = inputs + targets + sample_weights\n if mode == ModeKeys.TRAIN and not isinstance(K.symbolic_learning_phase(),\n int):\n ins += [True]\n return ins\n\n\ndef _custom_compile_for_predict(model):\n \"\"\"Custom compile for TPU predict mode.\"\"\"\n if not model.built:\n # Model is not compilable because it does not know its number of inputs\n # and outputs, nor their shapes and names. We will compile after the first\n # time the model gets called on training data.\n return\n model._is_compiled = True\n model.total_loss = None\n model.train_function = None\n model.test_function = None\n model.predict_function = None\n\n\ndef _build_network_on_replica(model, mode, inputs=None, targets=None):\n \"\"\"Build an updated model on replicas.\n\n We create a new Keras model while sharing the variables from the old graph.\n Building a new sub-graph is required since the original keras model creates\n placeholders for the input and the output that are not accessible till we\n call iterator.get_next() inside the step_fn for `fit`/`evaluate`/`predict`.\n\n The sharing of weights and layers between the old and the new model gaurantee\n that we're using Strategy variables and any updates on either model are\n reflected correctly in callbacks and loop iterations.\n\n We need to make sure we share the optimizers between the old and the new model\n as well so that optimizer state is not lost if the user is running fit\n multiple times.\n\n Args:\n model: Model to be replicated across Replicas\n mode: Which of fit/eval/predict is building the distributed network\n inputs: Input variables to be passed to the model\n targets: Target tensor to be passed to model.compile\n\n Returns:\n A new model with shared layers with the old model.\n \"\"\"\n # Need to do imports here since we run into a circular dependency error.\n from tensorflow.python.keras import models # pylint: disable=g-import-not-at-top\n from tensorflow.python.keras.engine import sequential # pylint: disable=g-import-not-at-top\n\n # We rely on the internal methods to avoid having share_weights weights in the\n # public API.\n if isinstance(model, sequential.Sequential):\n updated_model = models._clone_sequential_model(model, input_tensors=inputs,\n share_weights=True)\n else:\n updated_model = models._clone_functional_model(model, input_tensors=inputs,\n share_weights=True)\n\n # Recast all low precision outputs back to float32 since we only casted\n # the inputs to bfloat16 and not targets. This is done so that we can preserve\n # precision when calculating the loss value.\n def _upcast_low_precision_outputs(output):\n if output.dtype == dtypes.bfloat16:\n return math_ops.cast(output, dtypes.float32)\n else:\n return output\n updated_model.outputs = [_upcast_low_precision_outputs(o)\n for o in updated_model.outputs]\n\n if isinstance(targets, tuple):\n targets = nest.flatten(targets)\n\n if mode == ModeKeys.PREDICT and inputs is not None: # TPU predict case\n _custom_compile_for_predict(updated_model)\n else:\n updated_model.compile(\n model.optimizer,\n model.loss,\n metrics=metrics_module.clone_metrics(model._compile_metrics),\n loss_weights=model.loss_weights,\n sample_weight_mode=model.sample_weight_mode,\n weighted_metrics=metrics_module.clone_metrics(\n model._compile_weighted_metrics),\n target_tensors=targets)\n return updated_model\n\n\ndef _build_distributed_network(model, strategy, mode, inputs=None,\n targets=None):\n \"\"\"Create a cloned model on each replica.\"\"\"\n with K.get_graph().as_default(), strategy.scope():\n distributed_model = strategy.extended.call_for_each_replica(\n _build_network_on_replica,\n args=(model, mode, inputs, targets))\n set_distributed_model(model, mode, distributed_model)\n\n\ndef _clone_and_build_model(model, mode, inputs=None, targets=None):\n \"\"\"Clone and build the given keras_model.\"\"\"\n # We need to set the import here since we run into a circular dependency\n # error.\n from tensorflow.python.keras import models # pylint: disable=g-import-not-at-top\n cloned_model = models.clone_model(model, input_tensors=inputs)\n\n # Compile and build model.\n if isinstance(model.optimizer, optimizers.TFOptimizer):\n optimizer = model.optimizer\n else:\n optimizer_config = model.optimizer.get_config()\n optimizer = model.optimizer.__class__.from_config(optimizer_config)\n\n # Recast all low precision outputs back to float32 since we only casted\n # the inputs to bfloat16 and not targets. This is done so that we can preserve\n # precision when calculating the loss value.\n def _upcast_low_precision_outputs(output):\n if output.dtype == dtypes.bfloat16:\n return math_ops.cast(output, dtypes.float32)\n else:\n return output\n cloned_model.outputs = [_upcast_low_precision_outputs(o)\n for o in cloned_model.outputs]\n\n if isinstance(targets, tuple):\n targets = nest.flatten(targets)\n if mode == ModeKeys.PREDICT and inputs is not None: # TPU predict case\n _custom_compile_for_predict(cloned_model)\n else:\n cloned_model.compile(\n optimizer,\n model.loss,\n metrics=metrics_module.clone_metrics(model._compile_metrics),\n loss_weights=model.loss_weights,\n sample_weight_mode=model.sample_weight_mode,\n weighted_metrics=metrics_module.clone_metrics(\n model._compile_weighted_metrics),\n target_tensors=targets)\n return cloned_model\n\n\ndef clone_model_on_replicas(model, strategy, mode, inputs=None, targets=None):\n \"\"\"Create a cloned model on each replica.\"\"\"\n with K.get_graph().as_default(), strategy.scope():\n distributed_model = strategy.extended.call_for_each_replica(\n _clone_and_build_model, args=(model, mode, inputs, targets))\n set_distributed_model(model, mode, distributed_model)\n if mode == ModeKeys.TRAIN:\n model._make_callback_model(distributed_model)\n\n\ndef _make_execution_function(model, mode):\n \"\"\"Makes or reuses function to run one step of distributed model execution.\"\"\"\n strategy = model._distribution_strategy\n\n distributed_model = get_distributed_model(model, mode)\n # If distributed model for a particular `mode` is already built, use the\n # `_distribution_function` on that distributed model.\n if distributed_model:\n return distributed_model._distributed_function\n\n # If distributed_model is not built, create one for `mode`.\n if model._compile_distribution:\n clone_model_on_replicas(model, strategy, mode)\n else:\n _build_distributed_network(model, strategy, mode)\n\n # We've just created the distributed model. So `distributed_model` should be\n # not None.\n distributed_model = get_distributed_model(model, mode)\n assert distributed_model\n\n # Also create an execution fuction on that distributed model.\n if context.executing_eagerly():\n distributed_function = _make_eager_execution_function(model, mode)\n else:\n distributed_function = _make_graph_execution_function(model, mode)\n\n # We cache the distributed execution function on the model since creating\n # distributed models and exection functions are expensive.\n distributed_model._distributed_function = distributed_function\n return distributed_function\n\n\ndef _make_graph_execution_function(model, mode):\n \"\"\"Makes function to run one step of distributed model in graph mode.\"\"\"\n\n def _per_device_function(model):\n f = model._make_execution_function(mode)\n return (f.inputs, f.outputs, f.updates_op, f.session_kwargs)\n\n strategy = model._distribution_strategy\n with strategy.scope():\n # Create train ops on each of the devices when we call\n # `_per_device_fit_function`.\n (grouped_inputs, grouped_outputs, grouped_updates,\n grouped_session_args) = strategy.extended.call_for_each_replica(\n _per_device_function, args=(get_distributed_model(model, mode),))\n\n # Initialize the variables in the replicated model. This is necessary for\n # multi-worker training because on some workers, initialization is not\n # needed. This method does initialization or waiting for initialization\n # according to the context object of distribute coordinator.\n init_restore_or_wait_for_variables()\n\n # Unwrap all the per device values returned from `call_for_each_replica`.\n # Unwrapping per device values gives you a list of values that can be\n # used to construct a new train function that is composed of update ops on\n # all the devices over which the model is distributed.\n (all_inputs, all_outputs, all_updates, all_session_args) = unwrap_values(\n strategy,\n grouped_inputs,\n grouped_outputs,\n grouped_updates,\n grouped_session_args,\n with_loss_tensor=(mode != ModeKeys.PREDICT))\n\n return K.function(\n all_inputs,\n all_outputs,\n updates=all_updates,\n name='distributed_{}_function'.format(mode),\n **all_session_args)\n\n\ndef _make_eager_execution_function(model, mode):\n \"\"\"Makes function to run one step of distributed model eager execution.\"\"\"\n def _per_device_function(model):\n f = model._make_execution_function(mode)\n return (f.inputs, f.outputs)\n\n # NOTE(priyag): Try creating a new FuncGraph within DS scope instead of using\n # the global one.\n strategy = model._distribution_strategy\n global_graph = K.get_graph()\n\n with global_graph.as_default(), strategy.scope():\n # First we gather the relevant portions of the model across all replicas.\n # `K._scratch_graph(global_graph)` signals to Keras that it should not\n # lift to a separate graph when creating the per-replica functions.\n with K._scratch_graph(global_graph):\n # Create train ops on each of the devices when we call\n # `_per_device_fit_function`.\n grouped = strategy.extended.call_for_each_replica(\n _per_device_function, args=(get_distributed_model(model, mode),))\n grouped_inputs, grouped_outputs = grouped\n\n # Unwrap all the per device values returned from `call_for_each_replica`.\n # Unwrapping per device values gives you a list of values that can be\n # used to construct a new train function that is composed of\n # inputs/outputs on all the devices over which the model is distributed.\n (all_inputs, all_outputs, _, _) = unwrap_values(\n strategy,\n grouped_inputs,\n grouped_outputs,\n with_loss_tensor=(mode != ModeKeys.PREDICT))\n\n # Finally, a joint Keras function is created; this one will be created in\n # a separate FuncGraph.\n return K.function(\n all_inputs,\n all_outputs,\n name='eager_distributed_{}_function'.format(mode))\n\n\ndef _copy_weights_to_distributed_model(original_model, mode):\n \"\"\"Copies weights from original model to distributed models.\"\"\"\n strategy = original_model._distribution_strategy\n distributed_model = get_distributed_model(original_model, mode)\n if strategy:\n # Copy the weights from the original model to each of the replicated\n # models.\n orig_model_weights = original_model.get_weights()\n first_model = strategy.unwrap(distributed_model)[0]\n set_weights(strategy, first_model, orig_model_weights)\n\n\ndef _copy_weights_to_original_model(model, mode):\n \"\"\"Copies weights from first distributed model back to original model.\"\"\"\n if model._distribution_strategy and mode == ModeKeys.TRAIN:\n distributed_model = get_distributed_model(model, mode)\n updated_weights = model._distribution_strategy.unwrap(\n distributed_model)[0].get_weights()\n model.set_weights(updated_weights)\n\n\ndef _per_device_aggregate_batch(batch_outs, model, mode):\n \"\"\"Aggregates the per-device batch-level outputs from a distributed step.\"\"\"\n if model._distribution_strategy is not None and mode == ModeKeys.PREDICT:\n total_batch_outs = []\n for i in range(len(model.outputs)):\n num_replicas = model._distribution_strategy.num_replicas_in_sync\n nested_outs = batch_outs[i * num_replicas:i * num_replicas + num_replicas]\n total_batch_outs.append(np.concatenate(nest.flatten(nested_outs)))\n return total_batch_outs\n return batch_outs\n\n\ndef _reset_metrics(model):\n if model._distribution_strategy:\n for mode in [ModeKeys.TRAIN, ModeKeys.TEST, ModeKeys.PREDICT]:\n distributed_model = get_distributed_model(model, mode)\n if distributed_model:\n first_model = model._distribution_strategy.unwrap(distributed_model)[0]\n first_model.reset_metrics()\n\n\ndef get_distributed_model(model, mode):\n key = _generate_cache_key(mode)\n return model._distributed_model_cache.get(key, None)\n\n\ndef set_distributed_model(model, mode, distributed_model):\n key = _generate_cache_key(mode)\n model._distributed_model_cache[key] = distributed_model\n\n\ndef _generate_cache_key(mode):\n key = hash(mode)\n return key\n\n\n@tf_contextlib.contextmanager\ndef distributed_scope(strategy, learning_phase):\n with strategy.scope(), K.learning_phase_scope(learning_phase):\n yield\n\n\ndef filter_distributed_callbacks(callbacks_list):\n \"\"\"Filter Callbacks based on the worker context when running multi-worker.\n\n Arguments:\n callbacks_list: A list of `Callback` instances.\n\n Returns:\n The list of `Callback` instances that should be run on this worker.\n \"\"\"\n\n if not K.in_multi_worker_mode():\n raise ValueError(\n 'filter_distributed_callbacks() should only be called when Keras '\n 'is in multi worker mode.')\n\n worker_context = dc_context.get_current_worker_context()\n callbacks_list = callbacks_list or []\n if not [\n c for c in callbacks_list if isinstance(c, callbacks.ModelCheckpoint)\n ]:\n # TODO(rchao): Consider providing a ModelCheckpoint here if the user\n # fails to.\n logging.warning('ModelCheckpoint callback is not provided. '\n 'Workers will need to restart training if any fails.')\n # TODO(rchao): Add similar warning for restoring callback (to be designed).\n\n if callbacks_list is None or worker_context.is_chief:\n return callbacks_list\n\n # Some Callbacks should only run on the chief worker.\n return [\n callback for callback in callbacks_list if not callback._chief_worker_only\n ] # pylint: disable=protected-access\n", "# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for api module.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport functools\nimport gc\n\nimport numpy as np\n\nfrom tensorflow.python.autograph import utils\nfrom tensorflow.python.autograph.core import converter\nfrom tensorflow.python.autograph.impl import api\nfrom tensorflow.python.autograph.pyct import errors\nfrom tensorflow.python.autograph.pyct import inspect_utils\nfrom tensorflow.python.autograph.pyct import parser\nfrom tensorflow.python.autograph.utils import py_func\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras.engine import sequential\nfrom tensorflow.python.keras.layers import core\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.util import tf_inspect\n\ntf = utils.fake_tf()\n\n\ntesting_global_numeric = 2\n\n\nclass TestResource(str):\n pass\n\n\nclass ApiTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def test_decorator_recursive(self):\n\n class TestClass(object):\n\n def called_member(self, a):\n if a < 0:\n a = -a\n return a\n\n @api.convert(recursive=True)\n def test_method(self, x, s, a):\n while tf.reduce_sum(x) > s:\n x //= self.called_member(a)\n return x\n\n tc = TestClass()\n with self.cached_session() as sess:\n x = tc.test_method(\n constant_op.constant([2, 4]), constant_op.constant(1),\n constant_op.constant(-2))\n self.assertListEqual([0, 1], self.evaluate(x).tolist())\n\n @test_util.run_deprecated_v1\n def test_decorator_not_recursive(self):\n\n class TestClass(object):\n\n def called_member(self, a):\n return tf.negative(a)\n\n @api.convert(recursive=False)\n def test_method(self, x, s, a):\n while tf.reduce_sum(x) > s:\n x //= self.called_member(a)\n return x\n\n tc = TestClass()\n with self.cached_session() as sess:\n x = tc.test_method(\n constant_op.constant([2, 4]), constant_op.constant(1),\n constant_op.constant(-2))\n self.assertListEqual([0, 1], self.evaluate(x).tolist())\n\n @test_util.run_deprecated_v1\n def test_convert_then_do_not_convert_graph(self):\n\n class TestClass(object):\n\n @api.do_not_convert(api.RunMode.GRAPH)\n def called_member(self, a):\n return tf.negative(a)\n\n @api.convert(recursive=True)\n def test_method(self, x, s, a):\n while tf.reduce_sum(x) > s:\n x //= self.called_member(a)\n return x\n\n tc = TestClass()\n x = tc.test_method(\n constant_op.constant((2, 4)), constant_op.constant(1),\n constant_op.constant(-2))\n self.assertAllEqual((0, 1), self.evaluate(x))\n\n @test_util.run_deprecated_v1\n def test_convert_then_do_not_convert_py_func(self):\n\n class TestClass(object):\n\n @api.do_not_convert(\n api.RunMode.PY_FUNC, return_dtypes=py_func.MatchDType(1))\n def called_member(self, a):\n return np.negative(a)\n\n @api.convert(recursive=True)\n def test_method(self, x, s, a):\n while tf.reduce_sum(x) > s:\n y = self.called_member(a)\n # set_shape works around while_loop's limitations.\n # TODO(mdan): Allow specifying shapes (or ShapeLike) instead.\n y.set_shape(a.shape)\n x //= y\n return x\n\n tc = TestClass()\n x = tc.test_method(\n constant_op.constant((2, 4)), constant_op.constant(1),\n constant_op.constant(-2))\n self.assertAllEqual((0, 1), self.evaluate(x))\n\n @test_util.run_deprecated_v1\n def test_decorator_calls_decorated(self):\n\n class TestClass(object):\n\n @api.convert()\n def called_member(self, a):\n if a < 0:\n a = -a\n return a\n\n @api.convert(recursive=True)\n def test_method(self, x, s, a):\n while tf.reduce_sum(x) > s:\n x //= self.called_member(a)\n return x\n\n tc = TestClass()\n with self.cached_session() as sess:\n x = tc.test_method(\n constant_op.constant([2, 4]), constant_op.constant(1),\n constant_op.constant(-2))\n self.assertListEqual([0, 1], self.evaluate(x).tolist())\n\n def test_decorator_preserves_argspec(self):\n\n class TestClass(object):\n\n def called_member(self, a):\n if a < 0:\n a = -a\n return a\n\n called_member_converted = api.convert()(called_member)\n\n tc = TestClass()\n self.assertListEqual(\n list(tf_inspect.getfullargspec(tc.called_member)),\n list(tf_inspect.getfullargspec(tc.called_member_converted)))\n\n @test_util.run_deprecated_v1\n def test_convert_call_site_decorator(self):\n\n class TestClass(object):\n\n def called_member(self, a):\n if a < 0:\n a = -a\n return a\n\n @api.convert(recursive=True)\n def test_method(self, x, s, a):\n while tf.reduce_sum(x) > s:\n x //= api.converted_call(self.called_member, None,\n converter.ConversionOptions(), (a,), {})\n return x\n\n tc = TestClass()\n x = tc.test_method(\n constant_op.constant([2, 4]), constant_op.constant(1),\n constant_op.constant(-2))\n self.assertListEqual([0, 1], self.evaluate(x).tolist())\n\n def test_converted_call_builtin(self):\n x = api.converted_call(range, None, converter.ConversionOptions(), (3,), {})\n self.assertEqual((0, 1, 2), tuple(x))\n\n def test_converted_call_function(self):\n\n def test_fn(x):\n if x < 0:\n return -x\n return x\n\n x = api.converted_call(test_fn, None, converter.ConversionOptions(),\n (constant_op.constant(-1),), {})\n self.assertEqual(1, self.evaluate(x))\n\n @test_util.run_v1_only('b/120545219')\n def test_converted_call_functools_partial(self):\n\n def test_fn(x, y, z):\n if x < 0:\n return -x, -y, -z\n return x, y, z\n\n x = api.converted_call(\n functools.partial(test_fn, constant_op.constant(-1), z=-3), None,\n converter.ConversionOptions(), (constant_op.constant(-2),), {})\n self.assertEqual((1, 2, 3), self.evaluate(x))\n\n x = api.converted_call(\n functools.partial(\n functools.partial(test_fn, constant_op.constant(-1)), z=-3), None,\n converter.ConversionOptions(), (constant_op.constant(-2),), {})\n self.assertEqual((1, 2, 3), self.evaluate(x))\n\n def test_converted_call_method_explicit_owner(self):\n # TODO(mdan): Implement.\n pass\n\n def test_converted_call_method_explicit_super_owner(self):\n # TODO(mdan): Implement.\n pass\n\n def test_converted_call_method(self):\n\n class TestClass(object):\n\n def __init__(self, x):\n self.x = x\n\n def test_method(self):\n if self.x < 0:\n return -self.x\n return self.x\n\n tc = TestClass(constant_op.constant(-1))\n x = api.converted_call(tc.test_method, None, converter.ConversionOptions(),\n (), {})\n self.assertEqual(1, self.evaluate(x))\n\n def test_converted_call_method_as_object_attribute(self):\n\n class AnotherClass(object):\n\n def __init__(self):\n self.another_class_attr = constant_op.constant(1)\n\n def method(self):\n if self.another_class_attr > 0:\n return self.another_class_attr + 1\n return self.another_class_attr + 10\n\n class TestClass(object):\n\n def __init__(self, another_obj_method):\n self.another_obj_method = another_obj_method\n\n obj = AnotherClass()\n tc = TestClass(obj.method)\n\n x = api.converted_call('another_obj_method', tc,\n converter.ConversionOptions(), (), {})\n self.assertEqual(self.evaluate(x), 2)\n\n def test_converted_call_method_converts_recursively(self):\n\n class TestClass(object):\n\n def __init__(self, x):\n self.x = x\n\n def other_method(self):\n if self.x < 0:\n return -self.x\n return self.x\n\n def test_method(self):\n return self.other_method()\n\n tc = TestClass(constant_op.constant(-1))\n x = api.converted_call(tc.test_method, None,\n converter.ConversionOptions(recursive=True), (), {})\n self.assertEqual(1, self.evaluate(x))\n\n def test_converted_call_method_by_class(self):\n\n class TestClass(object):\n\n def __init__(self, x):\n self.x = x\n\n def test_method(self):\n if self.x < 0:\n return -self.x\n return self.x\n\n tc = TestClass(constant_op.constant(-1))\n x = api.converted_call(TestClass.test_method, None,\n converter.ConversionOptions(), (tc,), {})\n self.assertEqual(1, self.evaluate(x))\n\n def test_converted_call_callable_object(self):\n\n class TestClass(object):\n\n def __init__(self, x):\n self.x = x\n\n def __call__(self):\n if self.x < 0:\n return -self.x\n return self.x\n\n tc = TestClass(constant_op.constant(-1))\n x = api.converted_call(tc, None, converter.ConversionOptions(), (), {})\n self.assertEqual(1, self.evaluate(x))\n\n @test_util.run_deprecated_v1\n def test_converted_call_constructor(self):\n\n class TestClass(object):\n\n def __init__(self, x):\n self.x = x\n\n def test_method(self):\n if self.x < 0:\n return -self.x\n return self.x\n\n tc = api.converted_call(TestClass, None, converter.ConversionOptions(),\n (constant_op.constant(-1),), {})\n # tc is still a TestClass - constructors are whitelisted.\n # TODO(b/124016764): Support this use case.\n # The error below is specific to the `if` statement not being converted.\n with self.assertRaisesRegex(\n TypeError, 'Using a `tf.Tensor` as a Python `bool`'):\n tc.test_method()\n\n def test_converted_call_already_converted(self):\n\n def f(x):\n return x == 0\n\n x = api.converted_call(f, None, converter.ConversionOptions(),\n (constant_op.constant(0),), {})\n self.assertTrue(self.evaluate(x))\n\n converted_f = api.to_graph(\n f, experimental_optional_features=converter.Feature.ALL)\n x = api.converted_call(converted_f, None, converter.ConversionOptions(),\n (constant_op.constant(0),), {})\n self.assertTrue(self.evaluate(x))\n\n def test_converted_call_then_already_converted_dynamic(self):\n\n @api.convert()\n def g(x):\n if x > 0:\n return x\n else:\n return -x\n\n def f(g, x):\n return g(x)\n\n x = api.converted_call(f, None, converter.ConversionOptions(),\n (g, constant_op.constant(1)), {})\n self.assertEqual(self.evaluate(x), 1)\n\n @test_util.run_deprecated_v1\n def test_converted_call_no_user_code(self):\n\n def f(x):\n return len(x)\n\n opts = converter.ConversionOptions(internal_convert_user_code=False)\n\n # f should not be converted, causing len to error out.\n with self.assertRaisesRegexp(Exception,\n 'object of type \\'Tensor\\' has no len()'):\n api.converted_call(f, None, opts, (constant_op.constant([0]),), {})\n\n # len on the other hand should work fine.\n x = api.converted_call(len, None, opts, (constant_op.constant([0]),), {})\n # The constant has static shape so the result is a primitive not a Tensor.\n self.assertEqual(x, 1)\n\n def test_converted_call_whitelisted_method(self):\n\n opts = converter.ConversionOptions()\n\n model = sequential.Sequential([\n core.Dense(2)\n ])\n\n x = api.converted_call(model.call, None, opts,\n (constant_op.constant([[0.0]]),), {'training': True})\n\n self.evaluate(variables.global_variables_initializer())\n self.assertAllEqual([[0.0, 0.0]], self.evaluate(x))\n\n def test_converted_call_whitelisted_method_via_owner(self):\n\n opts = converter.ConversionOptions()\n\n model = sequential.Sequential([\n core.Dense(2)\n ])\n\n x = api.converted_call('call', model, opts,\n (constant_op.constant([[0.0]]),), {'training': True})\n\n self.evaluate(variables.global_variables_initializer())\n self.assertAllEqual([[0.0, 0.0]], self.evaluate(x))\n\n def test_converted_call_namedtuple(self):\n\n opts = converter.ConversionOptions()\n\n x = api.converted_call(collections.namedtuple, None, opts,\n ('TestNamedtuple', ('a', 'b')), {})\n\n self.assertTrue(inspect_utils.isnamedtuple(x))\n\n def test_converted_call_namedtuple_via_collections(self):\n\n opts = converter.ConversionOptions()\n\n x = api.converted_call('namedtuple', collections, opts, ('TestNamedtuple',\n ('a', 'b')), {})\n\n self.assertTrue(inspect_utils.isnamedtuple(x))\n\n def test_converted_call_lambda(self):\n\n opts = converter.ConversionOptions()\n\n l = lambda x: x == 0\n\n x = api.converted_call(l, None, opts, (constant_op.constant(0),), {})\n\n self.evaluate(variables.global_variables_initializer())\n self.assertAllEqual(True, self.evaluate(x))\n\n @test_util.run_deprecated_v1\n def test_to_graph_basic(self):\n\n def test_fn(x, s):\n while tf.reduce_sum(x) > s:\n x //= 2\n return x\n\n compiled_fn = api.to_graph(test_fn)\n\n with self.cached_session() as sess:\n x = compiled_fn(constant_op.constant([4, 8]), 4)\n self.assertListEqual([1, 2], self.evaluate(x).tolist())\n\n @test_util.run_deprecated_v1\n def test_to_graph_with_defaults(self):\n\n foo = 4\n\n def test_fn(x, s=foo):\n while tf.reduce_sum(x) > s:\n x //= 2\n return x\n\n compiled_fn = api.to_graph(test_fn)\n\n with self.cached_session() as sess:\n x = compiled_fn(constant_op.constant([4, 8]))\n self.assertListEqual([1, 2], self.evaluate(x).tolist())\n\n def test_to_graph_with_globals(self):\n\n def test_fn(x):\n global testing_global_numeric\n testing_global_numeric = x + testing_global_numeric\n return testing_global_numeric\n\n # TODO(b/122368197)\n with self.assertRaisesRegex(\n errors.AutoGraphError, 'global keyword is not yet supported'):\n api.to_graph(test_fn)\n\n def test_to_graph_with_kwargs_clashing_converted_call(self):\n\n def called_fn(**kwargs):\n return kwargs['f'] + kwargs['owner']\n\n def test_fn():\n # These arg names intentionally match converted_call's\n return called_fn(f=1, owner=2)\n\n compiled_fn = api.to_graph(test_fn)\n\n self.assertEqual(compiled_fn(), 3)\n\n def test_to_graph_with_kwargs_clashing_unconverted_call(self):\n\n @api.do_not_convert()\n def called_fn(**kwargs):\n return kwargs['f'] + kwargs['owner']\n\n def test_fn():\n # These arg names intentionally match _call_unconverted's\n return called_fn(f=1, owner=2)\n\n compiled_fn = api.to_graph(test_fn)\n\n self.assertEqual(compiled_fn(), 3)\n\n def test_to_code_basic(self):\n\n def test_fn(x, s):\n while tf.reduce_sum(x) > s:\n x /= 2\n return x\n\n compiled_code = api.to_code(test_fn)\n\n # Just check that it is parseable Python code.\n self.assertIsNotNone(parser.parse_str(compiled_code))\n\n def test_source_map_attribute_present(self):\n\n def test_fn(y):\n return y**2\n\n self.assertTrue(hasattr(api.to_graph(test_fn), 'ag_source_map'))\n\n def assertNoMemoryLeaks(self, target_f):\n refs_before = set(id(obj) for obj in gc.get_objects())\n target_f()\n gc.collect()\n objs_after = [obj for obj in gc.get_objects() if id(obj) not in refs_before]\n leaked = [obj for obj in objs_after if isinstance(obj, TestResource)]\n self.assertFalse(leaked,\n 'Resources {} were leaked by AutoGraph.'.format(leaked))\n\n def test_no_module_memory_leak(self):\n def f():\n resource = TestResource('some-resource')\n @api.convert()\n def target(x):\n return x + resource, 42\n self.assertEqual(target('foo'), ('foosome-resource', 42))\n\n self.assertNoMemoryLeaks(f)\n\n def test_no_module_memory_leak_deferred_call(self):\n def f():\n resource = TestResource('some-resource')\n @api.convert()\n def target(x):\n def inner_fn():\n return x + resource\n return inner_fn, 42\n self.assertEqual(target('foo')[0](), 'foosome-resource')\n\n f()\n # TODO(brianklee): Reenable when we've revised module loading approach.\n # self.assertNoMemoryLeaks(f)\n\n\nif __name__ == '__main__':\n test.main()\n" ]
[ [ "tensorflow.python.autograph.core.converter.ConversionOptions", "tensorflow.python.autograph.impl.conversion.is_whitelisted_for_graph", "tensorflow.python.autograph.impl.conversion.entity_to_graph", "tensorflow.python.platform.test.main", "tensorflow.python.autograph.pyct.compiler.ast_to_source", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ops.variables.is_variable_initialized", "tensorflow.python.framework.ops.executing_eagerly_outside_functions", "tensorflow.python.keras.backend._get_session", "tensorflow.python.keras.backend.symbolic_learning_phase", "tensorflow.python.data.ops.dataset_ops.get_legacy_output_shapes", "tensorflow.python.eager.context.executing_eagerly", "tensorflow.python.keras.metrics.clone_metrics", "tensorflow.python.keras.models._clone_functional_model", "tensorflow.python.keras.models.clone_model", "tensorflow.python.keras.backend.learning_phase_scope", "numpy.ceil", "tensorflow.python.keras.backend.get_session", "tensorflow.python.util.nest.map_structure", "tensorflow.python.keras.backend.in_multi_worker_mode", "tensorflow.python.ops.math_ops.cast", "tensorflow.python.platform.tf_logging.warning", "tensorflow.python.framework.tensor_util.is_tensor", "tensorflow.python.keras.models._clone_sequential_model", "tensorflow.python.distribute.distribute_coordinator_context.get_current_worker_context", "tensorflow.python.keras.backend._scratch_graph", "tensorflow.python.keras.backend._initialize_variables", "tensorflow.python.keras.backend.get_graph", "tensorflow.python.util.nest.flatten" ], [ "tensorflow.python.autograph.impl.api.do_not_convert", "tensorflow.python.autograph.core.converter.ConversionOptions", "tensorflow.python.autograph.impl.api.to_code", "numpy.negative", "tensorflow.python.framework.test_util.run_v1_only", "tensorflow.python.util.tf_inspect.getfullargspec", "tensorflow.python.autograph.utils.py_func.MatchDType", "tensorflow.python.autograph.impl.api.to_graph", "tensorflow.python.autograph.impl.api.convert", "tensorflow.python.autograph.utils.fake_tf", "tensorflow.python.autograph.pyct.inspect_utils.isnamedtuple", "tensorflow.python.platform.test.main", "tensorflow.python.keras.layers.core.Dense", "tensorflow.python.autograph.impl.api.converted_call", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.autograph.pyct.parser.parse_str", "tensorflow.python.framework.constant_op.constant" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.13" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "2.7", "2.6", "2.4", "2.3", "2.9", "2.5", "2.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.13" ] } ]
MattePalte/Bugs-Quantum-Computing-Platforms
[ "0c1c805fd5dfce465a8955ee3faf81037023a23e", "0c1c805fd5dfce465a8955ee3faf81037023a23e", "0c1c805fd5dfce465a8955ee3faf81037023a23e", "0c1c805fd5dfce465a8955ee3faf81037023a23e", "0c1c805fd5dfce465a8955ee3faf81037023a23e", "0c1c805fd5dfce465a8955ee3faf81037023a23e" ]
[ "artifacts/old_dataset_versions/original_commits_v02/pennylane/pennylane#385/after/test_tf.py", "artifacts/old_dataset_versions/minimal_commits_v02/pennylane/pennylane#481_B/before/_qubit_device.py", "artifacts/old_dataset_versions/minimal_commits_v02/amazon-braket-sdk-python/amazon-braket-sdk-python#263/before/observable.py", "artifacts/old_dataset_versions/minimal_commits_v02/Cirq/Cirq#3948/after/_compat.py", "artifacts/old_dataset_versions/minimal_commits_v02/tequila/tequila#48/after/qc_base.py", "artifacts/old_dataset_versions/minimal_commits_v02/strawberryfields/strawberryfields#90/after/ops.py" ]
[ "# Copyright 2018 Xanadu Quantum 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\"\"\"\nUnit tests for the :mod:`pennylane.interface.tf` QNode interface.\n\"\"\"\n\nimport pytest\n\nimport numpy as np\n\ntry:\n import tensorflow as tf\n\n if tf.__version__[0] == \"1\":\n import tensorflow.contrib.eager as tfe\n tf.enable_eager_execution()\n Variable = tfe.Variable\n else:\n from tensorflow import Variable\n\nexcept ImportError as e:\n pass\n\nimport pennylane as qml\n\nfrom pennylane.qnode import _flatten, unflatten, QNode, QuantumFunctionError\nfrom pennylane.plugins.default_qubit import CNOT, Rotx, Roty, Rotz, I, Y, Z\nfrom pennylane._device import DeviceError\n\n\ndef expZ(state):\n return np.abs(state[0]) ** 2 - np.abs(state[1]) ** 2\n\n\[email protected](scope='module')\ndef tf_support():\n \"\"\"Boolean fixture for TensorFlow support\"\"\"\n try:\n import tensorflow as tf\n tf_support = True\n\n except ImportError as e:\n tf_support = False\n\n return tf_support\n\n\[email protected]()\ndef skip_if_no_tf_support(tf_support):\n if not tf_support:\n pytest.skip(\"Skipped, no tf support\")\n\n\[email protected](\"skip_if_no_tf_support\")\nclass TestTFQNodeExceptions():\n \"\"\"TFQNode basic tests.\"\"\"\n\n def test_qnode_fails_on_wrong_return_type(self, qubit_device_2_wires):\n \"\"\"The qfunc must return only Expectations\"\"\"\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def qf(x):\n qml.RX(x, wires=[0])\n return qml.expval(qml.PauliZ(0)), 0.3\n\n with pytest.raises(QuantumFunctionError, match='must return either'):\n qf(Variable(0.5))\n\n def test_qnode_fails_on_expval_not_returned(self, qubit_device_2_wires):\n \"\"\"All expectation values in the qfunc must be returned\"\"\"\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def qf(x):\n qml.RX(x, wires=[0])\n ex = qml.expval(qml.PauliZ(1))\n return qml.expval(qml.PauliZ(0))\n\n with pytest.raises(QuantumFunctionError, match='All measured observables'):\n qf(Variable(0.5))\n\n def test_qnode_fails_on_wrong_expval_order(self, qubit_device_2_wires):\n \"\"\"Expvals must be returned in the order they were created in\"\"\"\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def qf(x):\n qml.RX(x, wires=[0])\n ex = qml.expval(qml.PauliZ(1))\n return qml.expval(qml.PauliZ(0)), ex\n\n with pytest.raises(QuantumFunctionError, match='All measured observables'):\n qf(Variable(0.5))\n\n def test_qnode_fails_on_gates_after_measurements(self, qubit_device_2_wires):\n \"\"\"Gates have to precede measurements\"\"\"\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def qf(x):\n qml.RX(x, wires=[0])\n ev = qml.expval(qml.PauliZ(1))\n qml.RY(0.5, wires=[0])\n return ev\n\n with pytest.raises(QuantumFunctionError, match='gates must precede'):\n qf(Variable(0.5))\n\n def test_qnode_fails_on_multiple_measurements_of_same_wire(self, qubit_device_2_wires):\n \"\"\"A wire can only be measured once\"\"\"\n \n @qml.qnode(qubit_device_2_wires, interface='tf')\n def qf(x):\n qml.RX(x, wires=[0])\n qml.CNOT(wires=[0, 1])\n return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliX(0))\n\n with pytest.raises(QuantumFunctionError, match='can only be measured once'):\n qf(Variable(0.5))\n\n def test_qnode_fails_on_qfunc_with_too_many_wires(self, qubit_device_2_wires):\n \"\"\"The device must have sufficient wires for the qfunc\"\"\"\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def qf(x):\n qml.RX(x, wires=[0])\n qml.CNOT(wires=[0, 2])\n return qml.expval(qml.PauliZ(0))\n\n with pytest.raises(QuantumFunctionError, match='applied to invalid wire'):\n qf(Variable(0.5))\n\n def test_qnode_fails_on_combination_of_cv_and_qbit_ops(self, qubit_device_1_wire):\n \"\"\"CV and discrete operations must not be mixed\"\"\"\n \n @qml.qnode(qubit_device_1_wire, interface='tf')\n def qf(x):\n qml.RX(x, wires=[0])\n qml.Displacement(0.5, 0, wires=[0])\n return qml.expval(qml.PauliZ(0))\n\n with pytest.raises(QuantumFunctionError, match='Continuous and discrete'):\n qf(Variable(0.5))\n\n def test_qnode_fails_for_cv_ops_on_qubit_device(self, qubit_device_1_wire):\n \"\"\"A qubit device cannot execute CV operations\"\"\"\n\n @qml.qnode(qubit_device_1_wire, interface='tf')\n def qf(x):\n qml.Displacement(0.5, 0, wires=[0])\n return qml.expval(qml.X(0))\n\n with pytest.raises(DeviceError, match='Gate [a-zA-Z]+ not supported on device'):\n qf(Variable(0.5))\n\n def test_qnode_fails_for_cv_observables_on_qubit_device(self, qubit_device_1_wire):\n \"\"\"A qubit device cannot measure CV observables\"\"\"\n\n @qml.qnode(qubit_device_1_wire, interface='tf')\n def qf(x):\n return qml.expval(qml.X(0))\n\n with pytest.raises(DeviceError, match='Observable [a-zA-Z]+ not supported on device'):\n qf(Variable(0.5))\n\n\[email protected](\"skip_if_no_tf_support\")\nclass TestTFQNodeParameterHandling:\n \"\"\"Test that the TFQNode properly handles the parameters of qfuncs\"\"\"\n\n def test_qnode_fanout(self, qubit_device_1_wire, tol):\n \"\"\"Tests that qnodes can compute the correct function when the same parameter is used in multiple gates.\"\"\"\n\n @qml.qnode(qubit_device_1_wire, interface='tf')\n def circuit(reused_param, other_param):\n qml.RX(reused_param, wires=[0])\n qml.RZ(other_param, wires=[0])\n qml.RX(reused_param, wires=[0])\n return qml.expval(qml.PauliZ(0))\n\n thetas = tf.linspace(-2*np.pi, 2*np.pi, 7)\n\n for reused_param in thetas:\n for theta in thetas:\n other_param = theta ** 2 / 11\n y_eval = circuit(reused_param, other_param)\n Rx = Rotx(reused_param.numpy())\n Rz = Rotz(other_param.numpy())\n zero_state = np.array([1.,0.])\n final_state = (Rx @ Rz @ Rx @ zero_state)\n y_true = expZ(final_state)\n\n assert np.allclose(y_eval, y_true, atol=tol, rtol=0)\n\n def test_qnode_array_parameters_scalar_return(self, qubit_device_1_wire, tol):\n \"\"\"Test that QNode can take arrays as input arguments, and that they interact properly with TensorFlow.\n Test case for a circuit that returns a scalar.\"\"\"\n\n # The objective of this test is not to check if the results are correctly calculated, \n # but to check that the interoperability of the different return types works.\n @qml.qnode(qubit_device_1_wire, interface='tf')\n def circuit(dummy1, array, dummy2):\n qml.RY(0.5 * array[0,1], wires=0)\n qml.RY(-0.5 * array[1,1], wires=0)\n return qml.expval(qml.PauliX(0)) # returns a scalar\n\n grad_target = (np.array(1.), np.array([[0.5, 0.43879, 0], [0, -0.43879, 0]]), np.array(-0.4))\n cost_target = 1.03257\n\n args = (Variable(0.46), Variable([[2., 3., 0.3], [7., 4., 2.1]]), Variable(-0.13))\n\n def cost(x, array, y):\n c = tf.cast(circuit(tf.constant(0.111), array, tf.constant(4.5)), tf.float32)\n \n return c +0.5*array[0,0] +x -0.4*y\n\n with tf.GradientTape() as tape:\n cost_res = cost(*args)\n grad_res = np.array([i.numpy() for i in tape.gradient(cost_res, [args[0], args[2]])])\n\n assert np.allclose(cost_res.numpy(), cost_target, atol=tol, rtol=0)\n assert np.allclose(grad_res, np.fromiter(grad_target[::2], dtype=np.float32), atol=tol, rtol=0)\n\n def test_qnode_array_parameters_1_vector_return(self, qubit_device_1_wire, tol):\n \"\"\"Test that QNode can take arrays as input arguments, and that they interact properly with TensorFlow\n Test case for a circuit that returns a 1-vector.\"\"\"\n\n # The objective of this test is not to check if the results are correctly calculated, \n # but to check that the interoperability of the different return types works.\n @qml.qnode(qubit_device_1_wire, interface='tf')\n def circuit(dummy1, array, dummy2):\n qml.RY(0.5 * array[0,1], wires=0)\n qml.RY(-0.5 * array[1,1], wires=0)\n return qml.expval(qml.PauliX(0)), # note the comma, returns a 1-vector\n\n grad_target = (np.array(1.), np.array([[0.5, 0.43879, 0], [0, -0.43879, 0]]), np.array(-0.4))\n cost_target = 1.03257\n\n args = (Variable(0.46), Variable([[2., 3., 0.3], [7., 4., 2.1]]), Variable(-0.13))\n\n def cost(x, array, y):\n c = tf.cast(circuit(tf.constant(0.111), array, tf.constant(4.5)), tf.float32)\n c = c[0] # get a scalar\n return c +0.5*array[0,0] +x -0.4*y\n\n with tf.GradientTape() as tape:\n cost_res = cost(*args)\n grad_res = np.array([i.numpy() for i in tape.gradient(cost_res, [args[0], args[2]])])\n\n assert np.allclose(cost_res.numpy(), cost_target, atol=tol, rtol=0)\n assert np.allclose(grad_res, np.fromiter(grad_target[::2], dtype=np.float32), atol=tol, rtol=0)\n\n def test_qnode_array_parameters_2_vector_return(self, qubit_device_2_wires, tol):\n \"\"\"Test that QNode can take arrays as input arguments, and that they interact properly with TensorFlow\n Test case for a circuit that returns a 2-vector.\"\"\"\n\n # The objective of this test is not to check if the results are correctly calculated, \n # but to check that the interoperability of the different return types works.\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def circuit(dummy1, array, dummy2):\n qml.RY(0.5 * array[0,1], wires=0)\n qml.RY(-0.5 * array[1,1], wires=0)\n qml.RY(array[1,0], wires=1)\n return qml.expval(qml.PauliX(0)), qml.expval(qml.PauliX(1)) # returns a 2-vector\n\n grad_target = (np.array(1.), np.array([[0.5, 0.43879, 0], [0, -0.43879, 0]]), np.array(-0.4))\n cost_target = 1.03257\n\n args = (Variable(0.46), Variable([[2., 3., 0.3], [7., 4., 2.1]]), Variable(-0.13))\n\n def cost(x, array, y):\n c = tf.cast(circuit(tf.constant(0.111), array, tf.constant(4.5)), tf.float32)\n c = c[0] # get a scalar\n return c +0.5*array[0,0] +x -0.4*y\n\n with tf.GradientTape() as tape:\n cost_res = cost(*args)\n grad_res = np.array([i.numpy() for i in tape.gradient(cost_res, [args[0], args[2]])])\n\n assert np.allclose(cost_res.numpy(), cost_target, atol=tol, rtol=0)\n assert np.allclose(grad_res, np.fromiter(grad_target[::2], dtype=np.float32), atol=tol, rtol=0)\n\n\n def test_array_parameters_evaluate(self, qubit_device_2_wires, tol):\n \"\"\"Test that array parameters gives same result as positional arguments.\"\"\"\n a, b, c = tf.constant(0.5), tf.constant(0.54), tf.constant(0.3)\n\n def ansatz(x, y, z):\n qml.QubitStateVector(np.array([1, 0, 1, 1])/np.sqrt(3), wires=[0, 1])\n qml.Rot(x, y, z, wires=0)\n qml.CNOT(wires=[0, 1])\n return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1))\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def circuit1(x, y, z):\n return ansatz(x, y, z)\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def circuit2(x, array):\n return ansatz(x, array[0], array[1])\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def circuit3(array):\n return ansatz(*array)\n\n positional_res = circuit1(a, b, c)\n array_res1 = circuit2(a, Variable([b, c]))\n array_res2 = circuit3(Variable([a, b, c]))\n\n assert np.allclose(positional_res.numpy(), array_res1.numpy(), atol=tol, rtol=0)\n assert np.allclose(positional_res.numpy(), array_res2.numpy(), atol=tol, rtol=0)\n\n def test_multiple_expectation_different_wires(self, qubit_device_2_wires, tol):\n \"\"\"Tests that qnodes return multiple expectation values.\"\"\"\n a, b, c = Variable(0.5), Variable(0.54), Variable(0.3)\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def circuit(x, y, z):\n qml.RX(x, wires=[0])\n qml.RZ(y, wires=[0])\n qml.CNOT(wires=[0, 1])\n qml.RY(y, wires=[0])\n qml.RX(z, wires=[0])\n return qml.expval(qml.PauliY(0)), qml.expval(qml.PauliZ(1))\n\n res = circuit(a, b, c)\n\n out_state = np.kron(Rotx(c.numpy()), I) @ np.kron(Roty(b.numpy()), I) @ CNOT \\\n @ np.kron(Rotz(b.numpy()), I) @ np.kron(Rotx(a.numpy()), I) @ np.array([1, 0, 0, 0])\n\n ex0 = np.vdot(out_state, np.kron(Y, I) @ out_state)\n ex1 = np.vdot(out_state, np.kron(I, Z) @ out_state)\n ex = np.array([ex0, ex1])\n\n assert np.allclose(ex, res.numpy(), atol=tol, rtol=0)\n\n def test_multiple_keywordargs_used(self, qubit_device_2_wires, tol):\n \"\"\"Tests that qnodes use multiple keyword arguments.\"\"\"\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def circuit(w, x=None, y=None):\n qml.RX(x, wires=[0])\n qml.RX(y, wires=[1])\n return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))\n\n c = circuit(tf.constant(1.), x=np.pi, y=np.pi)\n\n assert np.allclose(c.numpy(), [-1., -1.], atol=tol, rtol=0)\n\n def test_multidimensional_keywordargs_used(self, qubit_device_2_wires, tol):\n \"\"\"Tests that qnodes use multi-dimensional keyword arguments.\"\"\"\n def circuit(w, x=None):\n qml.RX(x[0], wires=[0])\n qml.RX(x[1], wires=[1])\n return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))\n\n circuit = qml.QNode(circuit, qubit_device_2_wires).to_tf()\n\n c = circuit(tf.constant(1.), x=[np.pi, np.pi])\n assert np.allclose(c.numpy(), [-1., -1.], atol=tol, rtol=0)\n\n def test_keywordargs_for_wires(self, qubit_device_2_wires, tol):\n \"\"\"Tests that wires can be passed as keyword arguments.\"\"\"\n default_q = 0\n\n def circuit(x, q=default_q):\n qml.RY(x, wires=0)\n return qml.expval(qml.PauliZ(q))\n\n circuit = qml.QNode(circuit, qubit_device_2_wires).to_tf()\n\n c = circuit(tf.constant(np.pi), q=1)\n assert np.allclose(c, 1., atol=tol, rtol=0)\n\n c = circuit(tf.constant(np.pi))\n assert np.allclose(c.numpy(), -1., atol=tol, rtol=0)\n\n def test_keywordargs_used(self, qubit_device_1_wire, tol):\n \"\"\"Tests that qnodes use keyword arguments.\"\"\"\n\n def circuit(w, x=None):\n qml.RX(x, wires=[0])\n return qml.expval(qml.PauliZ(0))\n\n circuit = qml.QNode(circuit, qubit_device_1_wire).to_tf()\n\n c = circuit(tf.constant(1.), x=np.pi)\n assert np.allclose(c.numpy(), -1., atol=tol, rtol=0)\n\n def test_mixture_numpy_tensors(self, qubit_device_2_wires, tol):\n \"\"\"Tests that qnodes work with python types and tensors.\"\"\"\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def circuit(w, x, y):\n qml.RX(x, wires=[0])\n qml.RX(y, wires=[1])\n return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))\n\n c = circuit(tf.constant(1.), np.pi, np.pi).numpy()\n assert np.allclose(c, [-1., -1.], atol=tol, rtol=0)\n\n def test_keywordarg_updated_in_multiple_calls(self, qubit_device_2_wires):\n \"\"\"Tests that qnodes update keyword arguments in consecutive calls.\"\"\"\n\n def circuit(w, x=None):\n qml.RX(w, wires=[0])\n qml.RX(x, wires=[1])\n return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))\n\n circuit = qml.QNode(circuit, qubit_device_2_wires).to_tf()\n\n c1 = circuit(tf.constant(0.1), x=tf.constant(0.))\n c2 = circuit(tf.constant(0.1), x=np.pi)\n assert c1[1] != c2[1]\n\n def test_keywordarg_passes_through_classicalnode(self, qubit_device_2_wires, tol):\n \"\"\"Tests that qnodes' keyword arguments pass through classical nodes.\"\"\"\n\n def circuit(w, x=None):\n qml.RX(w, wires=[0])\n qml.RX(x, wires=[1])\n return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))\n\n circuit = qml.QNode(circuit, qubit_device_2_wires).to_tf()\n\n def classnode(w, x=None):\n return circuit(w, x=x)\n\n c = classnode(tf.constant(0.), x=np.pi)\n assert np.allclose(c.numpy(), [1., -1.], atol=tol, rtol=0)\n\n def test_keywordarg_gradient(self, qubit_device_2_wires, tol):\n \"\"\"Tests that qnodes' keyword arguments work with gradients\"\"\"\n\n def circuit(x, y, input_state=np.array([0, 0])):\n qml.BasisState(input_state, wires=[0, 1])\n qml.RX(x, wires=[0])\n qml.RY(y, wires=[0])\n return qml.expval(qml.PauliZ(0))\n\n circuit = qml.QNode(circuit, qubit_device_2_wires).to_tf()\n\n x = 0.543\n y = 0.45632\n expected_grad = np.array([np.sin(x)*np.cos(y), np.sin(y)*np.cos(x)])\n\n x_t = Variable(x)\n y_t = Variable(y)\n\n # test first basis state against analytic result\n with tf.GradientTape() as tape:\n c = circuit(x_t, y_t, input_state=np.array([0, 0]))\n grads = np.array(tape.gradient(c, [x_t, y_t]))\n\n assert np.allclose(grads, -expected_grad, atol=tol, rtol=0)\n\n # test third basis state against analytic result\n with tf.GradientTape() as tape:\n c = circuit(x_t, y_t, input_state=np.array([1, 0]))\n grads = np.array(tape.gradient(c, [x_t, y_t]))\n\n assert np.allclose(grads, expected_grad, atol=tol, rtol=0)\n\n # test first basis state via the default keyword argument against analytic result\n with tf.GradientTape() as tape:\n c = circuit(x_t, y_t)\n grads = np.array(tape.gradient(c, [x_t, y_t]))\n\n assert np.allclose(grads, -expected_grad, atol=tol, rtol=0)\n\n\[email protected](\"skip_if_no_tf_support\")\nclass TestIntegration:\n \"\"\"Integration tests to ensure the TensorFlow QNode agrees with the NumPy QNode\"\"\"\n\n def test_qnode_evaluation_agrees(self, qubit_device_2_wires, tol):\n \"\"\"Tests that simple example is consistent.\"\"\"\n\n @qml.qnode(qubit_device_2_wires, interface='autograd')\n def circuit(phi, theta):\n qml.RX(phi[0], wires=0)\n qml.RY(phi[1], wires=1)\n qml.CNOT(wires=[0, 1])\n qml.PhaseShift(theta[0], wires=0)\n return qml.expval(qml.PauliZ(0))\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def circuit_tf(phi, theta):\n qml.RX(phi[0], wires=0)\n qml.RY(phi[1], wires=1)\n qml.CNOT(wires=[0, 1])\n qml.PhaseShift(theta[0], wires=0)\n return qml.expval(qml.PauliZ(0))\n\n phi = [0.5, 0.1]\n theta = [0.2]\n\n phi_t = Variable(phi)\n theta_t = Variable(theta)\n\n autograd_eval = circuit(phi, theta)\n tf_eval = circuit_tf(phi_t, theta_t)\n assert np.allclose(autograd_eval, tf_eval.numpy(), atol=tol, rtol=0)\n\n def test_qnode_gradient_agrees(self, qubit_device_2_wires, tol):\n \"\"\"Tests that simple gradient example is consistent.\"\"\"\n\n @qml.qnode(qubit_device_2_wires, interface='autograd')\n def circuit(phi, theta):\n qml.RX(phi[0], wires=0)\n qml.RY(phi[1], wires=1)\n qml.CNOT(wires=[0, 1])\n qml.PhaseShift(theta[0], wires=0)\n return qml.expval(qml.PauliZ(0))\n\n @qml.qnode(qubit_device_2_wires, interface='tf')\n def circuit_tf(phi, theta):\n qml.RX(phi[0], wires=0)\n qml.RY(phi[1], wires=1)\n qml.CNOT(wires=[0, 1])\n qml.PhaseShift(theta[0], wires=0)\n return qml.expval(qml.PauliZ(0))\n\n phi = [0.5, 0.1]\n theta = [0.2]\n\n phi_t = Variable(phi)\n theta_t = Variable(theta)\n\n dcircuit = qml.grad(circuit, [0, 1])\n autograd_grad = dcircuit(phi, theta)\n\n with tf.GradientTape() as g:\n g.watch([phi_t, theta_t])\n y = circuit_tf(phi_t, theta_t)\n tf_grad = g.gradient(y, [phi_t, theta_t])\n\n assert np.allclose(autograd_grad[0], tf_grad[0], atol=tol, rtol=0)\n assert np.allclose(autograd_grad[1], tf_grad[1], atol=tol, rtol=0)\n\n\ngradient_test_data = [\n (0.5, -0.1),\n (0.0, np.pi),\n (-3.6, -3.6),\n (1.0, 2.5),\n]\n\n\[email protected](\"skip_if_no_tf_support\")\nclass TestTFGradients:\n \"\"\"Integration tests involving gradients of QNodes and hybrid computations using the tf interface\"\"\"\n\n @pytest.fixture\n def qnodes(self):\n \"\"\"Two QNodes to be used for the gradient tests\"\"\"\n dev = qml.device(\"default.qubit\", wires=2)\n\n @qml.qnode(dev, interface=\"tf\")\n def f(x):\n qml.RX(x, wires=0)\n return qml.expval(qml.PauliZ(0))\n\n @qml.qnode(dev, interface=\"tf\")\n def g(y):\n qml.RY(y, wires=0)\n return qml.expval(qml.PauliX(0))\n\n return f, g\n\n @pytest.mark.parametrize(\"x, y\", gradient_test_data)\n def test_addition_qnodes_gradient(self, qnodes, x, y):\n \"\"\"Test the gradient of addition of two QNode circuits\"\"\"\n f, g = qnodes\n\n def add(a, b):\n return a + b\n\n xt = Variable(x)\n yt = Variable(y)\n\n # addition\n with tf.GradientTape() as tape:\n tape.watch([xt, yt])\n a = f(xt)\n b = g(yt)\n y = add(a, b)\n grad = tape.gradient(y, [a, b])\n\n assert grad[0].numpy() == 1.0\n assert grad[1].numpy() == 1.0\n\n # same tensor added to itself\n\n with tf.GradientTape() as tape:\n tape.watch([xt, yt])\n a = f(xt)\n y = add(a, a)\n grad = tape.gradient(y, [a, a])\n\n assert grad[0].numpy() == 2.0\n assert grad[1].numpy() == 2.0\n\n # different qnodes with same input parameter added together\n\n with tf.GradientTape() as tape:\n tape.watch([xt, yt])\n a = f(xt)\n b = g(xt)\n y = add(a, b)\n grad = tape.gradient(y, [a, b])\n\n assert grad[0].numpy() == 1.0\n assert grad[1].numpy() == 1.0\n\n @pytest.mark.parametrize(\"x, y\", gradient_test_data)\n def test_subtraction_qnodes_gradient(self, qnodes, x, y):\n \"\"\"Test the gradient of subtraction of two QNode circuits\"\"\"\n f, g = qnodes\n\n def subtract(a, b):\n return a - b\n\n xt = Variable(x)\n yt = Variable(y)\n\n # subtraction\n with tf.GradientTape() as tape:\n tape.watch([xt, yt])\n a = f(xt)\n b = g(yt)\n y = subtract(a, b)\n grad = tape.gradient(y, [a, b])\n\n assert grad[0].numpy() == 1.0\n assert grad[1].numpy() == -1.0\n\n @pytest.mark.parametrize(\"x, y\", gradient_test_data)\n def test_multiplication_qnodes_gradient(self, qnodes, x, y):\n \"\"\"Test the gradient of multiplication of two QNode circuits\"\"\"\n f, g = qnodes\n\n def mult(a, b):\n return a * b\n\n xt = Variable(x)\n yt = Variable(y)\n\n # multiplication\n with tf.GradientTape() as tape:\n tape.watch([xt, yt])\n a = f(xt)\n b = g(yt)\n y = mult(a, b)\n grad = tape.gradient(y, [a, b])\n\n assert grad[0].numpy() == b.numpy()\n assert grad[1].numpy() == a.numpy()\n\n @pytest.mark.parametrize(\"x, y\", gradient_test_data)\n def test_division_qnodes_gradient(self, qnodes, x, y, tol):\n \"\"\"Test the gradient of division of two QNode circuits\"\"\"\n f, g = qnodes\n\n def div(a, b):\n return a / b\n\n xt = Variable(x)\n yt = Variable(y)\n\n # division\n with tf.GradientTape() as tape:\n tape.watch([xt, yt])\n a = f(xt)\n b = g(yt)\n y = div(a, b)\n grad = tape.gradient(y, [a, b])\n\n assert grad[0].numpy() == 1 / b.numpy()\n assert np.allclose(grad[1].numpy(), -a.numpy() / b.numpy() ** 2, atol=tol, rtol=0)\n\n @pytest.mark.parametrize(\"x, y\", gradient_test_data)\n def test_composition_qnodes_gradient(self, qnodes, x, y):\n \"\"\"Test the gradient of composition of two QNode circuits\"\"\"\n f, g = qnodes\n\n xt = Variable(x)\n yt = Variable(y)\n\n # compose function with xt as input\n with tf.GradientTape() as tape:\n tape.watch([xt])\n y = f(xt)\n grad1 = tape.gradient(y, xt)\n\n with tf.GradientTape() as tape:\n tape.watch([xt])\n y = f(xt)\n grad2 = tape.gradient(y, xt)\n\n assert tf.equal(grad1, grad2)\n\n # compose function with a as input\n with tf.GradientTape() as tape:\n tape.watch([xt])\n a = f(xt)\n y = f(a)\n grad1 = tape.gradient(y, a)\n\n with tf.GradientTape() as tape:\n tape.watch([xt])\n a = f(xt)\n y = f(a)\n grad2 = tape.gradient(y, a)\n\n assert tf.equal(grad1, grad2)\n\n # compose function with b as input\n with tf.GradientTape() as tape:\n tape.watch([xt])\n b = g(xt)\n y = g(b)\n grad1 = tape.gradient(y, b)\n\n with tf.GradientTape() as tape:\n tape.watch([xt])\n b = g(xt)\n y = g(b)\n grad2 = tape.gradient(y, b)\n\n assert tf.equal(grad1, grad2)\n", "# Copyright 2018-2020 Xanadu Quantum 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\"\"\"\nThis module contains the :class:`QubitDevice` abstract base class.\n\"\"\"\n\n# For now, arguments may be different from the signatures provided in Device\n# e.g. instead of expval(self, observable, wires, par) have expval(self, observable)\n# pylint: disable=arguments-differ, abstract-method, no-value-for-parameter,too-many-instance-attributes\nimport abc\n\nimport numpy as np\n\nfrom pennylane.operation import Sample, Variance, Expectation, Probability\nfrom pennylane.qnodes import QuantumFunctionError\nfrom pennylane import Device\n\n\nclass QubitDevice(Device):\n \"\"\"Abstract base class for PennyLane qubit devices.\n\n The following abstract methods **must** be defined:\n\n * :meth:`~.probability`: returns the probability or marginal probability from the\n device after circuit execution. :meth:`~.marginal_prob` may be used here.\n\n * :meth:`~.apply`: append circuit operations, compile the circuit (if applicable),\n and perform the quantum computation.\n\n Where relevant, devices that generate their own samples (such as hardware) should\n overwrite the following methods:\n\n * :meth:`~.generate_samples`: Generate samples from the device from the\n exact or approximate probability distribution.\n\n This device contains common utility methods for qubit-based devices. These\n do not need to be overwritten. Utility methods include:\n\n * :meth:`~.expval`, :meth:`~.var`, :meth:`~.sample`: return expectation values,\n variances, and samples of observables after the circuit has been rotated\n into the observable eigenbasis.\n\n Args:\n wires (int): number of subsystems in the quantum state represented by the device\n shots (int): number of circuit evaluations/random samples used to estimate\n expectation values of observables\n analytic (bool): If ``True``, the device calculates probability, expectation values,\n and variances analytically. If ``False``, a finite number of samples set by\n the argument ``shots`` are used to estimate these quantities.\n \"\"\"\n\n # pylint: disable=too-many-public-methods\n _asarray = staticmethod(np.asarray)\n\n def __init__(self, wires=1, shots=1000, analytic=True):\n super().__init__(wires=wires, shots=shots)\n\n self.analytic = analytic\n \"\"\"bool: If ``True``, the device supports exact calculation of expectation\n values, variances, and probabilities. If ``False``, samples are used\n to estimate the statistical quantities above.\"\"\"\n\n self._wires_measured = set()\n \"\"\"set[int]: wires acted on by quantum operations and observables\"\"\"\n\n self._samples = None\n \"\"\"None or array[int]: stores the samples generated by the device\n *after* rotation to diagonalize the observables.\"\"\"\n\n @classmethod\n def capabilities(cls):\n \"\"\"Get the capabilities of the plugin.\n\n Devices that inherit from this class automatically\n have the following items in their capabilities\n dictionary:\n\n * ``\"model\": \"qubit\"``\n * ``\"tensor_observables\": True``\n\n Returns:\n dict[str->*]: results\n \"\"\"\n capabilities = cls._capabilities\n capabilities.update(model=\"qubit\", tensor_observables=True)\n return capabilities\n\n def reset(self):\n \"\"\"Reset the backend state.\n\n After the reset, the backend should be as if it was just constructed.\n Most importantly the quantum state is reset to its initial value.\n \"\"\"\n self._wires_measured = set()\n self._samples = None\n\n def execute(self, circuit):\n \"\"\"Execute a queue of quantum operations on the device and then\n measure the given observables.\n\n For plugin developers: instead of overwriting this, consider\n implementing a suitable subset of\n\n * :meth:`apply`\n\n * :meth:`~.generate_samples`\n\n * :meth:`~.probability`\n\n Args:\n circuit (~.CircuitGraph): circuit to execute on the device\n\n Raises:\n QuantumFunctionError: if the value of :attr:`~.Observable.return_type` is not supported\n\n Returns:\n array[float]: measured value(s)\n \"\"\"\n self.check_validity(circuit.operations, circuit.observables)\n\n # apply all circuit operations\n self.apply(circuit.operations, circuit.diagonalizing_gates)\n\n # determine the wires that are measured by the circuit\n self._wires_measured = QubitDevice.active_wires(circuit.observables)\n\n # generate computational basis samples\n if (not self.analytic) or circuit.is_sampled:\n self.generate_samples()\n\n # compute the required statistics\n results = self.statistics(circuit.observables)\n\n # Ensures that a combination with sample does not put\n # expvals and vars in superfluous arrays\n all_sampled = all(obs.return_type is Sample for obs in circuit.observables)\n if circuit.is_sampled and not all_sampled:\n return self._asarray(results, dtype=\"object\")\n\n return self._asarray(results)\n\n @abc.abstractmethod\n def apply(self, operations, rotations=None, **kwargs):\n \"\"\"Apply quantum operations, rotate the circuit into the measurement\n basis, and compile and execute the quantum circuit.\n\n This method recieves a list of quantum operations queued by the QNode,\n and should be responsible for:\n\n * Constructing the quantum program\n * (Optional) Rotating the quantum circuit using the rotation\n operations provided. This diagonalizes the circuit so that arbitrary\n observables can be measured in the computational basis.\n * Compile the circuit\n * Execute the quantum circuit\n\n Both arguments are provided as lists of PennyLane :class:`~.Operation`\n instances. Useful properties include :attr:`~.Operation.name`,\n :attr:`~.Operation.wires`, and :attr:`~.Operation.parameters`:\n\n >>> op = qml.RX(0.2, wires=[0])\n >>> op.name # returns the operation name\n \"RX\"\n >>> op.wires # returns a list of wires\n [0]\n >>> op.parameters # returns a list of parameters\n [0.2]\n\n Args:\n operations (list[~.Operation]): operations to apply to the device\n rotations (list[~.Operation]): operations that rotate the circuit\n pre-measurement into the eigenbasis of the observables.\n \"\"\"\n\n @staticmethod\n def active_wires(operators):\n \"\"\"Returns the wires acted on by a set of operators.\n\n Args:\n operators (list[~.Operation]): operators for which\n we are gathering the active wires\n\n Returns:\n set[int]: the set of wires activated by the specified operators\n \"\"\"\n wires = []\n for op in operators:\n\n for wire in op.wires:\n if isinstance(wire, int):\n wires.append(wire)\n else:\n wires.extend(wire)\n\n return set(wires)\n\n def statistics(self, observables):\n \"\"\"Process measurement results from circuit execution and return statistics.\n\n This includes returning expectation values, variance, samples and probabilities.\n\n Args:\n observables (List[:class:`Observable`]): the observables to be measured\n\n Raises:\n QuantumFunctionError: if the value of :attr:`~.Observable.return_type` is not supported\n\n Returns:\n Union[float, List[float]]: the corresponding statistics\n \"\"\"\n results = []\n\n for obs in observables:\n # Pass instances directly\n if obs.return_type is Expectation:\n results.append(self.expval(obs))\n\n elif obs.return_type is Variance:\n results.append(self.var(obs))\n\n elif obs.return_type is Sample:\n results.append(np.array(self.sample(obs)))\n\n elif obs.return_type is Probability:\n results.append(self.probability(wires=obs.wires))\n\n elif obs.return_type is not None:\n raise QuantumFunctionError(\n \"Unsupported return type specified for observable {}\".format(obs.name)\n )\n\n return results\n\n def generate_samples(self):\n \"\"\"Generate computational basis samples.\n\n If the device contains a sample return type, or the\n device is running in non-analytic mode, ``dev.shots`` number of\n computational basis samples are generated and stored within\n the :attr:`~._samples` attribute.\n\n .. warning::\n\n This method should be overwritten on devices that\n generate their own computational basis samples.\n \"\"\"\n number_of_states = 2 ** len(self._wires_measured)\n rotated_prob = self.probability(self._wires_measured)\n samples = self.sample_basis_states(number_of_states, rotated_prob)\n self._samples = QubitDevice.states_to_binary(samples, number_of_states)\n\n def sample_basis_states(self, number_of_states, state_probability):\n \"\"\"Sample from the computational basis states based on the state\n probability.\n\n This is an auxiliary method to the generate_samples method.\n\n Args:\n number_of_states (int): the number of basis states to sample from\n\n Returns:\n List[int]: the sampled basis states\n \"\"\"\n basis_states = np.arange(number_of_states)\n return np.random.choice(basis_states, self.shots, p=state_probability)\n\n @staticmethod\n def states_to_binary(samples, number_of_states):\n \"\"\"Convert basis states from base 10 to binary representation.\n\n This is an auxiliary method to the generate_samples method.\n\n Args:\n samples (List[int]): samples of basis states in base 10 representation\n number_of_states (int): the number of basis states to sample from\n\n Returns:\n List[int]: basis states in binary representation\n \"\"\"\n powers_of_two = 1 << np.arange(number_of_states)\n states_sampled_base_ten = samples[:, None] & powers_of_two\n return (states_sampled_base_ten > 0).astype(int)\n\n @property\n def state(self):\n \"\"\"Returns the state vector of the circuit prior to measurement.\n\n .. note::\n\n Only state vector simulators support this property. Please see the\n plugin documentation for more details.\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def probability(self, wires=None):\n \"\"\"Return the (marginal) probability of each computational basis\n state from the last run of the device.\n\n If no wires are specified, then all the basis states representable by\n the device are considered and no marginalization takes place.\n\n Args:\n wires (Sequence[int]): Sequence of wires to return\n marginal probabilities for. Wires not provided\n are traced out of the system.\n\n Returns:\n List[float]: list of the probabilities\n \"\"\"\n\n def marginal_prob(self, prob, wires=None):\n \"\"\"Return the marginal probability of the computational basis\n states by summing the probabiliites on the non-specified wires.\n\n If no wires are specified, then all the basis states representable by\n the device are considered and no marginalization takes place.\n\n Args:\n prob: The probabilities to return the marginal probabilities\n for\n wires (Sequence[int]): Sequence of wires to return\n marginal probabilities for. Wires not provided\n are traced out of the system.\n\n Returns:\n array[float]: array of the resulting marginal probabilities.\n \"\"\"\n wires = list(wires or range(self.num_wires))\n wires = np.hstack(wires)\n inactive_wires = list(set(range(self.num_wires)) - set(wires))\n prob = prob.reshape([2] * self.num_wires)\n return np.apply_over_axes(np.sum, prob, inactive_wires).flatten()\n\n def expval(self, observable):\n wires = observable.wires\n\n if self.analytic:\n # exact expectation value\n eigvals = observable.eigvals\n prob = self.probability(wires=wires)\n return (eigvals @ prob).real\n\n # estimate the ev\n return np.mean(self.sample(observable))\n\n def var(self, observable):\n wires = observable.wires\n\n if self.analytic:\n # exact variance value\n eigvals = observable.eigvals\n prob = self.probability(wires=wires)\n return (eigvals ** 2) @ prob - (eigvals @ prob).real ** 2\n\n # estimate the variance\n return np.var(self.sample(observable))\n\n def sample(self, observable):\n wires = observable.wires\n name = observable.name\n\n if isinstance(name, str) and name in {\"PauliX\", \"PauliY\", \"PauliZ\", \"Hadamard\"}:\n # Process samples for observables with eigenvalues {1, -1}\n return 1 - 2 * self._samples[:, wires[0]]\n\n # Replace the basis state in the computational basis with the correct eigenvalue.\n # Extract only the columns of the basis samples required based on ``wires``.\n wires = np.hstack(wires)\n samples = self._samples[:, np.array(wires)]\n unraveled_indices = [2] * len(wires)\n indices = np.ravel_multi_index(samples.T, unraveled_indices)\n return observable.eigvals[indices]\n", "# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nfrom __future__ import annotations\n\nfrom typing import List, Sequence, Tuple, Union\n\nimport numpy as np\n\nfrom braket.circuits.gate import Gate\nfrom braket.circuits.quantum_operator import QuantumOperator\n\n\nclass Observable(QuantumOperator):\n \"\"\"\n Class `Observable` to represent a quantum observable.\n\n Objects of this type can be used as input to `ResultType.Sample`, `ResultType.Variance`,\n `ResultType.Expectation` to specify the measurement basis.\n \"\"\"\n\n def __init__(self, qubit_count: int, ascii_symbols: Sequence[str]):\n super().__init__(qubit_count=qubit_count, ascii_symbols=ascii_symbols)\n\n def to_ir(self) -> List[Union[str, List[List[List[float]]]]]:\n \"\"\"List[Union[str, List[List[List[float]]]]]: Returns the IR\n representation for the observable\"\"\"\n raise NotImplementedError\n\n @property\n def basis_rotation_gates(self) -> Tuple[Gate, ...]:\n \"\"\"Tuple[Gate]: Returns the basis rotation gates for this observable.\"\"\"\n raise NotImplementedError\n\n @property\n def eigenvalues(self) -> np.ndarray:\n \"\"\"np.ndarray: Returns the eigenvalues of this observable.\"\"\"\n raise NotImplementedError\n\n def eigenvalue(self, index: int) -> float:\n \"\"\"Returns the the eigenvalue of this observable at the given index.\n\n The eigenvalues are ordered by their corresponding computational basis state\n after diagonalization.\n\n Args:\n index: The index of the desired eigenvalue\n\n Returns:\n float: The `index`th eigenvalue of the observable.\n \"\"\"\n raise NotImplementedError\n\n @classmethod\n def register_observable(cls, observable: Observable) -> None:\n \"\"\"Register an observable implementation by adding it into the `Observable` class.\n\n Args:\n observable (Observable): Observable class to register.\n \"\"\"\n setattr(cls, observable.__name__, observable)\n\n def __matmul__(self, other) -> Observable.TensorProduct:\n if isinstance(other, Observable.TensorProduct):\n return other.__rmatmul__(self)\n if isinstance(other, Observable):\n return Observable.TensorProduct([self, other])\n\n raise ValueError(\"Can only perform tensor products between observables.\")\n\n def __repr__(self) -> str:\n return f\"{self.name}('qubit_count': {self.qubit_count})\"\n\n def __eq__(self, other) -> bool:\n if isinstance(other, Observable):\n return self.name == other.name\n return NotImplemented\n\n\nclass StandardObservable(Observable):\n \"\"\"\n Class `StandardObservable` to represent a Pauli-like quantum observable with\n eigenvalues of (+1, -1).\n \"\"\"\n\n def __init__(self, ascii_symbols: Sequence[str]):\n super().__init__(qubit_count=1, ascii_symbols=ascii_symbols)\n self._eigenvalues = (1.0, -1.0) # immutable\n\n @property\n def eigenvalues(self) -> np.ndarray:\n return np.array(self._eigenvalues)\n\n def eigenvalue(self, index: int) -> float:\n return self._eigenvalues[index]\n", "# Copyright 2018 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Workarounds for compatibility issues between versions and libraries.\"\"\"\nimport functools\nimport importlib\nimport os\nimport re\nimport sys\nimport traceback\nimport warnings\nfrom types import ModuleType\nfrom typing import Any, Callable, Optional, Dict, Tuple, Type, Set\n\nimport numpy as np\nimport pandas as pd\nimport sympy\n\n\ndef proper_repr(value: Any) -> str:\n \"\"\"Overrides sympy and numpy returning repr strings that don't parse.\"\"\"\n\n if isinstance(value, sympy.Basic):\n result = sympy.srepr(value)\n\n # HACK: work around https://github.com/sympy/sympy/issues/16074\n # (only handles a few cases)\n fixed_tokens = ['Symbol', 'pi', 'Mul', 'Pow', 'Add', 'Mod', 'Integer', 'Float', 'Rational']\n for token in fixed_tokens:\n result = result.replace(token, 'sympy.' + token)\n\n return result\n\n if isinstance(value, np.ndarray):\n if np.issubdtype(value.dtype, np.datetime64):\n return f'np.array({value.tolist()!r}, dtype=np.{value.dtype!r})'\n return f'np.array({value.tolist()!r}, dtype=np.{value.dtype})'\n\n if isinstance(value, pd.MultiIndex):\n return f'pd.MultiIndex.from_tuples({repr(list(value))}, names={repr(list(value.names))})'\n\n if isinstance(value, pd.Index):\n return (\n f'pd.Index({repr(list(value))}, '\n f'name={repr(value.name)}, '\n f'dtype={repr(str(value.dtype))})'\n )\n\n if isinstance(value, pd.DataFrame):\n cols = [value[col].tolist() for col in value.columns]\n rows = list(zip(*cols))\n return (\n f'pd.DataFrame('\n f'\\n columns={proper_repr(value.columns)}, '\n f'\\n index={proper_repr(value.index)}, '\n f'\\n data={repr(rows)}'\n f'\\n)'\n )\n\n return repr(value)\n\n\ndef proper_eq(a: Any, b: Any) -> bool:\n \"\"\"Compares objects for equality, working around __eq__ not always working.\n\n For example, in numpy a == b broadcasts and returns an array instead of\n doing what np.array_equal(a, b) does. This method uses np.array_equal(a, b)\n when dealing with numpy arrays.\n \"\"\"\n if type(a) == type(b):\n if isinstance(a, np.ndarray):\n return np.array_equal(a, b)\n if isinstance(a, (pd.DataFrame, pd.Index, pd.MultiIndex)):\n return a.equals(b)\n if isinstance(a, (tuple, list)):\n return len(a) == len(b) and all(proper_eq(x, y) for x, y in zip(a, b))\n return a == b\n\n\ndef _warn_or_error(msg):\n from cirq.testing.deprecation import ALLOW_DEPRECATION_IN_TEST\n\n called_from_test = 'PYTEST_CURRENT_TEST' in os.environ\n deprecation_allowed = ALLOW_DEPRECATION_IN_TEST in os.environ\n if called_from_test and not deprecation_allowed:\n raise ValueError(f\"Cirq should not use deprecated functionality: {msg}\")\n\n # we have to dynamically count the non-internal frames\n # due to the potentially multiple nested module wrappers\n stack_level = 1\n for filename, _, _, _ in reversed(traceback.extract_stack()):\n if not _is_internal(filename) and \"_compat.py\" not in filename:\n break\n if \"_compat.py\" in filename:\n stack_level += 1\n\n warnings.warn(\n msg,\n DeprecationWarning,\n stacklevel=stack_level,\n )\n\n\ndef _validate_deadline(deadline: str):\n DEADLINE_REGEX = r\"^v(\\d)+\\.(\\d)+$\"\n assert re.match(DEADLINE_REGEX, deadline), \"deadline should match vX.Y\"\n\n\ndef deprecated(\n *, deadline: str, fix: str, name: Optional[str] = None\n) -> Callable[[Callable], Callable]:\n \"\"\"Marks a function as deprecated.\n\n Args:\n deadline: The version where the function will be deleted. It should be a minor version\n (e.g. \"v0.7\").\n fix: A complete sentence describing what the user should be using\n instead of this particular function (e.g. \"Use cos instead.\")\n name: How to refer to the function.\n Defaults to `func.__qualname__`.\n\n Returns:\n A decorator that decorates functions with a deprecation warning.\n \"\"\"\n _validate_deadline(deadline)\n\n def decorator(func: Callable) -> Callable:\n @functools.wraps(func)\n def decorated_func(*args, **kwargs) -> Any:\n qualname = func.__qualname__ if name is None else name\n _warn_or_error(\n f'{qualname} was used but is deprecated.\\n'\n f'It will be removed in cirq {deadline}.\\n'\n f'{fix}\\n'\n )\n\n return func(*args, **kwargs)\n\n decorated_func.__doc__ = (\n f'THIS FUNCTION IS DEPRECATED.\\n\\n'\n f'IT WILL BE REMOVED IN `cirq {deadline}`.\\n\\n'\n f'{fix}\\n\\n'\n f'{decorated_func.__doc__ or \"\"}'\n )\n\n return decorated_func\n\n return decorator\n\n\ndef deprecated_class(\n *, deadline: str, fix: str, name: Optional[str] = None\n) -> Callable[[Type], Type]:\n \"\"\"Marks a class as deprecated.\n\n Args:\n deadline: The version where the function will be deleted. It should be a minor version\n (e.g. \"v0.7\").\n fix: A complete sentence describing what the user should be using\n instead of this particular function (e.g. \"Use cos instead.\")\n name: How to refer to the class.\n Defaults to `class.__qualname__`.\n\n Returns:\n A decorator that decorates classes with a deprecation warning.\n \"\"\"\n\n _validate_deadline(deadline)\n\n def decorator(clazz: Type) -> Type:\n clazz_new = clazz.__new__\n\n def patched_new(cls, *args, **kwargs):\n qualname = clazz.__qualname__ if name is None else name\n _warn_or_error(\n f'{qualname} was used but is deprecated.\\n'\n f'It will be removed in cirq {deadline}.\\n'\n f'{fix}\\n'\n )\n\n return clazz_new(cls)\n\n setattr(clazz, '__new__', patched_new)\n clazz.__doc__ = (\n f'THIS CLASS IS DEPRECATED.\\n\\n'\n f'IT WILL BE REMOVED IN `cirq {deadline}`.\\n\\n'\n f'{fix}\\n\\n'\n f'{clazz.__doc__ or \"\"}'\n )\n\n return clazz\n\n return decorator\n\n\ndef deprecated_parameter(\n *,\n deadline: str,\n fix: str,\n func_name: Optional[str] = None,\n parameter_desc: str,\n match: Callable[[Tuple[Any, ...], Dict[str, Any]], bool],\n rewrite: Optional[\n Callable[[Tuple[Any, ...], Dict[str, Any]], Tuple[Tuple[Any, ...], Dict[str, Any]]]\n ] = None,\n) -> Callable[[Callable], Callable]:\n \"\"\"Marks a function parameter as deprecated.\n\n Also handles rewriting the deprecated parameter into the new signature.\n\n Args:\n deadline: The version where the function will be deleted. It should be a minor version\n (e.g. \"v0.7\").\n fix: A complete sentence describing what the user should be using\n instead of this particular function (e.g. \"Use cos instead.\")\n func_name: How to refer to the function.\n Defaults to `func.__qualname__`.\n parameter_desc: The name and type of the parameter being deprecated,\n e.g. \"janky_count\" or \"janky_count keyword\" or\n \"positional janky_count\".\n match: A lambda that takes args, kwargs and determines if the\n deprecated parameter is present or not. This determines whether or\n not the deprecation warning is printed, and also whether or not\n rewrite is called.\n rewrite: Returns new args/kwargs that don't use the deprecated\n parameter. Defaults to making no changes.\n\n Returns:\n A decorator that decorates functions with a parameter deprecation\n warning.\n \"\"\"\n _validate_deadline(deadline)\n\n def decorator(func: Callable) -> Callable:\n @functools.wraps(func)\n def decorated_func(*args, **kwargs) -> Any:\n if match(args, kwargs):\n if rewrite is not None:\n args, kwargs = rewrite(args, kwargs)\n\n qualname = func.__qualname__ if func_name is None else func_name\n _warn_or_error(\n f'The {parameter_desc} parameter of {qualname} was '\n f'used but is deprecated.\\n'\n f'It will be removed in cirq {deadline}.\\n'\n f'{fix}\\n',\n )\n\n return func(*args, **kwargs)\n\n return decorated_func\n\n return decorator\n\n\ndef deprecate_attributes(module: ModuleType, deprecated_attributes: Dict[str, Tuple[str, str]]):\n \"\"\"Wrap a module with deprecated attributes that give warnings.\n\n Args:\n module: The module to wrap.\n deprecated_attributes: A dictionary from attribute name to a tuple of\n strings, where the first string gives the version that the attribute\n will be removed in, and the second string describes what the user\n should do instead of accessing this deprecated attribute.\n\n Returns:\n Wrapped module with deprecated attributes. Use of these attributes\n will cause a warning for these deprecated attributes.\n \"\"\"\n\n for (deadline, _) in deprecated_attributes.values():\n _validate_deadline(deadline)\n\n class Wrapped(ModuleType):\n\n __dict__ = module.__dict__\n\n def __getattr__(self, name):\n if name in deprecated_attributes:\n deadline, fix = deprecated_attributes[name]\n _warn_or_error(\n f'{name} was used but is deprecated.\\n'\n f'It will be removed in cirq {deadline}.\\n'\n f'{fix}\\n'\n )\n return getattr(module, name)\n\n return Wrapped(module.__name__, module.__doc__)\n\n\nclass DeprecatedModuleLoader(importlib.abc.Loader):\n \"\"\"A Loader for deprecated modules.\n\n It wraps an existing Loader instance, to which it delegates the loading. On top of that\n it ensures that the sys.modules cache has both the deprecated module's name and the\n new module's name pointing to the same exact ModuleType instance.\n\n Args:\n loader: the loader to be wrapped\n old_module_name: the deprecated module's fully qualified name\n new_module_name: the new module's fully qualified name\n \"\"\"\n\n def __init__(self, loader: Any, old_module_name: str, new_module_name: str):\n \"\"\"A module loader that uses an existing module loader and intercepts\n the execution of a module.\n \"\"\"\n self.loader = loader\n if hasattr(loader, 'exec_module'):\n # mypy#2427\n self.exec_module = self._wrap_exec_module(loader.exec_module) # type: ignore\n # while this is rare and load_module was deprecated in 3.4\n # in older environments this line makes them work as well\n if hasattr(loader, 'load_module'):\n # mypy#2427\n self.load_module = self._wrap_load_module(loader.load_module) # type: ignore\n if hasattr(loader, 'create_module'):\n self.create_module = loader.create_module # type: ignore\n self.old_module_name = old_module_name\n self.new_module_name = new_module_name\n\n def module_repr(self, module: ModuleType) -> str:\n return self.loader.module_repr(module)\n def _wrap_load_module(self, method: Any) -> Any:\n def load_module(fullname: str) -> ModuleType:\n assert fullname == self.old_module_name, (\n f\"DeprecatedModuleLoader for {self.old_module_name} was asked to \"\n f\"load {fullname}\"\n )\n if self.new_module_name in sys.modules:\n sys.modules[self.old_module_name] = sys.modules[self.new_module_name]\n return sys.modules[self.old_module_name]\n method(self.new_module_name)\n assert self.new_module_name in sys.modules, (\n f\"Wrapped loader {self.loader} was \"\n f\"expected to insert \"\n f\"{self.new_module_name} in sys.modules \"\n f\"but it did not.\"\n )\n sys.modules[self.old_module_name] = sys.modules[self.new_module_name]\n return sys.modules[self.old_module_name]\n return load_module\n\n def _wrap_exec_module(self, method: Any) -> Any:\n def exec_module(module: ModuleType) -> None:\n assert module.__name__ == self.old_module_name, (\n f\"DeprecatedModuleLoader for {self.old_module_name} was asked to \"\n f\"load {module.__name__}\"\n )\n # check for new_module whether it was loaded\n if self.new_module_name in sys.modules:\n # found it - no need to load the module again\n sys.modules[self.old_module_name] = sys.modules[self.new_module_name]\n return\n\n # now we know we have to initialize the module\n sys.modules[self.old_module_name] = module\n sys.modules[self.new_module_name] = module\n\n try:\n return method(module)\n except BaseException:\n # if there's an error, we atomically remove both\n del sys.modules[self.new_module_name]\n del sys.modules[self.old_module_name]\n raise\n\n return exec_module\n\n\ndef _is_internal(filename: str) -> bool:\n \"\"\"Returns whether filename is internal to python.\n\n This is similar to how the built-in warnings module differentiates frames from internal modules.\n It is specific to CPython - see\n https://github.com/python/cpython/blob/41ec17e45d54473d32f543396293256f1581e44d/Lib/warnings.py#L275.\n \"\"\"\n return 'importlib' in filename and '_bootstrap' in filename\n\n\n_warned: Set[str] = set()\n\n\ndef _deduped_module_warn_or_error(old_module_name, new_module_name, deadline):\n if old_module_name in _warned:\n return\n\n _warned.add(old_module_name)\n\n _warn_or_error(\n f\"{old_module_name} was used but is deprecated.\\n \"\n f\"it will be removed in cirq {deadline}.\\n \"\n f\"Use {new_module_name} instead.\\n\",\n )\n\n\nclass DeprecatedModuleFinder(importlib.abc.MetaPathFinder):\n \"\"\"A module finder to handle deprecated module references.\n\n It sends a deprecation warning when a deprecated module is asked to be found.\n It is meant to be used as a wrapper around existing MetaPathFinder instances.\n\n Args:\n finder: the finder to wrap.\n new_module_name: the new module's fully qualified name\n old_module_name: the deprecated module's fully qualified name\n deadline: the deprecation deadline\n \"\"\"\n\n def __init__(\n self,\n finder: Any,\n new_module_name: str,\n old_module_name: str,\n deadline: str,\n ):\n \"\"\"An aliasing module finder that uses an existing module finder to find a python\n module spec and intercept the execution of matching modules.\n \"\"\"\n self.finder = finder\n self.new_module_name = new_module_name\n self.old_module_name = old_module_name\n self.deadline = deadline\n # to cater for metadata path finders\n # https://docs.python.org/3/library/importlib.metadata.html#extending-the-search-algorithm\n if hasattr(finder, \"find_distributions\"):\n\n def find_distributions(context):\n return self.finder.find_distributions(context)\n\n self.find_distributions = find_distributions\n if hasattr(finder, \"invalidate_caches\"):\n\n def invalidate_caches() -> None:\n return self.finder.invalidate_caches()\n\n # mypy#2427\n self.invalidate_caches = invalidate_caches # type: ignore\n\n def find_spec(self, fullname: str, path: Any = None, target: Any = None) -> Any:\n \"\"\"Finds the specification of a module.\n\n This is an implementation of the importlib.abc.MetaPathFinder.find_spec method.\n See https://docs.python.org/3/library/importlib.html#importlib.abc.MetaPathFinder.\n\n Args:\n fullname: name of the module.\n path: if presented, this is the parent module's submodule search path.\n target: When passed in, target is a module object that the finder may use to make a more\n educated guess about what spec to return. We don't use it here, just pass it along\n to the wrapped finder.\n \"\"\"\n if fullname != self.old_module_name and not fullname.startswith(self.old_module_name + \".\"):\n # if we are not interested in it, then just pass through to the wrapped finder\n return self.finder.find_spec(fullname, path, target)\n\n # warn for deprecation\n _deduped_module_warn_or_error(self.old_module_name, self.new_module_name, self.deadline)\n\n new_fullname = self.new_module_name + fullname[len(self.old_module_name) :]\n\n # find the corresponding spec in the new structure\n if fullname == self.old_module_name:\n # this is the first time the deprecated module is being found\n # which means that the new parent needs to be found first and under\n # the new parent's path, we should be able to find the new name of\n # the deprecated module\n # this code is heavily inspired by importlib.util.find_spec\n parent_name = new_fullname.rpartition('.')[0]\n if parent_name:\n parent = __import__(parent_name, fromlist=['__path__'])\n # note that compared to importlib.util.find_spec we don't handle\n # AttributeError here because it is not expected to happen in case\n # of a DeprecatedModuleLoader - the new parent should exist and be\n # a proper package\n parent_path = parent.__path__\n else:\n parent_path = None\n spec = self.finder.find_spec(new_fullname, parent_path, None)\n else:\n # we are finding a submodule of the parent of the deprecated module,\n # which means that the parent was already found, and thus, `path` is\n # correctly pointing to the module's parent in the new hierarchy\n spec = self.finder.find_spec(\n new_fullname,\n path=path,\n target=target,\n )\n\n # if the spec exists, return the DeprecatedModuleLoader that will do the loading as well\n # as set the alias(es) in sys.modules as necessary\n if spec is not None:\n # change back the name to the deprecated module name\n spec.name = fullname\n # some loaders do a check to ensure the module's name is the same\n # as the loader was created for\n if getattr(spec.loader, \"name\", None) == new_fullname:\n setattr(spec.loader, \"name\", fullname)\n spec.loader = DeprecatedModuleLoader(spec.loader, fullname, new_fullname)\n return spec\n\n\ndef deprecated_submodule(\n *, new_module_name: str, old_parent: str, old_child: str, deadline: str, create_attribute: bool\n):\n \"\"\"Creates a deprecated module reference recursively for a module.\n\n For `new_module_name` (e.g. cirq_google) creates an alias (e.g cirq.google) in Python's module\n cache. It also recursively checks for the already imported submodules (e.g. cirq_google.api) and\n creates the alias for them too (e.g. cirq.google.api). With this method it is possible to create\n an alias that really looks like a module, e.g you can do things like\n `from cirq.google import api` - which would be otherwise impossible.\n\n Note that this method will execute `new_module_name` in order to ensure that it is in the module\n cache.\n\n Args:\n new_module_name: absolute module name for the new module\n old_parent: the current module that had the original submodule\n old_child: the submodule that is being relocated\n create_attribute: if True, the submodule will be added as a deprecated attribute to the\n old_parent module\n Returns:\n None\n \"\"\"\n _validate_deadline(deadline)\n\n old_module_name = f\"{old_parent}.{old_child}\"\n\n if create_attribute:\n new_module = importlib.import_module(new_module_name)\n _setup_deprecated_submodule_attribute(\n new_module_name, old_parent, old_child, deadline, new_module\n )\n\n def wrap(finder: Any) -> Any:\n if not hasattr(finder, 'find_spec'):\n return finder\n # this is just to make mypy not complain about the type of new_module_spec being Optional\n return DeprecatedModuleFinder(finder, new_module_name, old_module_name, deadline)\n\n sys.meta_path = [wrap(finder) for finder in sys.meta_path]\n\n\ndef _setup_deprecated_submodule_attribute(\n new_module_name: str, old_parent: str, old_child: str, deadline: str, new_module: ModuleType\n):\n parent_module = sys.modules[old_parent]\n setattr(parent_module, old_child, new_module)\n\n class Wrapped(ModuleType):\n __dict__ = parent_module.__dict__\n\n def __getattr__(self, name):\n if name == old_child:\n _deduped_module_warn_or_error(\n f\"{old_parent}.{old_child}\", new_module_name, deadline\n )\n return getattr(parent_module, name)\n\n sys.modules[old_parent] = Wrapped(parent_module.__name__, parent_module.__doc__)\n", "from dataclasses import dataclass\nfrom tequila import TequilaException, BitString, TequilaWarning\nfrom tequila.hamiltonian import QubitHamiltonian\n\nfrom tequila.circuit import QCircuit, gates\nfrom tequila.objective.objective import Variable, Variables, ExpectationValue\n\nfrom tequila.simulators.simulator_api import simulate\nfrom tequila.utils import to_float\n\nimport typing, numpy, numbers\nfrom itertools import product\n\nimport openfermion\nfrom openfermion.hamiltonians import MolecularData\n\nimport warnings\n\n\ndef prepare_product_state(state: BitString) -> QCircuit:\n \"\"\"Small convenience function\n\n Parameters\n ----------\n state :\n product state encoded into a bitstring\n state: BitString :\n \n\n Returns\n -------\n type\n unitary circuit which prepares the product state\n\n \"\"\"\n result = QCircuit()\n for i, v in enumerate(state.array):\n if v == 1:\n result += gates.X(target=i)\n return result\n\n\n@dataclass\nclass ParametersQC:\n \"\"\"Specialization of ParametersHamiltonian\"\"\"\n basis_set: str = '' # Quantum chemistry basis set\n geometry: str = '' # geometry of the underlying molecule (units: Angstrom!),\n # this can be a filename leading to an .xyz file or the geometry given as a string\n description: str = ''\n multiplicity: int = 1\n charge: int = 0\n closed_shell: bool = True\n name: str = \"molecule\"\n\n @property\n def filename(self):\n \"\"\" \"\"\"\n return \"{}_{}\".format(self.name, self.basis_set)\n\n @property\n def molecular_data_param(self) -> dict:\n \"\"\":return: Give back all parameters for the MolecularData format from openfermion as dictionary\"\"\"\n return {'basis': self.basis_set, 'geometry': self.get_geometry(), 'description': self.description,\n 'charge': self.charge, 'multiplicity': self.multiplicity, 'filename': self.filename\n }\n\n @staticmethod\n def format_element_name(string):\n \"\"\"OpenFermion uses case sensitive hash tables for chemical elements\n I.e. you need to name Lithium: 'Li' and 'li' or 'LI' will not work\n this convenience function does the naming\n :return: first letter converted to upper rest to lower\n\n Parameters\n ----------\n string :\n \n\n Returns\n -------\n\n \"\"\"\n assert (len(string) > 0)\n assert (isinstance(string, str))\n fstring = string[0].upper() + string[1:].lower()\n return fstring\n\n @staticmethod\n def convert_to_list(geometry):\n \"\"\"Convert a molecular structure given as a string into a list suitable for openfermion\n\n Parameters\n ----------\n geometry :\n a string specifying a mol. structure. E.g. geometry=\"h 0.0 0.0 0.0\\n h 0.0 0.0 1.0\"\n\n Returns\n -------\n type\n A list with the correct format for openfermion E.g return [ ['h',[0.0,0.0,0.0], [..]]\n\n \"\"\"\n result = []\n for line in geometry.split('\\n'):\n words = line.split()\n if len(words) != 4: break\n try:\n tmp = (ParametersQC.format_element_name(words[0]),\n (float(words[1]), float(words[2]), float(words[3])))\n result.append(tmp)\n except ValueError:\n print(\"get_geometry list unknown line:\\n \", line, \"\\n proceed with caution!\")\n return result\n\n def get_geometry_string(self) -> str:\n \"\"\"returns the geometry as a string\n :return: geometry string\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n if self.geometry.split('.')[-1] == 'xyz':\n geomstring, comment = self.read_xyz_from_file(self.geometry)\n if comment is not None:\n self.description = comment\n return geomstring\n else:\n return self.geometry\n\n def get_geometry(self):\n \"\"\"Returns the geometry\n If a xyz filename was given the file is read out\n otherwise it is assumed that the geometry was given as string\n which is then reformatted as a list usable as input for openfermion\n :return: geometry as list\n e.g. [(h,(0.0,0.0,0.35)),(h,(0.0,0.0,-0.35))]\n Units: Angstrom!\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n if self.geometry.split('.')[-1] == 'xyz':\n geomstring, comment = self.read_xyz_from_file(self.geometry)\n if self.description == '':\n self.description = comment\n if self.name == \"molecule\":\n self.name = self.geometry.split('.')[0]\n return self.convert_to_list(geomstring)\n elif self.geometry is not None:\n return self.convert_to_list(self.geometry)\n else:\n raise Exception(\"Parameters.qc.geometry is None\")\n\n @staticmethod\n def read_xyz_from_file(filename):\n \"\"\"Read XYZ filetype for molecular structures\n https://en.wikipedia.org/wiki/XYZ_file_format\n Units: Angstrom!\n\n Parameters\n ----------\n filename :\n return:\n\n Returns\n -------\n\n \"\"\"\n with open(filename, 'r') as file:\n content = file.readlines()\n natoms = int(content[0])\n comment = str(content[1]).strip('\\n')\n coord = ''\n for i in range(natoms):\n coord += content[2 + i]\n return coord, comment\n\n\n@dataclass\nclass ClosedShellAmplitudes:\n \"\"\" \"\"\"\n tIjAb: numpy.ndarray = None\n tIA: numpy.ndarray = None\n\n def make_parameter_dictionary(self, threshold=1.e-8):\n \"\"\"\n\n Parameters\n ----------\n threshold :\n (Default value = 1.e-8)\n\n Returns\n -------\n\n \"\"\"\n variables = {}\n if self.tIjAb is not None:\n nvirt = self.tIjAb.shape[2]\n nocc = self.tIjAb.shape[0]\n assert (self.tIjAb.shape[1] == nocc and self.tIjAb.shape[3] == nvirt)\n for (I, J, A, B), value in numpy.ndenumerate(self.tIjAb):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(nocc + A, I, nocc + B, J)] = value\n if self.tIA is not None:\n nocc = self.tIA.shape[0]\n for (I, A), value, in numpy.ndenumerate(self.tIA):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(A + nocc, I)] = value\n\n return dict(sorted(variables.items(), key=lambda x: numpy.abs(x[1]), reverse=True))\n\n\n@dataclass\nclass Amplitudes:\n \"\"\"Coupled-Cluster Amplitudes\n We adopt the Psi4 notation for consistency\n I,A for alpha\n i,a for beta\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n\n @classmethod\n def from_closed_shell(cls, cs: ClosedShellAmplitudes):\n \"\"\"\n Initialize from closed-shell Amplitude structure\n\n Parameters\n ----------\n cs: ClosedShellAmplitudes :\n \n\n Returns\n -------\n\n \"\"\"\n tijab = cs.tIjAb - numpy.einsum(\"ijab -> ijba\", cs.tIjAb, optimize='greedy')\n return cls(tIjAb=cs.tIjAb, tIA=cs.tIA, tiJaB=cs.tIjAb, tia=cs.tIA, tijab=tijab, tIJAB=tijab)\n\n tIjAb: numpy.ndarray = None\n tIA: numpy.ndarray = None\n tiJaB: numpy.ndarray = None\n tijab: numpy.ndarray = None\n tIJAB: numpy.ndarray = None\n tia: numpy.ndarray = None\n\n def make_parameter_dictionary(self, threshold=1.e-8):\n \"\"\"\n\n Parameters\n ----------\n threshold :\n (Default value = 1.e-8)\n Neglect amplitudes below the threshold\n\n Returns\n -------\n Dictionary of tequila variables (hash is in the style of (a,i,b,j))\n\n \"\"\"\n variables = {}\n if self.tIjAb is not None:\n nvirt = self.tIjAb.shape[2]\n nocc = self.tIjAb.shape[0]\n assert (self.tIjAb.shape[1] == nocc and self.tIjAb.shape[3] == nvirt)\n\n for (I, j, A, b), value in numpy.ndenumerate(self.tIjAb):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (nocc + A), 2 * I, 2 * (nocc + b) + 1, j + 1)] = value\n for (i, J, a, B), value in numpy.ndenumerate(self.tiJaB):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (nocc + a) + 1, 2 * i + 1, 2 * (nocc + B), J)] = value\n for (i, j, a, b), value in numpy.ndenumerate(self.tijab):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (nocc + a) + 1, 2 * i + 1, 2 * (nocc + b) + 1, j + 1)] = value\n for (I, J, A, B), value in numpy.ndenumerate(self.tijab):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (nocc + A), 2 * I, 2 * (nocc + B), J)] = value\n\n if self.tIA is not None:\n nocc = self.tIjAb.shape[0]\n assert (self.tia.shape[0] == nocc)\n for (I, A), value, in numpy.ndenumerate(self.tIA):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (A + nocc), 2 * I)] = value\n for (i, a), value, in numpy.ndenumerate(self.tIA):\n if not numpy.isclose(value, 0.0, atol=threshold):\n variables[(2 * (a + nocc) + 1, 2 * i + 1)] = value\n\n return variables\n\n\nclass NBodyTensor:\n \"\"\" Convenience class for handling N-body tensors \"\"\"\n\n def __init__(self, elems: numpy.ndarray = None, active_indices: list = None, scheme: str = None,\n size_full: int = None):\n\n # Set elements\n self.elems = elems\n # Active indices only as list of indices (e.g. spatial orbital indices), not as a dictionary of irreducible\n # representations\n if active_indices is not None:\n self.active_indices = active_indices\n self._passive_indices = None\n self._full_indices = None\n self._indices_set: bool = False\n\n # Determine order of tensor\n # Assume, that tensor is entered in desired shape, not as flat array.\n self.order = len(self.elems.shape)\n # Can use size_full < self.elems.shape[0] -> 'full' space is to be considered a subspace as well\n if size_full is None:\n self._size_full = self.elems.shape[0]\n else:\n self._size_full = size_full\n # 2-body tensors (<=> order 4) currently allow reordering\n if self.order == 4:\n if scheme is None:\n self.scheme = 'chem'\n else:\n self.scheme = scheme.lower()\n else:\n if scheme is not None:\n raise Exception(\"Ordering only implemented for tensors of order 4 / 2-body tensors.\")\n self.scheme = None\n\n def sub_lists(self, idx_lists: list = None) -> numpy.ndarray:\n \"\"\"\n Get subspace of tensor by a set of index lists\n according to hPQ.sub_lists(idx_lists=[p, q]) = [hPQ for P in p and Q in q]\n\n This essentially is an implementation of a non-contiguous slicing using numpy.take\n\n Parameters\n ----------\n idx_lists :\n List of lists, each defining the desired subspace per axis\n Size needs to match order of tensor, and lists successively correspond to axis=0,1,2,...,N\n\n Returns\n -------\n out :\n Sliced tensor as numpy.ndarray\n \"\"\"\n # Check if index list has correct size\n if len(idx_lists) != self.order:\n raise Exception(\"Need to pass an index list for each dimension!\" +\n \" Length of idx_lists needs to match order of tensor.\")\n\n # Perform slicing via numpy.take\n out = self.elems\n for ax in range(self.order):\n if idx_lists[ax] is not None: # None means, we want the full space in this direction\n out = numpy.take(out, idx_lists[ax], axis=ax)\n\n return out\n\n def set_index_lists(self):\n \"\"\" Set passive and full index lists based on class inputs \"\"\"\n tmp_size = self._size_full\n if self._size_full is None:\n tmp_size = self.elems.shape[0]\n\n self._passive_indices = [i for i in range(tmp_size)\n if i not in self.active_indices]\n self._full_indices = [i for i in range(tmp_size)]\n\n def sub_str(self, name: str) -> numpy.ndarray:\n \"\"\"\n Get subspace of tensor by a string\n Currently is able to resolve an active space, named 'a', full space 'f', and the complement 'p' = 'f' - 'a'.\n Full space in this context may also be smaller than actual tensor dimension.\n\n The specification of active space in this context only allows to pick a set from a list of orbitals, and\n is not able to resolve an active space from irreducible representations.\n\n Example for one-body tensor:\n hPQ.sub_lists(name='ap') = [hPQ for P in active_indices and Q in _passive_indices]\n\n Parameters\n ----------\n name :\n String specifying the desired subspace, elements need to be a (active), f (full), p (full - active)\n\n Returns\n -------\n out :\n Sliced tensor as numpy.ndarray\n \"\"\"\n if not self._indices_set:\n self.set_index_lists()\n self._indices_set = True\n\n if name is None:\n raise Exception(\"No name specified.\")\n if len(name) != self.order:\n raise Exception(\"Name does not match order of the tensor.\")\n if self.active_indices is None:\n raise Exception(\"Need to set an active space in order to call this function.\")\n\n idx_lists = []\n # Parse name as string of space indices\n for char in name:\n if char.lower() == 'a':\n idx_lists.append(self.active_indices)\n elif char.lower() == 'p':\n idx_lists.append(self._passive_indices)\n elif char.lower() == 'f':\n if self._size_full is None:\n idx_lists.append(None)\n else:\n idx_lists.append(self._full_indices)\n else:\n raise Exception(\"Need to specify a valid letter (a,p,f).\")\n\n out = self.sub_lists(idx_lists)\n\n return out\n\n def is_openfermion(self) -> bool:\n \"\"\"\n Checks whether current ordering scheme is 'openfermion'\n \"\"\"\n if self.scheme == 'openfermion' or self.scheme == 'of':\n return True\n else:\n return False\n\n def is_chem(self) -> bool:\n \"\"\"\n Checks whether current ordering scheme is 'chem'\n \"\"\"\n if self.scheme == 'chem' or self.scheme == 'c':\n return True\n else:\n return False\n\n def is_phys(self) -> bool:\n \"\"\"\n Checks whether current ordering scheme is 'phys'\n \"\"\"\n if self.scheme == 'phys' or self.scheme == 'p':\n return True\n else:\n return False\n\n def reorder(self, to: str = 'of'):\n \"\"\"\n Function to reorder tensors according to some convention.\n\n Parameters\n ----------\n to :\n Ordering scheme of choice.\n 'openfermion', 'of' (default) :\n openfermion - ordering, corresponds to integrals of the type\n h^pq_rs = int p(1)* q(2)* O(1,2) r(2) s(1) (O(1,2)\n with operators a^pq_rs = a^p a^q a_r a_s (a^p == a^dagger_p)\n currently needed for dependencies on openfermion-library\n 'chem', 'c' :\n quantum chemistry ordering, collect particle terms,\n more convenient for real-space methods\n h^pq_rs = int p(1) q(1) O(1,2) r(2) s(2)\n This is output by psi4\n 'phys', 'p' :\n typical physics ordering, integrals of type\n h^pq_rs = int p(1)* q(2)* O(1,2) r(1) s(2)\n with operators a^pq_rs = a^p a^q a_s a_r\n\n Returns\n -------\n \"\"\"\n if self.order != 4:\n raise Exception('Reordering currently only implemented for two-body tensors.')\n to = to.lower()\n\n if self.is_chem():\n if to == 'chem' or to == 'c':\n pass\n elif to == 'openfermion' or to == 'of':\n self.elems = numpy.einsum(\"psqr -> pqrs\", self.elems, optimize='greedy')\n self.scheme = 'openfermion'\n elif to == 'phys' or to == 'p':\n self.elems = numpy.einsum(\"prqs -> pqrs\", self.elems, optimize='greedy')\n self.scheme = 'phys'\n elif self.is_openfermion():\n if to == 'chem' or to == 'c':\n self.elems = numpy.einsum(\"pqrs -> psqr\", self.elems, optimize='greedy')\n self.scheme = 'chem'\n elif to == 'openfermion' or to == 'of':\n pass\n elif to == 'phys' or to == 'p':\n self.elems = numpy.einsum(\"pqrs -> pqsr\", self.elems, optimize='greedy')\n self.scheme = 'phys'\n elif self.is_phys():\n if to == 'chem' or to == 'c':\n self.elems = numpy.einsum(\"pqrs -> prqs\", self.elems, optimize='greedy')\n self.scheme = 'chem'\n elif to == 'openfermion' or to == 'of':\n self.elems = numpy.einsum(\"pqsr -> pqrs\", self.elems, optimize='greedy')\n self.scheme = 'openfermion'\n elif to == 'phys' or to == 'p':\n pass\n\n\nclass QuantumChemistryBase:\n \"\"\" \"\"\"\n\n class _QubitEncoding:\n \"\"\"\n Small wrapper class for the Qubit Transformation\n Provides more controlled output and handles special cases\n \"\"\"\n\n def __init__(self, transformation: typing.Callable, **kwargs):\n self._trafo = transformation\n self._kwargs = kwargs\n\n def __call__(self, op):\n errlog = \"\"\n try:\n try:\n return self._trafo(op, **self._kwargs)\n except TypeError as E:\n print(\"converting to interaction operator\")\n errlog += \"\\n\" + str(E)\n return self._trafo(openfermion.get_interaction_operator(op), **self._kwargs)\n except Exception as E:\n errlog += \"\\n\" + str(E)\n raise TequilaException(\"Error in QubitEncoding \" + str(self) + errlog)\n\n def __repr__(self):\n if len(self._kwargs) > 0:\n return \"transformation=\" + str(self._trafo) + \"\\nadditional keys: \" + str(self._kwargs)\n else:\n return \"transformation=\" + str(self._trafo)\n\n def __str__(self):\n return self.__repr__()\n\n def __init__(self, parameters: ParametersQC,\n transformation: typing.Union[str, typing.Callable] = None,\n active_orbitals: list = None,\n reference: list = None,\n *args,\n **kwargs):\n\n self.parameters = parameters\n\n if \"molecule\" in kwargs:\n self.molecule = kwargs[\"molecule\"]\n else:\n self.molecule = self.make_molecule(*args, **kwargs)\n\n assert (parameters.basis_set.lower() == self.molecule.basis.lower())\n assert (parameters.multiplicity == self.molecule.multiplicity)\n assert (parameters.charge == self.molecule.charge)\n\n self.active_space = None\n if active_orbitals is not None:\n self.active_space = self._make_active_space_data(active_orbitals=active_orbitals, reference=reference)\n\n if reference is None:\n self.reference = [i for i in range(self.n_electrons // 2)]\n else:\n self.reference = reference\n\n self.transformation = self._initialize_transformation(transformation=transformation, *args, **kwargs)\n self._rdm1 = None\n self._rdm2 = None\n def _initialize_transformation(self, transformation, *args, **kwargs):\n # filter out arguments to the transformation\n trafo_args = {k.split(\"__\")[1]: v for k, v in kwargs.items() if\n (hasattr(k, \"lower\") and \"transformation__\" in k.lower())}\n\n if transformation is None:\n trafo = openfermion.jordan_wigner\n elif hasattr(transformation, \"lower\") and transformation.lower() in [\"jordan-wigner\", \"jw\", \"j-w\",\n \"jordanwigner\"]:\n trafo = openfermion.jordan_wigner\n elif hasattr(transformation, \"lower\") and transformation.lower() in [\"bravyi-kitaev\", \"bk\", \"b-k\",\n \"bravyikitaev\"]:\n trafo = openfermion.bravyi_kitaev\n elif hasattr(transformation, \"lower\") and transformation.lower() in [\"bravyi-kitaev-tree\", \"bkt\",\n \"bravykitaevtree\", \"b-k-t\"]:\n trafo = openfermion.bravyi_kitaev_tree\n elif hasattr(transformation, \"lower\") and transformation.lower() in [\"tapered_bravyi_kitaev\", \"tbk\", \"t-b-k\",\n \"symmetry_conserving_bravyi_kitaev\"]:\n if \"active_orbitals\" not in trafo_args:\n trafo_args[\"active_orbitals\"] = self.n_orbitals * 2\n if \"active_fermions\" not in trafo_args:\n trafo_args[\"active_fermions\"] = self.n_electrons\n print(\"trafo_args = \", trafo_args)\n trafo = openfermion.symmetry_conserving_bravyi_kitaev\n\n elif hasattr(transformation, \"lower\"):\n trafo = getattr(openfermion, transformation.lower())\n else:\n assert (callable(transformation))\n trafo = transformation\n\n return self._QubitEncoding(transformation=trafo, **trafo_args)\n\n def _make_active_space_data(self, active_orbitals, reference=None):\n \"\"\"\n Small helper function\n Internal use only\n Parameters\n ----------\n active_orbitals: dictionary :\n list: Give a list of spatial orbital indices\n i.e. occ = [0,1,3] means that spatial orbital 0, 1 and 3 are used\n reference: (Default value=None)\n List of orbitals which form the reference\n Can be given in the same format as active_orbitals\n If given as None then the first N_electron/2 orbitals are taken\n for closed-shell systems.\n\n Returns\n -------\n Dataclass with active indices and reference indices (in spatial notation)\n\n \"\"\"\n\n if active_orbitals is None:\n return None\n\n @dataclass\n class ActiveSpaceData:\n active_orbitals: list # active orbitals (spatial, c1)\n reference_orbitals: list # reference orbitals (spatial, c1)\n\n def __str__(self):\n result = \"Active Space Data:\\n\"\n result += \"{key:15} : {value:15} \\n\".format(key=\"active_orbitals\", value=str(self.active_orbitals))\n result += \"{key:15} : {value:15} \\n\".format(key=\"reference_orbitals\",\n value=str(self.reference_orbitals))\n result += \"{key:15} : {value:15} \\n\".format(key=\"frozen_docc\", value=str(self.frozen_docc))\n result += \"{key:15} : {value:15} \\n\".format(key=\"frozen_uocc\", value=str(self.frozen_uocc))\n return result\n\n @property\n def frozen_reference_orbitals(self):\n return [i for i in self.reference_orbitals if i not in self.active_orbitals]\n\n @property\n def active_reference_orbitals(self):\n return [i for i in self.reference_orbitals if i in self.active_orbitals]\n\n if reference is None:\n # auto assignment only for closed-shell\n assert (self.n_electrons % 2 == 0)\n reference = sorted([i for i in range(self.n_electrons // 2)])\n\n return ActiveSpaceData(active_orbitals=sorted(active_orbitals),\n reference_orbitals=sorted(reference))\n\n @classmethod\n def from_openfermion(cls, molecule: openfermion.MolecularData,\n transformation: typing.Union[str, typing.Callable] = None,\n *args,\n **kwargs):\n \"\"\"\n Initialize direclty from openfermion MolecularData object\n\n Parameters\n ----------\n molecule\n The openfermion molecule\n Returns\n -------\n The Tequila molecule\n \"\"\"\n parameters = ParametersQC(basis_set=molecule.basis, geometry=molecule.geometry,\n description=molecule.description, multiplicity=molecule.multiplicity,\n charge=molecule.charge)\n return cls(parameters=parameters, transformation=transformation, molecule=molecule, *args, **kwargs)\n\n def make_excitation_generator(self, indices: typing.Iterable[typing.Tuple[int, int]]) -> QubitHamiltonian:\n \"\"\"\n Notes\n ----------\n Creates the transformed hermitian generator of UCC type unitaries:\n M(a^\\dagger_{a_0} a_{i_0} a^\\dagger{a_1}a_{i_1} ... - h.c.)\n where the qubit map M depends is self.transformation\n\n Parameters\n ----------\n indices : typing.Iterable[typing.Tuple[int, int]] :\n List of tuples [(a_0, i_0), (a_1, i_1), ... ] - recommended format, in spin-orbital notation (alpha odd numbers, beta even numbers)\n can also be given as one big list: [a_0, i_0, a_1, i_1 ...]\n Returns\n -------\n type\n 1j*Transformed qubit excitation operator, depends on self.transformation\n \"\"\"\n\n if self.transformation._trafo == openfermion.bravyi_kitaev_fast:\n raise TequilaException(\n \"The Bravyi-Kitaev-Superfast transformation does not support general FermionOperators yet\")\n\n # check indices and convert to list of tuples if necessary\n if len(indices) == 0:\n raise TequilaException(\"make_excitation_operator: no indices given\")\n elif not isinstance(indices[0], typing.Iterable):\n if len(indices) % 2 != 0:\n raise TequilaException(\"make_excitation_generator: unexpected input format of indices\\n\"\n \"use list of tuples as [(a_0, i_0),(a_1, i_1) ...]\\n\"\n \"or list as [a_0, i_0, a_1, i_1, ... ]\\n\"\n \"you gave: {}\".format(indices))\n converted = [(indices[2 * i], indices[2 * i + 1]) for i in range(len(indices) // 2)]\n else:\n converted = indices\n\n # convert to openfermion input format\n ofi = []\n dag = []\n for pair in converted:\n assert (len(pair) == 2)\n ofi += [(int(pair[0]), 1),\n (int(pair[1]), 0)] # openfermion does not take other types of integers like numpy.int64\n dag += [(int(pair[0]), 0), (int(pair[1]), 1)]\n\n op = openfermion.FermionOperator(tuple(ofi), 1.j) # 1j makes it hermitian\n op += openfermion.FermionOperator(tuple(reversed(dag)), -1.j)\n qop = QubitHamiltonian(qubit_hamiltonian=self.transformation(op))\n\n # check if the operator is hermitian and cast coefficients to floats\n # in order to avoid trouble with the simulation backends\n assert qop.is_hermitian()\n for k, v in qop.qubit_operator.terms.items():\n qop.qubit_operator.terms[k] = to_float(v)\n\n qop = qop.simplify()\n\n if len(qop) == 0:\n warnings.warn(\"Excitation generator is a unit operator.\\n\"\n \"Non-standard transformations might not work with general fermionic operators\\n\"\n \"indices = \" + str(indices), category=TequilaWarning)\n return qop\n\n def reference_state(self, reference_orbitals: list = None, n_qubits: int = None) -> BitString:\n \"\"\"Does a really lazy workaround ... but it works\n :return: Hartree-Fock Reference as binary-number\n\n Parameters\n ----------\n reference_orbitals: list:\n give list of doubly occupied orbitals\n default is None which leads to automatic list of the\n first n_electron/2 orbitals\n\n Returns\n -------\n\n \"\"\"\n\n if n_qubits is None:\n n_qubits = 2 * self.n_orbitals\n\n if self.transformation._trafo == openfermion.symmetry_conserving_bravyi_kitaev:\n def tapering(fop):\n fermion_hamiltonian_reorder = openfermion.utils.reorder(fop, openfermion.utils.up_then_down,\n num_modes=n_qubits)\n qubit_hamiltonian = openfermion.bravyi_kitaev_tree(fermion_hamiltonian_reorder, n_qubits=n_qubits)\n qubit_hamiltonian.compress()\n return qubit_hamiltonian\n\n transformation = tapering\n else:\n transformation = self.transformation\n\n if reference_orbitals is None:\n reference_orbitals = self.reference\n\n spin_orbitals = sorted([2 * i for i in reference_orbitals] + [2 * i + 1 for i in reference_orbitals])\n\n string = \"1.0 [\"\n for i in spin_orbitals:\n string += str(i) + \"^ \"\n string += \"]\"\n\n fop = openfermion.FermionOperator(string, 1.0)\n op = QubitHamiltonian(qubit_hamiltonian=transformation(fop))\n from tequila.wavefunction.qubit_wavefunction import QubitWaveFunction\n wfn = QubitWaveFunction.from_int(0, n_qubits=n_qubits)\n wfn = wfn.apply_qubitoperator(operator=op)\n assert (len(wfn.keys()) == 1)\n key = list(wfn.keys())[0]\n if self.transformation._trafo == openfermion.symmetry_conserving_bravyi_kitaev:\n active_qubits = [i for i in range(n_qubits) if i not in [n_qubits - 1, n_qubits // 2 - 1]]\n array = [key.array[i] for i in active_qubits]\n key = BitString.from_array(array=array)\n return key\n\n def make_molecule(self, *args, **kwargs) -> MolecularData:\n \"\"\"Creates a molecule in openfermion format by running psi4 and extracting the data\n Will check for previous outputfiles before running\n Will not recompute if a file was found\n\n Parameters\n ----------\n parameters :\n An instance of ParametersQC, which also holds an instance of ParametersPsi4 via parameters.psi4\n The molecule will be saved in parameters.filename, if this file exists before the call the molecule will be imported from the file\n\n Returns\n -------\n type\n the molecule in openfermion.MolecularData format\n\n \"\"\"\n molecule = MolecularData(**self.parameters.molecular_data_param)\n # try to load\n\n do_compute = True\n try:\n import os\n if os.path.exists(self.parameters.filename):\n molecule.load()\n do_compute = False\n except OSError:\n do_compute = True\n\n if do_compute:\n molecule = self.do_make_molecule(*args, **kwargs)\n\n molecule.save()\n return molecule\n\n def do_make_molecule(self, *args, **kwargs):\n \"\"\"\n\n Parameters\n ----------\n args\n kwargs\n\n Returns\n -------\n\n \"\"\"\n # integrals need to be passed in base class\n assert (\"one_body_integrals\" in kwargs)\n assert (\"two_body_integrals\" in kwargs)\n assert (\"nuclear_repulsion\" in kwargs)\n assert (\"n_orbitals\" in kwargs)\n\n molecule = MolecularData(**self.parameters.molecular_data_param)\n\n molecule.one_body_integrals = kwargs[\"one_body_integrals\"]\n molecule.two_body_integrals = kwargs[\"two_body_integrals\"]\n molecule.nuclear_repulsion = kwargs[\"nuclear_repulsion\"]\n molecule.n_orbitals = kwargs[\"n_orbitals\"]\n molecule.save()\n return molecule\n\n @property\n def n_orbitals(self) -> int:\n \"\"\" \"\"\"\n if self.active_space is None:\n return self.molecule.n_orbitals\n else:\n return len(self.active_space.active_orbitals)\n\n @property\n def n_electrons(self) -> int:\n \"\"\" \"\"\"\n if self.active_space is None:\n return self.molecule.n_electrons\n else:\n return 2 * len(self.active_space.active_reference_orbitals)\n\n def make_hamiltonian(self, occupied_indices=None, active_indices=None) -> QubitHamiltonian:\n \"\"\" \"\"\"\n if occupied_indices is None and self.active_space is not None:\n occupied_indices = self.active_space.frozen_reference_orbitals\n if active_indices is None and self.active_space is not None:\n active_indices = self.active_space.active_orbitals\n\n fop = openfermion.transforms.get_fermion_operator(\n self.molecule.get_molecular_hamiltonian(occupied_indices, active_indices))\n try:\n qop = self.transformation(fop)\n except TypeError:\n qop = self.transformation(openfermion.transforms.get_interaction_operator(fop))\n return QubitHamiltonian(qubit_hamiltonian=qop)\n\n def compute_one_body_integrals(self):\n \"\"\" \"\"\"\n if hasattr(self, \"molecule\"):\n return self.molecule.one_body_integrals\n\n def compute_two_body_integrals(self):\n \"\"\" \"\"\"\n if hasattr(self, \"molecule\"):\n return self.molecule.two_body_integrals\n\n def compute_ccsd_amplitudes(self) -> ClosedShellAmplitudes:\n \"\"\" \"\"\"\n raise Exception(\"BaseClass Method\")\n\n def prepare_reference(self, *args, **kwargs):\n \"\"\"\n\n Returns\n -------\n A tequila circuit object which prepares the reference of this molecule in the chosen transformation\n \"\"\"\n\n return prepare_product_state(self.reference_state(*args, **kwargs))\n\n def make_upgccsd_ansatz(self,\n include_singles:bool=True,\n include_reference:bool=True,\n indices:list=None,\n order:int =1,\n *args, **kwargs):\n \"\"\"\n UpGCCSD Ansatz similar as described by Lee et. al.\n\n Parameters\n ----------\n include_singles\n include singles excitations\n include_reference\n include the HF reference state as initial state\n indices\n pass custom defined set of indices from which the ansatz will be created\n List of tuples of tuples spin-indices e.g. [((2*p,2*q),(2*p+1,2*q+1)), ...]\n order\n Order of the ansatz (default is 1)\n determines how often the ordering gets repeated\n parameters of repeating layers are independent\n Returns\n -------\n UpGCCSD ansatz\n \"\"\"\n\n # indices defining the UpCCD ansatz\n if indices is None:\n indices = []\n for i in range(self.n_orbitals):\n for a in range(i + 1, self.n_orbitals):\n indices.append(((2 * i, 2 * a), (2 * i + 1, 2 * a + 1)))\n if include_singles:\n indices.append(((2 * i, 2 * a)))\n indices.append(((2 * i + 1, 2 * a + 1)))\n\n U = QCircuit()\n if include_reference:\n U = self.prepare_reference()\n\n generators = [self.make_excitation_generator(i, *args, **kwargs) for i in indices]\n\n for k in range(order):\n idx = [(k,i) for i in indices]\n U += gates.Trotterized(generators=generators, angles=idx, steps=1)\n return U\n\n def make_uccsd_ansatz(self, trotter_steps: int,\n initial_amplitudes: typing.Union[str, Amplitudes, ClosedShellAmplitudes] = \"mp2\",\n include_reference_ansatz=True,\n parametrized=True,\n threshold=1.e-8,\n trotter_parameters: gates.TrotterParameters = None) -> QCircuit:\n \"\"\"\n\n Parameters\n ----------\n initial_amplitudes :\n initial amplitudes given as ManyBodyAmplitudes structure or as string\n where 'mp2', 'cc2' or 'ccsd' are possible initializations\n include_reference_ansatz :\n Also do the reference ansatz (prepare closed-shell Hartree-Fock) (Default value = True)\n parametrized :\n Initialize with variables, otherwise with static numbers (Default value = True)\n trotter_steps: int :\n\n initial_amplitudes: typing.Union[str :\n\n Amplitudes :\n\n ClosedShellAmplitudes] :\n (Default value = \"mp2\")\n trotter_parameters: gates.TrotterParameters :\n (Default value = None)\n\n Returns\n -------\n type\n Parametrized QCircuit\n\n \"\"\"\n\n if self.n_electrons % 2 != 0:\n raise TequilaException(\"make_uccsd_ansatz currently only for closed shell systems\")\n\n nocc = self.n_electrons // 2\n nvirt = self.n_orbitals // 2 - nocc\n\n Uref = QCircuit()\n if include_reference_ansatz:\n Uref = self.prepare_reference()\n\n amplitudes = initial_amplitudes\n if hasattr(initial_amplitudes, \"lower\"):\n if initial_amplitudes.lower() == \"mp2\":\n amplitudes = self.compute_mp2_amplitudes()\n elif initial_amplitudes.lower() == \"ccsd\":\n amplitudes = self.compute_ccsd_amplitudes()\n else:\n try:\n amplitudes = self.compute_amplitudes(method=initial_amplitudes.lower())\n except Exception as exc:\n raise TequilaException(\n \"{}\\nDon't know how to initialize \\'{}\\' amplitudes\".format(exc, initial_amplitudes))\n\n if amplitudes is None:\n amplitudes = ClosedShellAmplitudes(\n tIjAb=numpy.zeros(shape=[nocc, nocc, nvirt, nvirt]),\n tIA=numpy.zeros(shape=[nocc, nvirt]))\n\n closed_shell = isinstance(amplitudes, ClosedShellAmplitudes)\n generators = []\n variables = []\n\n if not isinstance(amplitudes, dict):\n amplitudes = amplitudes.make_parameter_dictionary(threshold=threshold)\n amplitudes = dict(sorted(amplitudes.items(), key=lambda x: x[1]))\n\n for key, t in amplitudes.items():\n assert (len(key) % 2 == 0)\n if not numpy.isclose(t, 0.0, atol=threshold):\n\n if closed_shell:\n spin_indices = []\n if len(key) == 2:\n spin_indices = [[2 * key[0], 2 * key[1]], [2 * key[0] + 1, 2 * key[1] + 1]]\n partner = None\n else:\n spin_indices.append([2 * key[0] + 1, 2 * key[1] + 1, 2 * key[2], 2 * key[3]])\n spin_indices.append([2 * key[0], 2 * key[1], 2 * key[2] + 1, 2 * key[3] + 1])\n if key[0] != key[2] and key[1] != key[3]:\n spin_indices.append([2 * key[0], 2 * key[1], 2 * key[2], 2 * key[3]])\n spin_indices.append([2 * key[0] + 1, 2 * key[1] + 1, 2 * key[2] + 1, 2 * key[3] + 1])\n partner = tuple([key[2], key[1], key[0], key[3]]) # taibj -> tbiaj\n for idx in spin_indices:\n idx = [(idx[2 * i], idx[2 * i + 1]) for i in range(len(idx) // 2)]\n generators.append(self.make_excitation_generator(indices=idx))\n\n if parametrized:\n variables.append(Variable(name=key)) # abab\n variables.append(Variable(name=key)) # baba\n if partner is not None and key[0] != key[1] and key[2] != key[3]:\n variables.append(Variable(name=key) - Variable(partner)) # aaaa\n variables.append(Variable(name=key) - Variable(partner)) # bbbb\n else:\n variables.append(t)\n variables.append(t)\n if partner is not None and key[0] != key[1] and key[2] != key[3]:\n variables.append(t - amplitudes[partner])\n variables.append(t - amplitudes[partner])\n else:\n generators.append(self.make_excitation_operator(indices=spin_indices))\n if parametrized:\n variables.append(Variable(name=key))\n else:\n variables.append(t)\n\n return Uref + gates.Trotterized(generators=generators, angles=variables, steps=trotter_steps,\n parameters=trotter_parameters)\n\n def compute_amplitudes(self, method: str, *args, **kwargs):\n \"\"\"\n Compute closed-shell CC amplitudes\n\n Parameters\n ----------\n method :\n coupled-cluster methods like cc2, ccsd, cc3, ccsd(t)\n Success might depend on backend\n got an extra function for MP2\n *args :\n\n **kwargs :\n\n\n Returns\n -------\n\n \"\"\"\n raise TequilaException(\"compute amplitudes: Needs to be overwritten by backend\")\n\n def compute_mp2_amplitudes(self) -> ClosedShellAmplitudes:\n \"\"\"\n\n Compute closed-shell mp2 amplitudes\n\n .. math::\n t(a,i,b,j) = 0.25 * g(a,i,b,j)/(e(i) + e(j) -a(i) - b(j) )\n\n :return:\n\n Parameters\n ----------\n\n Returns\n -------\n\n \"\"\"\n assert self.parameters.closed_shell\n g = self.molecule.two_body_integrals\n fij = self.molecule.orbital_energies\n nocc = self.molecule.n_electrons // 2 # this is never the active space\n ei = fij[:nocc]\n ai = fij[nocc:]\n abgij = g[nocc:, nocc:, :nocc, :nocc]\n amplitudes = abgij * 1.0 / (\n ei.reshape(1, 1, -1, 1) + ei.reshape(1, 1, 1, -1) - ai.reshape(-1, 1, 1, 1) - ai.reshape(1, -1, 1, 1))\n E = 2.0 * numpy.einsum('abij,abij->', amplitudes, abgij) - numpy.einsum('abji,abij', amplitudes, abgij,\n optimize='greedy')\n\n self.molecule.mp2_energy = E + self.molecule.hf_energy\n return ClosedShellAmplitudes(tIjAb=numpy.einsum('abij -> ijab', amplitudes, optimize='greedy'))\n\n def compute_cis_amplitudes(self):\n \"\"\"\n Compute the CIS amplitudes of the molecule\n \"\"\"\n\n @dataclass\n class ResultCIS:\n \"\"\" \"\"\"\n omegas: typing.List[numbers.Real] # excitation energies [omega0, ...]\n amplitudes: typing.List[ClosedShellAmplitudes] # corresponding amplitudes [x_{ai}_0, ...]\n\n def __getitem__(self, item):\n return (self.omegas[item], self.amplitudes[item])\n\n def __len__(self):\n return len(self.omegas)\n\n g = self.molecule.two_body_integrals\n fij = self.molecule.orbital_energies\n\n nocc = self.n_alpha_electrons\n nvirt = self.n_orbitals - nocc\n\n pairs = []\n for i in range(nocc):\n for a in range(nocc, nocc + nvirt):\n pairs.append((a, i))\n M = numpy.ndarray(shape=[len(pairs), len(pairs)])\n\n for xx, x in enumerate(pairs):\n eia = fij[x[0]] - fij[x[1]]\n a, i = x\n for yy, y in enumerate(pairs):\n b, j = y\n delta = float(y == x)\n gpart = 2.0 * g[a, i, b, j] - g[a, i, j, b]\n M[xx, yy] = eia * delta + gpart\n\n omega, xvecs = numpy.linalg.eigh(M)\n\n # convert amplitudes to ndarray sorted by excitation energy\n nex = len(omega)\n amplitudes = []\n for ex in range(nex):\n t = numpy.ndarray(shape=[nvirt, nocc])\n exvec = xvecs[ex]\n for xx, x in enumerate(pairs):\n a, i = x\n t[a - nocc, i] = exvec[xx]\n amplitudes.append(ClosedShellAmplitudes(tIA=t))\n\n return ResultCIS(omegas=list(omega), amplitudes=amplitudes)\n\n @property\n def rdm1(self):\n \"\"\" \"\"\"\n if self._rdm1 is not None:\n return self._rdm1\n else:\n print(\"1-RDM has not been computed. Return None for 1-RDM.\")\n return None\n\n @property\n def rdm2(self):\n \"\"\" \"\"\"\n if self._rdm2 is not None:\n return self._rdm2\n else:\n print(\"2-RDM has not been computed. Return None for 2-RDM.\")\n return None\n\n def compute_rdms(self, U: QCircuit = None, variables: Variables = None, spin_free: bool = True,\n get_rdm1: bool = True, get_rdm2: bool = True):\n \"\"\"\n Computes the one- and two-particle reduced density matrices (rdm1 and rdm2) given\n a unitary U. This method uses the standard ordering in physics as denoted below.\n Note, that the representation of the density matrices depends on the qubit transformation\n used. The Jordan-Wigner encoding corresponds to 'classical' second quantized density\n matrices in the occupation picture.\n\n We only consider real orbitals and thus real-valued RDMs.\n The matrices are set as private members _rdm1, _rdm2 and can be accessed via the properties rdm1, rdm2.\n\n .. math :\n \\\\text{rdm1: } \\\\gamma^p_q = \\\\langle \\\\psi | a^p a_q | \\\\psi \\\\rangle\n = \\\\langle U 0 | a^p a_q | U 0 \\\\rangle\n \\\\text{rdm2: } \\\\gamma^{pq}_{rs} = \\\\langle \\\\psi | a^p a^q a_s a_r | \\\\psi \\\\rangle\n = \\\\langle U 0 | a^p a^q a_s a_r | U 0 \\\\rangle\n\n Parameters\n ----------\n U :\n Quantum Circuit to achieve the desired state \\\\psi = U |0\\\\rangle, non-optional\n variables :\n If U is parametrized, then need to hand over a set of fixed variables\n spin_free :\n Set whether matrices should be spin-free (summation over spin) or defined by spin-orbitals\n get_rdm1, get_rdm2 :\n Set whether either one or both rdm1, rdm2 should be computed. If both are needed at some point,\n it is recommended to compute them at once.\n\n Returns\n -------\n \"\"\"\n # Set up number of spin-orbitals and molecular orbitals respectively\n n_SOs = 2 * self.n_orbitals\n n_MOs = self.n_orbitals\n\n # Check whether unitary circuit is not 0\n if U is None:\n raise Exception('Need to specify a Quantum Circuit.')\n\n def _get_qop_hermitian(operator_tuple) -> QubitHamiltonian:\n \"\"\" Returns Hermitian part of Fermion operator as QubitHamiltonian \"\"\"\n op = openfermion.FermionOperator(operator_tuple)\n qop = QubitHamiltonian(self.transformation(op))\n real, imag = qop.split(hermitian=True)\n return real\n\n def _build_1bdy_operators_spinful() -> list:\n \"\"\" Returns spinful one-body operators as a symmetry-reduced list of QubitHamiltonians \"\"\"\n # Exploit symmetry pq = qp\n qops = []\n for p in range(n_SOs):\n for q in range(p + 1):\n op_string = ((p, 1), (q, 0))\n qop = _get_qop_hermitian(op_string)\n if qop: # should always exist here\n qops += [qop]\n else: # should not happen\n qops += [QubitHamiltonian.zero()]\n\n return qops\n\n def _build_2bdy_operators_spinful() -> list:\n \"\"\" Returns spinful two-body operators as a symmetry-reduced list of QubitHamiltonians \"\"\"\n # Exploit symmetries pqrs = -pqsr = -qprs = qpsr\n # and = rspq\n qops = []\n for p in range(n_SOs):\n for q in range(p):\n for r in range(n_SOs):\n for s in range(r):\n if p * n_SOs + q >= r * n_SOs + s:\n op_string = ((p, 1), (q, 1), (s, 0), (r, 0))\n qop = _get_qop_hermitian(op_string)\n qops += [qop]\n\n return qops\n\n def _build_1bdy_operators_spinfree() -> list:\n \"\"\" Returns spinfree one-body operators as a symmetry-reduced list of QubitHamiltonians \"\"\"\n # Exploit symmetry pq = qp (not changed by spin-summation)\n qops = []\n for p in range(n_MOs):\n for q in range(p + 1):\n # Spin aa\n op_list = ((2 * p, 1), (2 * q, 0))\n qop = _get_qop_hermitian(op_list)\n # Spin bb\n op_list = ((2 * p + 1, 1), (2 * q + 1, 0))\n qop += _get_qop_hermitian(op_list)\n if qop: # should always exist here\n qops += [qop]\n else:\n qops += [QubitHamiltonian.zero()]\n\n return qops\n\n def _build_2bdy_operators_spinfree() -> list:\n \"\"\" Returns spinfree two-body operators as a symmetry-reduced list of QubitHamiltonians \"\"\"\n # Exploit symmetries pqrs = qpsr (due to spin summation, '-pqsr = -qprs' drops out)\n # and = rspq\n qops = []\n for p, q, r, s in product(range(n_MOs), repeat=4):\n if p * n_MOs + q >= r * n_MOs + s and (p >= q or r >= s):\n # Spin aaaa\n op_string = ((2 * p, 1), (2 * q, 1), (2 * s, 0), (2 * r, 0))\n qop = _get_qop_hermitian(op_string)\n # Spin abab\n op_string = ((2 * p, 1), (2 * q + 1, 1), (2 * s + 1, 0), (2 * r, 0))\n qop += _get_qop_hermitian(op_string)\n # Spin baba\n op_string = ((2 * p + 1, 1), (2 * q, 1), (2 * s, 0), (2 * r + 1, 0))\n qop += _get_qop_hermitian(op_string)\n # Spin bbbb\n op_string = ((2 * p + 1, 1), (2 * q + 1, 1), (2 * s + 1, 0), (2 * r + 1, 0))\n qop += _get_qop_hermitian(op_string)\n\n qops += [qop]\n\n return qops\n\n def _assemble_rdm1(evals_1) -> numpy.ndarray:\n \"\"\"\n Returns spin-ful or spin-free one-particle RDM built by symmetry conditions\n Same symmetry with or without spin, so we can use the same function\n \"\"\"\n N = n_MOs if spin_free else n_SOs\n rdm1 = numpy.zeros([N, N])\n ctr: int = 0\n for p in range(N):\n for q in range(p + 1):\n rdm1[p, q] = evals_1[ctr]\n # Symmetry pq = qp\n rdm1[q, p] = rdm1[p, q]\n ctr += 1\n\n return rdm1\n\n def _assemble_rdm2_spinful(evals_2) -> numpy.ndarray:\n \"\"\" Returns spin-ful two-particle RDM built by symmetry conditions \"\"\"\n ctr: int = 0\n rdm2 = numpy.zeros([n_SOs, n_SOs, n_SOs, n_SOs])\n for p in range(n_SOs):\n for q in range(p):\n for r in range(n_SOs):\n for s in range(r):\n if p * n_SOs + q >= r * n_SOs + s:\n rdm2[p, q, r, s] = evals_2[ctr]\n # Symmetry pqrs = rspq\n rdm2[r, s, p, q] = rdm2[p, q, r, s]\n ctr += 1\n\n # Further permutational symmetries due to anticommutation relations\n for p in range(n_SOs):\n for q in range(p):\n for r in range(n_SOs):\n for s in range(r):\n rdm2[p, q, s, r] = -1 * rdm2[p, q, r, s] # pqrs = -pqsr\n rdm2[q, p, r, s] = -1 * rdm2[p, q, r, s] # pqrs = -qprs\n rdm2[q, p, s, r] = rdm2[p, q, r, s] # pqrs = qpsr\n\n return rdm2\n\n def _assemble_rdm2_spinfree(evals_2) -> numpy.ndarray:\n \"\"\" Returns spin-free two-particle RDM built by symmetry conditions \"\"\"\n ctr: int = 0\n rdm2 = numpy.zeros([n_MOs, n_MOs, n_MOs, n_MOs])\n for p, q, r, s in product(range(n_MOs), repeat=4):\n if p * n_MOs + q >= r * n_MOs + s and (p >= q or r >= s):\n rdm2[p, q, r, s] = evals_2[ctr]\n # Symmetry pqrs = rspq\n rdm2[r, s, p, q] = rdm2[p, q, r, s]\n ctr += 1\n\n # Further permutational symmetry: pqrs = qpsr\n for p, q, r, s in product(range(n_MOs), repeat=4):\n if p >= q or r >= s:\n rdm2[q, p, s, r] = rdm2[p, q, r, s]\n\n return rdm2\n\n # Build operator lists\n qops = []\n if spin_free:\n qops += _build_1bdy_operators_spinfree() if get_rdm1 else []\n qops += _build_2bdy_operators_spinfree() if get_rdm2 else []\n else:\n qops += _build_1bdy_operators_spinful() if get_rdm1 else []\n qops += _build_2bdy_operators_spinful() if get_rdm2 else []\n\n # Compute expected values\n evals = simulate(ExpectationValue(H=qops, U=U, shape=[len(qops)]), variables=variables)\n\n # Assemble density matrices\n # If self._rdm1, self._rdm2 exist, reset them if they are of the other spin-type\n def _reset_rdm(rdm):\n if rdm is not None:\n if spin_free and rdm.shape[0] != n_MOs:\n return None\n if not spin_free and rdm.shape[0] != n_SOs:\n return None\n return rdm\n\n self._rdm1 = _reset_rdm(self._rdm1)\n self._rdm2 = _reset_rdm(self._rdm2)\n # Split expectation values in 1- and 2-particle expectation values\n if get_rdm1:\n len_1 = n_MOs * (n_MOs + 1) // 2 if spin_free else n_SOs * (n_SOs + 1) // 2\n else:\n len_1 = 0\n evals_1, evals_2 = evals[:len_1], evals[len_1:]\n # Build matrices using the expectation values\n self._rdm1 = _assemble_rdm1(evals_1) if get_rdm1 else self._rdm1\n if spin_free:\n self._rdm2 = _assemble_rdm2_spinfree(evals_2) if get_rdm2 else self._rdm2\n else:\n self._rdm2 = _assemble_rdm2_spinful(evals_2) if get_rdm2 else self._rdm2\n\n def rdm_spinsum(self, sum_rdm1: bool = True, sum_rdm2: bool = True) -> tuple:\n \"\"\"\n Given the spin-ful 1- and 2-particle reduced density matrices, compute the spin-free RDMs by spin summation.\n\n Parameters\n ----------\n sum_rdm1, sum_rdm2 :\n If set to true, perform spin summation on rdm1, rdm2\n\n Returns\n -------\n rdm1_spinsum, rdm2_spinsum :\n The desired spin-free matrices\n \"\"\"\n n_MOs = self.n_orbitals\n rdm1_spinsum = None\n rdm2_spinsum = None\n\n # Spin summation on rdm1\n if sum_rdm1:\n # Check whether spin-rdm2 exists\n if self._rdm1 is None:\n raise Exception(\"The spin-RDM for the 1-RDM does not exist!\")\n # Check whether existing rdm1 is in spin-orbital basis\n if self._rdm1.shape[0] != 2 * n_MOs:\n raise Exception(\"The existing RDM needs to be in spin-orbital basis, it is already spin-free!\")\n # Do summation\n rdm1_spinsum = numpy.zeros([n_MOs, n_MOs])\n for p in range(n_MOs):\n for q in range(p + 1):\n rdm1_spinsum[p, q] += self._rdm1[2 * p, 2 * q]\n rdm1_spinsum[p, q] += self._rdm1[2 * p + 1, 2 * q + 1]\n for p in range(n_MOs):\n for q in range(p):\n rdm1_spinsum[q, p] = rdm1_spinsum[p, q]\n\n # Spin summation on rdm2\n if sum_rdm2:\n # Check whether spin-rdm2 exists\n if self._rdm2 is None:\n raise Exception(\"The spin-RDM for the 2-RDM does not exist!\")\n # Check whether existing rdm2 is in spin-orbital basis\n if self._rdm2.shape[0] != 2 * n_MOs:\n raise Exception(\"The existing RDM needs to be in spin-orbital basis, it is already spin-free!\")\n # Do summation\n rdm2_spinsum = numpy.zeros([n_MOs, n_MOs, n_MOs, n_MOs])\n for p, q, r, s in product(range(n_MOs), repeat=4):\n rdm2_spinsum[p, q, r, s] += self._rdm2[2 * p, 2 * q, 2 * r, 2 * s]\n rdm2_spinsum[p, q, r, s] += self._rdm2[2 * p + 1, 2 * q, 2 * r + 1, 2 * s]\n rdm2_spinsum[p, q, r, s] += self._rdm2[2 * p, 2 * q + 1, 2 * r, 2 * s + 1]\n rdm2_spinsum[p, q, r, s] += self._rdm2[2 * p + 1, 2 * q + 1, 2 * r + 1, 2 * s + 1]\n\n return rdm1_spinsum, rdm2_spinsum\n\n def __str__(self) -> str:\n result = str(type(self)) + \"\\n\"\n result += \"Qubit Encoding\\n\"\n result += str(self.transformation) + \"\\n\"\n for k, v in self.parameters.__dict__.items():\n result += \"{key:15} : {value:15} \\n\".format(key=str(k), value=str(v))\n return result\n", "# Copyright 2019 Xanadu Quantum 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.\nr\"\"\"\n.. _gates:\n\nQuantum operations\n===================\n\n**Module name:** :mod:`strawberryfields.ops`\n\n.. currentmodule:: strawberryfields.ops\n\n.. note::\n\n In the :mod:`strawberryfields.ops` API we use the convention :math:`\\hbar=2` by default, however\n this can be changed using the global variable :py:data:`strawberryfields.hbar`.\n\n See :ref:`conventions` for more details.\n\nThis module defines and implements the Python-embedded quantum programming language\nfor continuous-variable (CV) quantum systems.\nThe syntax is modeled after ProjectQ :cite:`projectq2016`.\n\nQuantum operations (state preparation, unitary gates, measurements, channels) act on\nregister objects using the following syntax:\n\n.. code-block:: python\n\n prog = sf.Program(3)\n with prog.context as q:\n G(params) | q\n F(params) | (q[1], q[6], q[2])\n\nHere :samp:`prog` is an instance of :class:`strawberryfields.program.Program`\nwhich defines the context where the commands are stored.\nWithin each command, the part on the left is an :class:`Operation` instance,\nquite typically a constructor call for the requested operation class with the relevant parameters.\nThe vertical bar calls the :func:`__or__` method of the :class:`Operation` object,\nwith the part on the right as the parameter. The part on the right is a single\n:class:`strawberryfields.engine.RegRef` object or, for multi-mode gates, a sequence of them.\nIt is of course also possible to construct gates separately and reuse them several times::\n\n R = Rgate(s)\n with prog.context as q:\n R | q\n Xgate(t) | q\n R.H | q\n\n\nThere are six kinds of :class:`Operation` objects:\n\n* :class:`Preparation` operations only manipulate the register state::\n\n with prog.context as q:\n Vac | q[0]\n All(Coherent(0.4, 0.2)) | (q[1], q[2])\n\n* Transformations such as :class:`Gate` and :class:`Channel` operations only manipulate the register state::\n\n with prog.context as q:\n Dgate(0.3) | q[0]\n BSgate(-0.5) | q[0:2]\n\n* :class:`Measurement` operations manipulate the register state and produce classical information.\n The information is directly available only after the program has been run up to the point of measurement::\n\n with prog.context as (alice, bob):\n Measure | alice\n\n eng = sf.LocalEngine(backend='fock')\n eng.run(prog)\n print(alice.val)\n\n Alternatively one may use a symbolic reference to the register containing the measurement result\n by supplying registers as the argument to an :class:`Operation`, in which case the measurement may be deferred,\n i.e., we may symbolically use the measurement result before it exists::\n\n with prog.context as (alice, bob):\n Measure | alice\n Dgate(alice) | bob\n\n One may also include an arbitrary post-processing function for the measurement result, to be applied\n before using it as the argument to another :class:`Operation`. The :func:`~.convert` decorator can be used in Python\n to convert a user-defined function into a post-processing function recognized by the engine::\n\n @convert\n def square(q):\n return q ** 2\n\n with prog.context as q:\n Measure | q[0]\n Dgate(square(q[0])) | q[1]\n\n Finally, the lower-level :class:`strawberryfields.engine.RegRefTransform` (RR) and\n an optional lambda function can be used to achieve the same functionality::\n\n with prog.context as q:\n Measure | q[0]\n Dgate(RR(q[0])) | q[1]\n Dgate(RR(q[0], lambda q: q ** 2)) | q[2]\n\n* Modes can be created and deleted during program execution using the\n function :func:`New` and the pre-constructed object :py:data:`Del`.\n Behind the scenes they utilize the meta-operations :class:`_New_modes` and :class:`_Delete`::\n\n with prog.context as (alice,):\n Sgate(1) | alice\n bob, charlie = New(2)\n BSgate(0.5) | (alice, bob)\n CXgate(1) | (alice, charlie)\n Del | alice\n S2gate(0.4) | (charlie, bob)\n\n* Finally, :class:`Decomposition` operations are a special case, and can act as\n either transformations *or* state preparation, depending on the decomposition used.\n Decompositions calculate the required elementary :class:`Gate` and/or :class:`Preparation`\n objects and parameters in order to decompose specific transformations or states.\n Examples of objects that are supported by decompositions include covariance matrices,\n interferometers, and symplectic transformations.\n\nHierarchy for operations\n------------------------\n\n.. inheritance-diagram:: strawberryfields.ops\n :parts: 1\n\n\nBase classes\n------------\n\nThe abstract base class hierarchy exists to provide the correct semantics for the actual operations that inherit them.\n\n.. autosummary::\n Operation\n Preparation\n Transformation\n Gate\n Channel\n Measurement\n Decomposition\n MetaOperation\n\n\nOperation class\n---------------\n\nAll Operations have the following methods.\n\n.. currentmodule:: strawberryfields.ops.Operation\n\n.. autosummary::\n __str__\n __or__\n merge\n decompose\n apply\n _apply\n\n.. currentmodule:: strawberryfields.ops\n\n\nState preparation\n-----------------\n\n.. autosummary::\n Vacuum\n Coherent\n Squeezed\n DisplacedSqueezed\n Thermal\n Fock\n Catstate\n Ket\n DensityMatrix\n Gaussian\n\nMeasurements\n------------\n\n.. autosummary::\n MeasureFock\n MeasureHomodyne\n MeasureHeterodyne\n\n\nChannels\n-----------\n\n.. autosummary::\n LossChannel\n ThermalLossChannel\n\n\nDecompositions\n--------------\n\n.. autosummary::\n Interferometer\n GraphEmbed\n GaussianTransform\n Gaussian\n\n\nSingle-mode gates\n-----------------\n\n.. autosummary::\n Dgate\n Xgate\n Zgate\n Sgate\n Rgate\n Pgate\n Vgate\n Fouriergate\n\nTwo-mode gates\n--------------\n\n.. autosummary::\n BSgate\n S2gate\n CXgate\n CZgate\n CKgate\n\nMeta-operations\n---------------\n\n.. autosummary::\n All\n _New_modes\n _Delete\n\n\nOperations shortcuts\n---------------------\n\nSeveral of the operation classes described below come with variables that point to pre-constructed instances;\nthis is to provide shorthands for operations that accept no arguments, as well as for common variants of operations that do.\n\n.. raw:: html\n\n <style>\n .widetable {\n width:100%;\n }\n </style>\n\n.. rst-class:: longtable widetable\n\n====================== =================================================================================\n**Shorthand variable** **Operation**\n``New`` :class:`~._New_modes`\n``Del`` :class:`~._Delete`\n``Vac`` :class:`~.Vacuum`\n``Fourier`` :class:`~.Fouriergate`\n``Measure`` :class:`~.MeasureFock`\n``MeasureX`` :class:`~.MeasureHomodyne` (:math:`\\phi=0`), :math:`x` quadrature measurement\n``MeasureP`` :class:`~.MeasureHomodyne` (:math:`\\phi=\\pi/2`), :math:`p` quadrature measurement\n``MeasureHD`` :class:`~.MeasureHeterodyne`\n``RR`` Alias for :class:`~.RegRefTransform`\n====================== =================================================================================\n\n\nCode details\n~~~~~~~~~~~~\n\n\"\"\"\n\nfrom collections.abc import Sequence\nimport copy\nimport warnings\n\nimport numpy as np\nfrom numpy import pi\n\nfrom scipy.linalg import block_diag\nfrom scipy.special import factorial as fac\n\nimport strawberryfields as sf\nfrom .backends.states import BaseFockState, BaseGaussianState\nfrom .backends.shared_ops import changebasis\nfrom .program import (Program, Command, RegRefTransform, MergeFailure)\nfrom .parameters import (Parameter, _unwrap, matmul, sign, abs, exp, log, sqrt,\n sin, cos, cosh, tanh, arcsinh, arccosh, arctan, arctan2,\n transpose, squeeze)\nfrom .decompositions import clements, bloch_messiah, williamson, graph_embed\n\n# pylint: disable=abstract-method\n# pylint: disable=protected-access\n# pylint: disable=too-many-arguments\n\n# numerical tolerances\n_decomposition_merge_tol = 1e-13\n_decomposition_tol = 1e-13 # TODO this tolerance is used for various purposes and is not well-defined\n\n\ndef warning_on_one_line(message, category, filename, lineno, file=None, line=None):\n \"\"\"User warning formatter\"\"\"\n # pylint: disable=unused-argument\n return '{}:{}: {}: {}\\n'.format(filename, lineno, category.__name__, message)\n\n\nwarnings.formatwarning = warning_on_one_line\n\n\ndef _seq_to_list(s):\n \"Converts a Sequence or a single object into a list.\"\n if not isinstance(s, Sequence):\n s = [s]\n return list(s)\n\n\nclass Operation:\n \"\"\"Abstract base class for quantum operations acting on one or more subsystems.\n\n The extra_deps instance variable is a set containing the :class:`.RegRef`\n the :class:`Operation` depends on. In the quantum circuit diagram notation it\n corresponds to the vertical double lines of classical information\n entering the :class:`Operation` that originate in a measurement of a subsystem.\n\n This abstract base class may be initialised with parameters; see the\n :class:`~strawberryfields.parameters.Parameter` class for more details.\n\n Args:\n par (Sequence[...]): parameters. len(par) >= 1. Alternatively,\n set to [] or None to allow initialisation with no parameters.\n \"\"\"\n # default: one-subsystem operation\n #: int: number of subsystems the operation acts on,\n # or None if any number of subsystems > 0 is okay\n ns = 1\n\n def __init__(self, par):\n #: set[RegRef]: extra dependencies due to deferred measurements, used during optimization\n self._extra_deps = set()\n #: list[Parameter]\n self.p = []\n\n if par:\n # convert each parameter into a Parameter instance, keep track of dependenciens\n for q in par:\n if not isinstance(q, Parameter):\n q = Parameter(q)\n self.p.append(q)\n self._extra_deps.update(q.deps)\n\n def __str__(self):\n \"\"\"String representation for the Operation using Blackbird syntax.\n\n Returns:\n str: string representation\n \"\"\"\n # defaults to the class name\n if self.p is None:\n return self.__class__.__name__\n\n # class name and parameter values\n temp = [str(i) for i in self.p]\n return self.__class__.__name__+'('+', '.join(temp)+')'\n\n @property\n def extra_deps(self):\n \"\"\"Extra dependencies due to parameters that depend on deferred measurements.\n\n Returns:\n set[RegRef]: dependencies\n \"\"\"\n return self._extra_deps\n\n def __or__(self, reg):\n \"\"\"Apply the operation to a part of a quantum register.\n\n Appends the Operation to a :class:`.Program` instance.\n\n Args:\n reg (RegRef, Sequence[RegRef]): subsystem(s) the operation is acting on\n\n Returns:\n list[RegRef]: subsystem list as RegRefs\n \"\"\"\n # into a list of subsystems\n reg = _seq_to_list(reg)\n if (not reg) or (self.ns is not None and self.ns != len(reg)):\n raise ValueError(\"Wrong number of subsystems.\")\n # append it to the Program\n reg = Program._current_context.append(self, reg)\n return reg\n\n def merge(self, other):\n \"\"\"Merge the operation with another (acting on the exact same set of subsystems).\n\n .. note:: For subclass overrides: merge may return a newly created object,\n or self, or other, but it must never modify self or other\n because the same Operation objects may be also used elsewhere.\n\n Args:\n other (Operation): operation to merge this one with\n\n Returns:\n Operation, None: other * self. The return value None represents\n the identity gate (doing nothing).\n\n Raises:\n ~strawberryfields.engine.MergeFailure: if the two\n operations cannot be merged\n \"\"\"\n # todo: Using the return value None to denote the identity is a\n # bit dangerous, since a function with no explicit return statement\n # also returns None, which can lead to puzzling bugs. Maybe return\n # a special singleton Identity object instead?\n raise NotImplementedError\n\n def decompose(self, reg):\n \"\"\"Decompose the operation into elementary operations supported by the backend API.\n\n See :mod:`strawberryfields.backends.base`.\n\n Args:\n reg (Sequence[RegRef]): subsystems the operation is acting on\n\n Returns:\n list[Command]: decomposition as a list of operations acting on specific subsystems\n \"\"\"\n # todo: For now decompose() works on unevaluated Parameters.\n # This causes an error if a :class:`.RegRefTransform`-based Parameter is used, and\n # decompose() tries to do arithmetic on it.\n return self._decompose(reg)\n\n def _decompose(self, reg):\n \"\"\"Internal decomposition method defined by subclasses.\n\n Args:\n reg (Sequence[RegRef]): subsystems the operation is acting on\n\n Returns:\n list[Command]: decomposition as a list of operations acting on specific subsystems\n \"\"\"\n raise NotImplementedError('No decomposition available: {}'.format(self))\n\n def _apply(self, reg, backend, **kwargs):\n \"\"\"Internal apply method. Uses numeric subsystem referencing.\n\n Args:\n reg (Sequence[int]): subsystem indices the operation is\n acting on (this is how the backend API wants them)\n backend (BaseBackend): backend to execute the operation\n\n Returns:\n array[Number] or None: Measurement results, if any; shape == (len(reg), shots).\n \"\"\"\n raise NotImplementedError('Missing direct implementation: {}'.format(self))\n\n def apply(self, reg, backend, **kwargs):\n \"\"\"Ask a local backend to execute the operation on the current register state right away.\n\n Takes care of parameter evaluations and any pending formal\n transformations (like dagger) and then calls :meth:`Operation._apply`.\n\n Args:\n reg (Sequence[RegRef]): subsystem(s) the operation is acting on\n backend (BaseBackend): backend to execute the operation\n\n Keyword Args:\n eval_params (bool): set this to False to explicitly turn off the\n evaluation of parameters in the Operation.apply method. This is\n useful if the parameters are pre-evaluated prior to calling this method.\n\n Returns:\n Any: the result of self._apply\n \"\"\"\n eval_params = kwargs.get('eval_params', True)\n original_p = self.p # store the original parameters\n\n if eval_params and original_p:\n # NOTE: We cannot just replace all RegRefTransform parameters with their\n # numerical values here. If we re-initialize a measured mode and\n # re-measure it, the RegRefTransform value should change accordingly\n # when it is used again after the new measurement.\n\n # Evaluate the Parameters, restore the originals later:\n self.p = [x.evaluate() for x in self.p]\n\n # convert RegRefs back to indices for the backend API\n temp = [rr.ind for rr in reg]\n # call the child class specialized _apply method\n result = self._apply(temp, backend, **kwargs)\n\n if eval_params and original_p:\n # restore original unevaluated Parameter instances\n self.p = original_p\n\n return result\n\n\n# ====================================================================\n# Derived operation classes\n# ====================================================================\n\n\nclass Preparation(Operation):\n \"\"\"Abstract base class for operations that demolish\n the previous state of the subsystem entirely.\n \"\"\"\n\n def merge(self, other):\n # sequential preparation, only the last one matters\n if isinstance(other, Preparation):\n # give a warning, since this is pointless and probably a user error\n warnings.warn('Two subsequent state preparations, first one has no effect.')\n return other\n\n raise MergeFailure('For now, Preparations cannot be merged with anything else.')\n\n\nclass Measurement(Operation):\n \"\"\"Abstract base class for projective subsystem measurements.\n\n The measurement is deferred: its result is available only\n after the backend has executed it. The value of the measurement can\n be accessed in the program through the symbolic subsystem reference\n to the measured subsystem.\n\n When the measurement happens, the state of the system is updated\n to the conditional state corresponding to the measurement result.\n Measurements also support postselection, see below.\n\n Args:\n select (None, Sequence[Number]): Desired values of the measurement\n results, one for each subsystem the measurement acts on.\n Allows the post-selection of specific measurement results\n instead of randomly sampling. None means no postselection.\n \"\"\"\n # todo: self.select could support :class:`~strawberryfields.parameters.Parameter` instances.\n ns = None\n\n def __init__(self, par, select=None):\n super().__init__(par)\n #: None, Sequence[Number]: postselection values, one for each measured subsystem\n self.select = select\n\n def __str__(self):\n # class name, parameter values, and possibly the select parameter\n temp = super().__str__()\n if self.select is not None:\n temp = temp[:-1] + ', select={})'.format(self.select)\n return temp\n\n def merge(self, other):\n raise MergeFailure('For now, measurements cannot be merged with anything else.')\n\n def apply(self, reg, backend, **kwargs):\n \"\"\"Ask a backend to execute the operation on the current register state right away.\n\n Like :func:`Operation.apply`, but also stores the measurement result in the RegRefs.\n \"\"\"\n values = super().apply(reg, backend, **kwargs)\n # measurement can act on multiple modes\n if self.ns == 1:\n values = [values]\n # store the results in the register reference objects\n for v, r in zip(values, reg):\n r.val = v\n\n\nclass Decomposition(Operation):\n \"\"\"Abstract base class for multimode matrix transformations.\n\n This class provides the base behaviour for decomposing various multimode operations\n into a sequence of gates and state preparations.\n\n The first parameter p[0] of the Decomposition is always a square matrix.\n \"\"\"\n ns = None # overridden by child classes in __init__\n\n def merge(self, other):\n # can be merged if they are the same class\n if isinstance(other, self.__class__):\n # at the moment, we will assume all state decompositions only\n # take one argument. The only exception currently are state\n # decompositions, which cannot be merged.\n U1 = self.p[0]\n U2 = other.p[0]\n U = matmul(U2, U1).x\n # Note: above we strip the Parameter wrapper to make the following check\n # easier to perform. The constructor restores it.\n # Another option would be to add the required methods to Parameter class.\n # check if the matrices cancel\n if np.all(np.abs(U - np.identity(len(U))) < _decomposition_merge_tol):\n return None\n\n return self.__class__(U)\n\n raise MergeFailure('Not the same decomposition type.')\n\n\nclass Transformation(Operation):\n \"\"\"Abstract base class for transformations.\n\n This class provides the base behaviour for operations which\n act on existing states.\n \"\"\"\n # NOTE: At the moment this is an empty class, and only\n # exists for a nicer inheritence diagram. One option is\n # to remove, and make Channel and Gate top-level derived classes.\n #\n # Are there any useful operations/properties shared by Gate/Channel?\n\n\n# ====================================================================\n# Derived transformation classes\n# ====================================================================\n\n\nclass Channel(Transformation):\n \"\"\"Abstract base class for channels.\n\n This class provides the base behaviour for non-unitary\n maps and transformations.\n \"\"\"\n\n def merge(self, other):\n # check that other is an identical channel, and that there are\n # no extra dependencies <=> no RegRefTransform parameters\n if isinstance(other, self.__class__) \\\n and len(self._extra_deps)+len(other._extra_deps) == 0:\n # check that all other parameters are identical\n if np.all(self.p[1:] != other.p[1:]):\n raise MergeFailure('Other parameters differ.')\n\n # determine the new loss parameter\n T = self.p[0] * other.p[0]\n\n # if one, replace with the identity\n if T == 1:\n return None\n\n if len(self.p) == 1:\n return self.__class__(T)\n\n return self.__class__(T, *self.p[1:])\n\n raise MergeFailure('Not the same operation family.')\n\n\nclass Gate(Transformation):\n \"\"\"Abstract base class for unitary quantum gates.\n\n The first parameter p[0] of the Gate class is special:\n\n * The value p[0] = 0 corresponds to the identity gate.\n * The inverse gate is obtained by negating p[0].\n * Two gates of this class can be merged by adding the\n first parameters together, assuming all the other parameters match.\n \"\"\"\n\n def __init__(self, par):\n super().__init__(par)\n # default: non-dagger form\n self.dagger = False #: bool: formal inversion of the gate\n\n def __str__(self):\n \"\"\"String representation for the gate.\"\"\"\n # add a dagger symbol to the class name if needed\n temp = super().__str__()\n if self.dagger:\n temp += \".H\"\n return temp\n\n @property\n def H(self):\n \"\"\"Returns a copy of the gate with the self.dagger flag flipped.\n\n H stands for hermitian conjugate.\n\n Returns:\n Gate: formal inverse of this gate\n \"\"\"\n # HACK Semantically a bad use of @property since this method is not a getter.\n # NOTE deepcopy would make copies of RegRefs inside a possible\n # RegRefTransformation parameter, RegRefs must not be copied.\n s = copy.copy(self)\n s.dagger = not s.dagger\n return s\n\n def decompose(self, reg):\n \"\"\"Decompose the operation into elementary operations supported by the backend API.\n\n Like :func:`Operation.decompose`, but applies self.dagger.\n \"\"\"\n seq = self._decompose(reg)\n if self.dagger:\n # apply daggers, reverse the Command sequence\n for cmd in seq:\n cmd.op.dagger = not cmd.op.dagger\n seq = list(reversed(seq))\n return seq\n\n def apply(self, reg, backend, **kwargs):\n \"\"\"Ask a backend to execute the operation on the current register state right away.\n\n Like :func:`Operation.apply`, but takes into account the special nature of\n p[0] and applies self.dagger.\n\n Returns:\n None: Gates do not return anything, return value is None\n \"\"\"\n z = self.p[0].evaluate()\n # if z represents a batch of parameters, then all of these\n # must be zero to skip calling backend\n if np.all(z == 0):\n # identity, no need to apply\n return\n if self.dagger:\n z = -z\n temp = self.p # store the original Parameters\n # evaluate the rest of the Parameters, restore the originals later\n self.p = [z] + [x.evaluate() for x in self.p[1:]]\n # calling the parent apply, skipping re-evaluation of self.p\n # (which wouldn't hurt but is unnecessary)\n super().apply(reg, backend, eval_params=False, **kwargs)\n self.p = temp # restore original unevaluated Parameter instances\n\n def merge(self, other):\n # can be merged if they are the same class and share all the other parameters\n if isinstance(other, self.__class__) and self.p[1:] == other.p[1:] \\\n and len(self._extra_deps)+len(other._extra_deps) == 0:\n # no extra dependencies <=> no RegRefTransform parameters,\n # with which we cannot do arithmetic at the moment\n # make sure the gates have the same dagger flag, if not, invert the second p[0]\n if self.dagger == other.dagger:\n temp = other.p[0]\n else:\n temp = -other.p[0]\n # now we can add up the parameters and keep self.dagger\n p0 = self.p[0] + temp\n if p0 == 0:\n return None # identity gate\n\n # return a copy\n # HACK: some of the subclass constructors only take a single parameter,\n # some take two, none take three\n if len(self.p) == 1:\n temp = self.__class__(p0)\n else:\n temp = self.__class__(p0, *self.p[1:])\n # NOTE deepcopy would make copies of RegRefs inside a possible\n # RegRefTransformation parameter, RegRefs must not be copied.\n # OTOH copy results in temp having the same p list as self,\n # which we would modify below.\n #temp = copy.copy(self)\n #temp.p[0] = p0\n temp.dagger = self.dagger\n return temp\n\n if isinstance(other, self.__class__):\n # without knowing anything more specific about the gates, we\n # can only merge them if they are each others' inverses\n if self.dagger != other.dagger:\n return None\n\n raise MergeFailure(\"Don't know how to merge these gates.\")\n\n raise MergeFailure('Not the same gate family.')\n\n\n# ====================================================================\n# State preparation operations\n# ====================================================================\n\n\nclass Vacuum(Preparation):\n \"\"\"Prepare a mode in the :ref:`vacuum state <vacuum_state>`.\n\n Can be accessed via the shortcut variable ``Vac``.\n \"\"\"\n\n def __init__(self):\n super().__init__([])\n\n def _apply(self, reg, backend, **kwargs):\n backend.prepare_vacuum_state(*reg)\n\n def __str__(self):\n # return the shorthand object when the\n # command is printed by the user\n return 'Vac'\n\n\nclass Coherent(Preparation):\n r\"\"\"Prepare a mode in a :ref:`coherent state <coherent_state>`.\n\n The gate is parameterized so that a user can specify a single complex number :math:`a=\\alpha`\n or use the polar form :math:`a = r, p=\\phi` and still get the same result.\n\n Args:\n a (complex): displacement parameter :math:`\\alpha`\n p (float): phase angle :math:`\\phi`\n \"\"\"\n\n def __init__(self, a=0., p=0.):\n super().__init__([a, p])\n\n def _apply(self, reg, backend, **kwargs):\n z = self.p[0] * exp(1j * self.p[1])\n backend.prepare_coherent_state(z.x, *reg)\n\n\nclass Squeezed(Preparation):\n r\"\"\"Prepare a mode in a :ref:`squeezed vacuum state <squeezed_state>`.\n\n Args:\n r (float): squeezing magnitude\n p (float): squeezing angle :math:`\\phi`\n \"\"\"\n\n def __init__(self, r=0., p=0.):\n super().__init__([r, p])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.prepare_squeezed_state(p[0], p[1], *reg)\n\n\nclass DisplacedSqueezed(Preparation):\n r\"\"\"Prepare a mode in a :ref:`displaced squeezed state <displaced_squeezed_state>`.\n\n A displaced squeezed state is prepared by squeezing a vacuum state, and\n then applying a displacement operator.\n\n .. math::\n \\ket{\\alpha,z} = D(\\alpha)\\ket{0,z} = D(\\alpha)S(z)\\ket{0},\n\n where the squeezing parameter :math:`z=re^{i\\phi}`.\n\n Args:\n alpha (complex): displacement parameter\n r (float): squeezing magnitude\n p (float): squeezing angle :math:`\\phi`\n \"\"\"\n\n def __init__(self, alpha=0., r=0., p=0.):\n super().__init__([alpha, r, p])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n # prepare the displaced squeezed state directly\n backend.prepare_displaced_squeezed_state(p[0], p[1], p[2], *reg)\n\n def _decompose(self, reg):\n # squeezed state preparation followed by a displacement gate\n return [\n Command(Squeezed(self.p[1], self.p[2]), reg),\n Command(Dgate(self.p[0]), reg)\n ]\n\n\nclass Fock(Preparation):\n r\"\"\"Prepare a mode in a :ref:`fock_basis` state.\n\n The prepared mode is traced out and replaced with the Fock state :math:`\\ket{n}`.\n As a result the state of the other subsystems may have to be described using a density matrix.\n\n Args:\n n (int): Fock state to prepare\n \"\"\"\n\n def __init__(self, n=0):\n super().__init__([n])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.prepare_fock_state(p[0], *reg)\n\n\nclass Catstate(Preparation):\n r\"\"\"Prepare a mode in a :ref:`cat state <cat_state>`.\n\n A cat state is the coherent superposition of two coherent states,\n\n .. math::\n \\ket{\\text{cat}(\\alpha)} = \\frac{1}{N} (\\ket{\\alpha} +e^{i\\phi} \\ket{-\\alpha}),\n\n where :math:`N = \\sqrt{2 (1+\\cos(\\phi)e^{-2|\\alpha|^2})}` is the normalization factor.\n\n Args:\n alpha (complex): displacement parameter\n p (float): parity, where :math:`\\phi=p\\pi`. ``p=0`` corresponds to an even\n cat state, and ``p=1`` an odd cat state.\n \"\"\"\n\n def __init__(self, alpha=0, p=0):\n super().__init__([alpha, p])\n\n def _apply(self, reg, backend, **kwargs):\n alpha = self.p[0]\n phi = pi*self.p[1]\n D = backend.get_cutoff_dim()\n l = np.arange(D)[:, np.newaxis]\n\n # normalization constant\n temp = exp(-0.5 * abs(alpha)**2)\n N = temp / sqrt(2*(1 + cos(phi) * temp**4))\n\n # coherent states\n c1 = (alpha ** l) / sqrt(fac(l))\n c2 = ((-alpha) ** l) / sqrt(fac(l))\n # add them up with a relative phase\n ket = (c1 + exp(1j*phi) * c2) * N\n\n # in order to support broadcasting, the batch axis has been located at last axis, but backend expects it up as first axis\n ket = transpose(ket)\n\n # drop dummy batch axis if it is not necessary\n ket = squeeze(ket)\n\n backend.prepare_ket_state(ket.x, *reg)\n\n\nclass Ket(Preparation):\n r\"\"\"Prepare mode(s) using the given ket vector(s) in the Fock basis.\n\n The prepared modes are traced out and replaced with the given ket state\n (in the Fock basis). As a result the state of the other subsystems may have\n to be described using a density matrix.\n\n The provided kets must be each be of length ``cutoff_dim``, matching\n the cutoff dimension used in calls to :meth:`eng.run <~.Engine.run>`.\n\n Args:\n state (array or BaseFockState): state vector in the Fock basis.\n This can be provided as either:\n\n * a single ket vector, for single mode state preparation\n * a multimode ket, with one array dimension per mode\n * a :class:`BaseFockState` state object.\n \"\"\"\n ns = None\n\n def __init__(self, state):\n if isinstance(state, BaseFockState):\n if not state.is_pure:\n raise ValueError(\"Provided Fock state is not pure.\")\n super().__init__([state.ket()])\n elif isinstance(state, BaseGaussianState):\n raise ValueError(\"Gaussian states are not supported for the Ket operation.\")\n else:\n super().__init__([state])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.prepare_ket_state(p[0], reg)\n\n\nclass DensityMatrix(Preparation):\n r\"\"\"Prepare mode(s) using the given density matrix in the Fock basis.\n\n The prepared modes are traced out and replaced with the given state\n (in the Fock basis). As a result, the overall state of system\n will also have to be described using a density matrix.\n\n The provided density matrices must be of size ``[cutoff_dim, cutoff_dim]``,\n matching the cutoff dimension used in calls to :meth:`eng.run <~.Engine.run>`.\n\n Args:\n state (array or BaseFockState): density matrix in the Fock basis.\n This can be provided as either:\n\n * a single mode two-dimensional matrix :math:`\\rho_{ij}`,\n * a multimode tensor :math:`\\rho_{ij,kl,\\dots,mn}`, with two indices per mode,\n * a :class:`BaseFockState` state object.\n \"\"\"\n ns = None\n\n def __init__(self, state):\n if isinstance(state, BaseFockState):\n super().__init__([state.dm()])\n elif isinstance(state, BaseGaussianState):\n raise ValueError(\"Gaussian states are not supported for the Ket operation.\")\n else:\n super().__init__([state])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.prepare_dm_state(p[0], reg)\n\n\nclass Thermal(Preparation):\n r\"\"\"Prepare a mode in a :ref:`thermal state <thermal_state>`.\n\n The requested mode is traced out and replaced with the thermal state :math:`\\rho(\\bar{n})`.\n As a result the state will be described using a density matrix.\n\n Args:\n n (float): mean thermal population of the mode\n \"\"\"\n\n def __init__(self, n=0):\n super().__init__([n])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.prepare_thermal_state(p[0], *reg)\n\n\n# ====================================================================\n# Measurements\n# ====================================================================\n\n\nclass MeasureFock(Measurement):\n \"\"\":ref:`photon_counting`: measures a set of modes in the Fock basis.\n\n Also accessible via the shortcut variable ``Measure``.\n\n The modes are projected to the Fock state corresponding to the result of the measurement.\n \"\"\"\n ns = None\n\n def __init__(self, select=None):\n if select is not None and not isinstance(select, Sequence):\n select = [select]\n super().__init__([], select)\n\n def _apply(self, reg, backend, **kwargs):\n return backend.measure_fock(reg, select=self.select, **kwargs)\n\n def __str__(self):\n if self.select is None:\n return 'Measure'\n return 'MeasureFock(select={})'.format(self.select)\n\n\nclass MeasureHomodyne(Measurement):\n r\"\"\"Performs a :ref:`homodyne measurement <homodyne>`, measures one quadrature of a mode.\n\n * Position basis measurement: :math:`\\phi = 0`\n (also accessible via the shortcut variable ``MeasureX``).\n\n * Momentum basis measurement: :math:`\\phi = \\pi/2`.\n (also accessible via the shortcut variable ``MeasureP``)\n\n The measured mode is reset to the vacuum state.\n\n Args:\n phi (float): measurement angle :math:`\\phi`\n select (None, float): (Optional) desired values of measurement result.\n Allows the post-selection of specific measurement results instead of randomly sampling.\n \"\"\"\n ns = 1\n\n def __init__(self, phi, select=None):\n super().__init__([phi], select)\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n s = sqrt(sf.hbar / 2) # scaling factor, since the backend API call is hbar-independent\n select = self.select\n if select is not None:\n select = select / s\n\n return s * backend.measure_homodyne(p[0], *reg, select=select, **kwargs)\n\n def __str__(self):\n if self.select is None:\n if self.p[0] == 0:\n return 'MeasureX'\n if self.p[0] == pi/2:\n return 'MeasureP'\n return super().__str__()\n\n\nclass MeasureHeterodyne(Measurement):\n r\"\"\"Performs a :ref:`heterodyne measurement <heterodyne>` on a mode.\n\n Also accessible via the shortcut variable ``MeasureHD``.\n\n Samples the joint Husimi distribution :math:`Q(\\vec{\\alpha}) = \\frac{1}{\\pi}\\bra{\\vec{\\alpha}}\\rho\\ket{\\vec{\\alpha}}`.\n The measured mode is reset to the vacuum state.\n\n Args:\n select (None, complex): (Optional) desired values of measurement result.\n Allows the post-selection of specific measurement results instead of randomly sampling.\n \"\"\"\n ns = 1\n\n def __init__(self, select=None):\n super().__init__([], select)\n\n def _apply(self, reg, backend, **kwargs):\n return backend.measure_heterodyne(*reg, select=self.select, **kwargs)\n\n def __str__(self):\n if self.select is None:\n return 'MeasureHD'\n return 'MeasureHeterodyne(select={})'.format(self.select)\n\n\n# ====================================================================\n# Channels\n# ====================================================================\n\n\nclass LossChannel(Channel):\n r\"\"\"Perform a :ref:`loss channel <loss>` operation on the specified mode.\n\n This channel couples mode :math:`\\a` to another bosonic mode :math:`\\hat{b}`\n prepared in the vacuum state using the following transformation:\n\n .. math::\n \\a \\mapsto \\sqrt{T} a+\\sqrt{1-T} \\hat{b}\n\n Args:\n T (float): the loss parameter :math:`0\\leq T\\leq 1`.\n \"\"\"\n\n def __init__(self, T):\n super().__init__([T])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.loss(p[0], *reg)\n\n\nclass ThermalLossChannel(Channel):\n r\"\"\"Perform a :ref:`thermal loss channel <thermal_loss>` operation on the specified mode.\n\n This channel couples mode :math:`\\a` to another bosonic mode :math:`\\hat{b}`\n prepared in a thermal state with mean photon number :math:`\\bar{n}`,\n using the following transformation:\n\n .. math::\n \\a \\mapsto \\sqrt{T} a+\\sqrt{1-T} \\hat{b}\n\n Args:\n T (float): the loss parameter :math:`0\\leq T\\leq 1`.\n nbar (float): mean photon number of the environment thermal state\n \"\"\"\n\n def __init__(self, T, nbar):\n super().__init__([T, nbar])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.thermal_loss(p[0], p[1], *reg)\n\n\n# ====================================================================\n# Unitary gates\n# ====================================================================\n\n\nclass Dgate(Gate):\n r\"\"\"Phase space :ref:`displacement <displacement>` gate.\n\n .. math::\n D(\\alpha) = \\exp(\\alpha a^\\dagger -\\alpha^* a) = \\exp\\left(-i\\sqrt{2}(\\re(\\alpha) \\hat{p} -\\im(\\alpha) \\hat{x})/\\sqrt{\\hbar}\\right)\n\n where :math:`\\alpha = r e^{i\\phi}` has magnitude :math:`r\\geq 0` and phase :math:`\\phi`.\n\n The gate is parameterized so that a user can specify a single complex number :math:`a=\\alpha`\n or use the polar form :math:`a = r, \\phi` and still get the same result.\n\n Args:\n a (complex): displacement parameter :math:`\\alpha`\n phi (float): extra (optional) phase angle :math:`\\phi`\n \"\"\"\n\n def __init__(self, a, phi=0.):\n super().__init__([a, phi])\n\n def _apply(self, reg, backend, **kwargs):\n z = self.p[0] * exp(1j * self.p[1])\n backend.displacement(z.x, *reg)\n\n\nclass Xgate(Gate):\n r\"\"\"Position :ref:`displacement <displacement>` gate.\n\n .. math::\n X(x) = e^{-i x \\hat{p}/\\hbar}\n\n Args:\n x (float): position displacement\n \"\"\"\n\n def __init__(self, x):\n super().__init__([x])\n\n def _apply(self, reg, backend, **kwargs):\n z = self.p[0] / sqrt(2 * sf.hbar)\n backend.displacement(z.x, *reg)\n\n\nclass Zgate(Gate):\n r\"\"\"Momentum :ref:`displacement <displacement>` gate.\n\n .. math::\n Z(p) = e^{i p \\hat{x}/\\hbar}\n\n Args:\n p (float): momentum displacement\n \"\"\"\n\n def __init__(self, p):\n super().__init__([p])\n\n def _apply(self, reg, backend, **kwargs):\n z = self.p[0] * 1j/sqrt(2 * sf.hbar)\n backend.displacement(z.x, *reg)\n\n\nclass Sgate(Gate):\n r\"\"\"Phase space :ref:`squeezing <squeezing>` gate.\n\n .. math::\n S(z) = \\exp\\left(\\frac{1}{2}(z^* a^2 -z {a^\\dagger}^2)\\right)\n\n where :math:`z = r e^{i\\phi}`.\n\n Args:\n r (float): squeezing amount\n phi (float): squeezing phase angle :math:`\\phi`\n \"\"\"\n\n def __init__(self, r, phi=0.):\n super().__init__([r, phi])\n\n def _apply(self, reg, backend, **kwargs):\n z = self.p[0] * exp(1j * self.p[1])\n backend.squeeze(z.x, *reg)\n\n\nclass Pgate(Gate):\n r\"\"\":ref:`Quadratic phase <quadratic>` gate.\n\n .. math::\n P(s) = e^{i \\frac{s}{2} \\hat{x}^2/\\hbar}\n\n Args:\n s (float): parameter\n \"\"\"\n\n def __init__(self, s):\n super().__init__([s])\n\n def _decompose(self, reg):\n # into a squeeze and a rotation\n temp = self.p[0] / 2\n r = arccosh(sqrt(1+temp**2))\n theta = arctan(temp)\n phi = -pi/2 * sign(temp) - theta\n return [\n Command(Sgate(r, phi), reg),\n Command(Rgate(theta), reg)\n ]\n\n\nclass Vgate(Gate):\n r\"\"\":ref:`Cubic phase <cubic>` gate.\n\n .. math::\n V(\\gamma) = e^{i \\frac{\\gamma}{3 \\hbar} \\hat{x}^3}\n\n .. warning:: The cubic phase gate has lower accuracy than the Kerr gate at the same cutoff dimension.\n\n Args:\n gamma (float): parameter\n \"\"\"\n\n def __init__(self, gamma):\n super().__init__([gamma])\n\n def _apply(self, reg, backend, **kwargs):\n gamma_prime = self.p[0] * sqrt(sf.hbar / 2)\n # the backend API call cubic_phase is hbar-independent\n backend.cubic_phase(gamma_prime.x, *reg)\n\n\nclass Kgate(Gate):\n r\"\"\":ref:`Kerr <kerr>` gate.\n\n .. math::\n K(\\kappa) = e^{i \\kappa \\hat{n}^2}\n\n Args:\n kappa (float): parameter\n \"\"\"\n\n def __init__(self, kappa):\n super().__init__([kappa])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.kerr_interaction(p[0], *reg)\n\n\nclass Rgate(Gate):\n r\"\"\":ref:`Rotation <rotation>` gate.\n\n .. math::\n R(\\theta) = e^{i \\theta a^\\dagger a}\n\n Args:\n theta (float): rotation angle :math:`\\theta`.\n \"\"\"\n\n def __init__(self, theta):\n super().__init__([theta])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.rotation(p[0], *reg)\n\n\nclass BSgate(Gate):\n r\"\"\"BSgate(theta=pi/4, phi=0.)\n :ref:`Beamsplitter <beamsplitter>` gate.\n\n .. math::\n B(\\theta,\\phi) = \\exp\\left(\\theta (e^{i \\phi} a^\\dagger b -e^{-i \\phi}a b^\\dagger) \\right)\n\n Args:\n theta (float): Transmittivity angle :math:`\\theta`. The transmission amplitude of the beamsplitter is :math:`t = \\cos(\\theta)`.\n The value :math:`\\theta=\\pi/4` gives the 50-50 beamsplitter (default).\n phi (float): Phase angle :math:`\\phi`. The reflection amplitude of the beamsplitter is :math:`r = e^{i\\phi}\\sin(\\theta)`.\n The value :math:`\\phi = \\pi/2` gives the symmetric beamsplitter.\n \"\"\"\n ns = 2\n\n def __init__(self, theta=pi/4, phi=0.):\n # default: 50% beamsplitter\n super().__init__([theta, phi])\n\n def _apply(self, reg, backend, **kwargs):\n t = cos(self.p[0])\n r = sin(self.p[0]) * exp(1j * self.p[1])\n backend.beamsplitter(t.x, r.x, *reg)\n\n\nclass S2gate(Gate):\n r\"\"\":ref:`Two-mode squeezing <two_mode_squeezing>` gate.\n\n .. math::\n S_2(z) = \\exp\\left(z^* ab -z a^\\dagger b^\\dagger \\right) = \\exp\\left(r (e^{-i\\phi} ab -e^{i\\phi} a^\\dagger b^\\dagger \\right)\n\n where :math:`z = r e^{i\\phi}`.\n\n Args:\n r (float): squeezing amount\n phi (float): squeezing phase angle :math:`\\phi`\n \"\"\"\n ns = 2\n\n def __init__(self, r, phi=0.):\n super().__init__([r, phi])\n\n def _decompose(self, reg):\n # two opposite squeezers sandwiched between 50% beamsplitters\n S = Sgate(self.p[0], self.p[1])\n BS = BSgate(pi/4, 0)\n return [\n Command(BS, reg),\n Command(S, reg[0]),\n Command(S.H, reg[1]),\n Command(BS.H, reg)\n ]\n\n\nclass CXgate(Gate):\n r\"\"\":ref:`Controlled addition or sum <CX>` gate in the position basis.\n\n .. math::\n \\text{CX}(s) = \\int dx \\ket{x}\\bra{x} \\otimes D\\left({\\frac{1}{\\sqrt{2\\hbar}}}s x\\right) = e^{-i s \\: \\hat{x} \\otimes \\hat{p}/\\hbar}\n\n In the position basis it maps\n :math:`\\ket{x_1, x_2} \\mapsto \\ket{x_1, s x_1 +x_2}`.\n\n Args:\n s (float): addition multiplier\n \"\"\"\n ns = 2\n\n def __init__(self, s=1):\n super().__init__([s])\n\n def _decompose(self, reg):\n s = self.p[0]\n r = arcsinh(-s/2)\n theta = 0.5*arctan2(-1.0/cosh(r), -tanh(r))\n\n BS1 = BSgate(theta, 0)\n BS2 = BSgate(theta+pi/2, 0)\n return [\n Command(BS1, reg),\n Command(Sgate(r, 0), reg[0]),\n Command(Sgate(-r, 0), reg[1]),\n Command(BS2, reg)\n ]\n\n\nclass CZgate(Gate):\n r\"\"\":ref:`Controlled phase <CZ>` gate in the position basis.\n\n .. math::\n \\text{CZ}(s) = \\iint dx dy \\: e^{i sxy/\\hbar} \\ket{x,y}\\bra{x,y} = e^{i s \\: \\hat{x} \\otimes \\hat{x}/\\hbar}\n\n In the position basis it maps\n :math:`\\ket{x_1, x_2} \\mapsto e^{i s x_1 x_2/\\hbar} \\ket{x_1, x_2}`.\n\n Args:\n s (float): phase shift multiplier\n \"\"\"\n ns = 2\n\n def __init__(self, s=1):\n super().__init__([s])\n\n def _decompose(self, reg):\n # phase-rotated CZ\n CX = CXgate(self.p[0])\n return [\n Command(Rgate(-pi/2), reg[1]),\n Command(CX, reg),\n Command(Rgate(pi/2), reg[1])\n ]\n\n\nclass CKgate(Gate):\n r\"\"\":ref:`Cross-Kerr <cross_kerr>` gate.\n\n .. math::\n CK(\\kappa) = e^{i \\kappa \\hat{n}_1\\hat{n}_2}\n\n Args:\n kappa (float): parameter\n \"\"\"\n ns = 2\n\n def __init__(self, kappa):\n super().__init__([kappa])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.cross_kerr_interaction(p[0], *reg)\n\n\nclass Fouriergate(Gate):\n r\"\"\":ref:`Fourier <fourier>` gate.\n\n Also accessible via the shortcut variable ``Fourier``.\n\n A special case of the :class:`phase space rotation gate <Rgate>`, where :math:`\\theta=\\pi/2`.\n\n .. math::\n F = R(\\pi/2) = e^{i (\\pi/2) a^\\dagger a}\n \"\"\"\n\n def __init__(self):\n super().__init__([pi/2])\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n backend.rotation(p[0], *reg)\n\n def __str__(self):\n \"\"\"String representation for the gate.\"\"\"\n temp = 'Fourier'\n if self.dagger:\n temp += '.H'\n return temp\n\n\n# ====================================================================\n# Metaoperations\n# ====================================================================\n\n\n# ====================================================================\n# Subsystem creation and deletion\n# ====================================================================\n\n\nclass MetaOperation(Operation):\n \"\"\"Abstract base class for metaoperations.\n\n This includes subsystem creation and deletion.\n \"\"\"\n\n def __init__(self):\n super().__init__(par=[])\n\n\nclass _Delete(MetaOperation):\n \"\"\"Deletes one or more existing modes.\n Also accessible via the shortcut variable ``Del``.\n\n The deleted modes are traced out.\n After the deletion the state of the remaining subsystems may have to be described using a density operator.\n \"\"\"\n ns = None\n\n def __or__(self, reg):\n reg = super().__or__(reg)\n Program._current_context._delete_subsystems(reg)\n\n def _apply(self, reg, backend, **kwargs):\n backend.del_mode(reg)\n\n def __str__(self):\n # use the shorthand object\n return 'Del'\n\n\ndef New(n=1):\n \"\"\"Adds new subsystems to the quantum register.\n\n The new modes are prepared in the vacuum state.\n\n Must only be called in a :class:`Program` context.\n\n Args:\n n (int): number of subsystems to add\n Returns:\n tuple[RegRef]: tuple of the newly added subsystem references\n \"\"\"\n # create RegRefs for the new modes\n refs = Program._current_context._add_subsystems(n)\n # append the actual Operation to the Program\n Program._current_context.append(_New_modes(n), refs)\n return refs\n\n\nclass _New_modes(MetaOperation):\n \"\"\"Used internally for adding new modes to the system in a deferred way.\n\n This class cannot be used with the :meth:`__or__` syntax since it would be misleading.\n Indeed, users should *not* use this class directly, but rather the function :func:`New`.\n \"\"\"\n ns = 0\n\n def __init__(self, n=1):\n \"\"\"\n Args:\n n (int): number of modes to add\n \"\"\"\n super().__init__()\n self.n = n # int: store the number of new modes for the __str__ method\n\n def _apply(self, reg, backend, **kwargs):\n # pylint: disable=unused-variable\n inds = backend.add_mode(len(reg))\n\n def __str__(self):\n # use the shorthand object\n return 'New({})'.format(self.n)\n\n\nclass All(MetaOperation):\n \"\"\"Metaoperation for applying a single-mode operation to every mode in the register.\n\n Args:\n op (Operation): single-mode operation to apply\n \"\"\"\n\n def __init__(self, op):\n if op.ns != 1:\n raise ValueError(\"Not a one-subsystem operation.\")\n super().__init__()\n self.op = op #: Operation: one-subsystem operation to apply\n\n def __str__(self):\n return super().__str__() + '({})'.format(str(self.op))\n\n def __or__(self, reg):\n # into a list of subsystems\n reg = _seq_to_list(reg)\n # convert into commands\n # make sure reg does not contain duplicates (we feed them to Program.append() one by one)\n Program._current_context._test_regrefs(reg)\n for r in reg:\n Program._current_context.append(self.op, [r])\n\n\n# ====================================================================\n# Decompositions\n# ====================================================================\n\n\nclass Interferometer(Decomposition):\n\n def __init__(self, U, tol=1e-11):\n super().__init__([U])\n self.ns = U.shape[0]\n\n if np.all(np.abs(U - np.identity(len(U))) < _decomposition_merge_tol):\n self.identity = True\n else:\n self.identity = False\n self.BS1, self.BS2, self.R = clements(U, tol=tol)\n\n def _decompose(self, reg):\n cmds = []\n\n if not self.identity:\n for n, m, theta, phi, _ in self.BS1:\n if np.abs(phi) >= _decomposition_tol:\n cmds.append(Command(Rgate(phi), reg[n]))\n if np.abs(theta) >= _decomposition_tol:\n cmds.append(Command(BSgate(theta, 0), (reg[n], reg[m])))\n\n for n, expphi in enumerate(self.R):\n if np.abs(expphi - 1) >= _decomposition_tol:\n q = log(expphi).imag\n cmds.append(Command(Rgate(q), reg[n]))\n\n for n, m, theta, phi, _ in reversed(self.BS2):\n if np.abs(theta) >= _decomposition_tol:\n cmds.append(Command(BSgate(-theta, 0), (reg[n], reg[m])))\n if np.abs(phi) >= _decomposition_tol:\n cmds.append(Command(Rgate(-phi), reg[n]))\n\n return cmds\n\n\nclass GraphEmbed(Decomposition):\n r\"\"\"Embed a graph into an interferometer setup.\n\n This operation uses the Takagi decomposition to decompose\n an adjacency matrix into a sequence of squeezers and beamsplitters and\n rotation gates.\n\n Args:\n A (array): an :math:`N\\times N` complex or real symmetric matrix\n max_mean_photon (float): threshold value. It guarantees that the mode with\n the largest squeezing has ``max_mean_photon`` as the mean photon number\n i.e., :math:`sinh(r_{max})^2 ==` max_mean_photon\n make_traceless (boolean): removes the trace of the input matrix\n tol (float): the tolerance used when checking if the input matrix is symmetric:\n :math:`|A-A^T| <` tol\n \"\"\"\n\n def __init__(self, A, max_mean_photon=1.0, make_traceless=True, tol=1e-6):\n super().__init__([A])\n self.ns = A.shape[0]\n\n if np.all(np.abs(A - np.identity(len(A))) < _decomposition_merge_tol):\n self.identity = True\n else:\n self.identity = False\n self.sq, self.U = graph_embed(\n A, max_mean_photon=max_mean_photon, make_traceless=make_traceless, tol=tol)\n\n def _decompose(self, reg):\n cmds = []\n\n if not self.identity:\n for n, s in enumerate(self.sq):\n if np.abs(s) >= _decomposition_tol:\n cmds.append(Command(Sgate(s), reg[n]))\n\n if np.all(np.abs(self.U - np.identity(len(self.U))) >= _decomposition_tol):\n cmds.append(Command(Interferometer(self.U), reg))\n\n return cmds\n\n\nclass GaussianTransform(Decomposition):\n\n def __init__(self, S, vacuum=False, tol=1e-10):\n super().__init__([S])\n self.ns = S.shape[0] // 2\n self.vacuum = vacuum #: bool: if True, ignore the first unitary matrix when applying the gate\n N = self.ns # shorthand\n\n # check if input symplectic is passive (orthogonal)\n diffn = np.linalg.norm(S @ S.T - np.identity(2*N))\n self.active = (np.abs(diffn) > _decomposition_tol) #: bool: S is an active symplectic transformation\n\n if not self.active:\n # The transformation is passive, do Clements\n X1 = S[:N, :N]\n P1 = S[N:, :N]\n self.U1 = X1+1j*P1\n else:\n # transformation is active, do Bloch-Messiah\n O1, smat, O2 = bloch_messiah(S, tol=tol)\n X1 = O1[:N, :N]\n P1 = O1[N:, :N]\n X2 = O2[:N, :N]\n P2 = O2[N:, :N]\n\n self.U1 = X1+1j*P1 #: array[complex]: unitary matrix corresponding to O_1\n self.U2 = X2+1j*P2 #: array[complex]: unitary matrix corresponding to O_2\n self.Sq = np.diagonal(smat)[:N] #: array[complex]: diagonal vector of the squeezing matrix R\n\n def _decompose(self, reg):\n cmds = []\n\n if self.active:\n if not self.vacuum:\n cmds = [Command(Interferometer(self.U2), reg)]\n\n for n, expr in enumerate(self.Sq):\n if np.abs(expr - 1) >= _decomposition_tol:\n r = abs(log(expr))\n phi = np.angle(log(expr))\n cmds.append(Command(Sgate(-r, phi), reg[n]))\n\n cmds.append(Command(Interferometer(self.U1), reg))\n else:\n if not self.vacuum:\n cmds = [Command(Interferometer(self.U1), reg)]\n\n return cmds\n\n\nclass Gaussian(Preparation, Decomposition):\n # pylint: disable=too-many-instance-attributes\n ns = None\n\n def __init__(self, V, r=None, decomp=True, tol=1e-6):\n V = V / (sf.hbar / 2)\n self.ns = V.shape[0] // 2\n\n if r is None:\n r = np.zeros(2*self.ns)\n r = np.asarray(r)\n\n if len(r) != V.shape[0]:\n raise ValueError('Vector of means must have the same length as the covariance matrix.')\n\n super().__init__([V, r]) # V is hbar-independent, r is not\n\n self.x_disp = r[:self.ns]\n self.p_disp = r[self.ns:]\n\n if decomp:\n th, self.S = williamson(V, tol=tol)\n self.pure = np.abs(np.linalg.det(V) - 1.0) < tol\n self.nbar = 0.5 * (np.diag(th)[:self.ns] - 1.0)\n\n self.decomp = decomp #: bool: if False, use the backend API call instead of decomposition\n\n def _apply(self, reg, backend, **kwargs):\n p = _unwrap(self.p)\n s = sqrt(sf.hbar / 2) # scaling factor, since the backend API call is hbar-independent\n backend.prepare_gaussian_state(p[1]/s, p[0], reg)\n\n def _decompose(self, reg):\n # pylint: disable=too-many-branches\n cmds = []\n\n V = self.p[0].x\n D = np.diag(V)\n is_diag = np.all(V == np.diag(D))\n\n BD = changebasis(self.ns) @ V @ changebasis(self.ns).T\n BD_modes = [BD[i*2:(i+1)*2, i*2:(i+1)*2]\n for i in range(BD.shape[0]//2)]\n is_block_diag = (not is_diag) and np.all(BD == block_diag(*BD_modes))\n\n if self.pure and is_diag:\n # covariance matrix consists of x/p quadrature squeezed state\n for n, expr in enumerate(D[:self.ns]):\n if np.abs(expr - 1) >= _decomposition_tol:\n r = abs(log(expr)/2)\n cmds.append(Command(Squeezed(r, 0), reg[n]))\n else:\n cmds.append(Command(Vac, reg[n]))\n\n elif self.pure and is_block_diag:\n # covariance matrix consists of rotated squeezed states\n for n, v in enumerate(BD_modes):\n if not np.all(v - np.identity(2) < _decomposition_tol):\n r = np.abs(arccosh(np.sum(np.diag(v)) / 2)) / 2\n phi = arctan(2 * v[0, 1] / np.sum(np.diag(v) * [1, -1]))\n cmds.append(Command(Squeezed(r, phi), reg[n]))\n else:\n cmds.append(Command(Vac, reg[n]))\n\n elif not self.pure and is_diag and np.all(D[:self.ns] == D[self.ns:]):\n # covariance matrix consists of thermal states\n for n, nbar in enumerate(0.5 * (D[:self.ns] - 1.0)):\n if nbar >= _decomposition_tol:\n cmds.append(Command(Thermal(nbar), reg[n]))\n else:\n cmds.append(Command(Vac, reg[n]))\n\n else:\n if not self.pure:\n # mixed state, must initialise thermal states\n for n, nbar in enumerate(self.nbar):\n if np.abs(nbar) >= _decomposition_tol:\n cmds.append(Command(Thermal(nbar), reg[n]))\n else:\n cmds.append(Command(Vac, reg[n]))\n else:\n for r in reg:\n cmds.append(Command(Vac, r))\n\n cmds.append(Command(GaussianTransform(self.S, vacuum=self.pure), reg))\n\n cmds += [Command(Xgate(u), reg[n])\n for n, u in enumerate(self.x_disp) if u != 0]\n cmds += [Command(Zgate(u), reg[n])\n for n, u in enumerate(self.p_disp) if u != 0]\n\n return cmds\n\n\n#=======================================================================\n# Shorthands, e.g. pre-constructed singleton-like objects\n\nDel = _Delete()\nVac = Vacuum()\nMeasure = MeasureFock()\nMeasureX = MeasureHomodyne(0)\nMeasureP = MeasureHomodyne(pi/2)\nMeasureHD = MeasureHeterodyne()\n\nFourier = Fouriergate()\n\nRR = RegRefTransform\n\nshorthands = ['New', 'Del', 'Vac', 'Measure', 'MeasureX', 'MeasureP', 'MeasureHD', 'Fourier', 'RR',\n 'All']\n\n#=======================================================================\n# here we list different classes of operations for unit testing purposes\n\nzero_args_gates = (Fouriergate,)\none_args_gates = (Xgate, Zgate, Rgate, Pgate, Vgate,\n Kgate, CXgate, CZgate, CKgate)\ntwo_args_gates = (Dgate, Sgate, BSgate, S2gate)\ngates = zero_args_gates + one_args_gates + two_args_gates\n\nchannels = (LossChannel, ThermalLossChannel)\n\nsimple_state_preparations = (Vacuum, Coherent, Squeezed, DisplacedSqueezed, Fock, Catstate, Thermal) # have __init__ methods with default arguments\nstate_preparations = simple_state_preparations + (Ket, DensityMatrix)\n\nmeasurements = (MeasureFock, MeasureHomodyne, MeasureHeterodyne)\n\ndecompositions = (Interferometer, GraphEmbed, GaussianTransform, Gaussian)\n\n#=======================================================================\n# exported symbols\n\n__all__ = [cls.__name__ for cls in gates + channels + state_preparations + measurements + decompositions] + shorthands\n" ]
[ [ "numpy.fromiter", "tensorflow.enable_eager_execution", "tensorflow.constant", "numpy.allclose", "tensorflow.Variable", "numpy.abs", "numpy.sqrt", "tensorflow.equal", "numpy.kron", "numpy.cos", "numpy.sin", "tensorflow.linspace", "numpy.array", "tensorflow.GradientTape" ], [ "numpy.hstack", "numpy.random.choice", "numpy.arange", "numpy.apply_over_axes", "numpy.ravel_multi_index", "numpy.array" ], [ "numpy.array" ], [ "numpy.issubdtype", "numpy.array_equal" ], [ "numpy.take", "numpy.einsum", "numpy.abs", "numpy.ndarray", "numpy.linalg.eigh", "numpy.ndenumerate", "numpy.zeros", "numpy.isclose" ], [ "numpy.diag", "numpy.abs", "scipy.linalg.block_diag", "numpy.asarray", "numpy.arange", "numpy.all", "numpy.linalg.det", "numpy.identity", "scipy.special.factorial", "numpy.zeros", "numpy.diagonal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.14", "0.15" ], "tensorflow": [] } ]
noamwino/IML.HUJI
[ "0b1b6f333a16200fa7717af1be12e5f38694b74c" ]
[ "exercises/city_temperature_prediction.py" ]
[ "import os.path\n\nimport IMLearn.learners.regressors.linear_regression\nfrom IMLearn.learners.regressors import PolynomialFitting\nfrom IMLearn.utils import split_train_test\n\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.io as pio\npio.templates.default = \"simple_white\"\n\n\nfrom IMLearn.metrics.loss_functions import mean_square_error\n\n\nCITY_TEMPERATURE_DATA_PATH = os.path.join(os.path.curdir, \"..\", \"datasets\", \"City_Temperature.csv\")\n\n\ndef load_data(filename: str) -> pd.DataFrame:\n \"\"\"\n Load city daily temperature dataset and preprocess data.\n Parameters\n ----------\n filename: str\n Path to house prices dataset\n\n Returns\n -------\n Design matrix and response vector (Temp)\n \"\"\"\n data = pd.read_csv(filename, parse_dates=[\"Date\"]).drop_duplicates()\n data = data.drop(data[data[\"Temp\"] < -70].index) # invalid Temp\n data[\"DayOfYear\"] = data['Date'].dt.dayofyear\n\n return data\n\n\ndef question_2(data):\n \"\"\" Exploring data specifically in Israel \"\"\"\n data = data.copy()\n data = data[data[\"Country\"] == \"Israel\"]\n data[\"Year\"] = data[\"Year\"].astype(str)\n\n fig = px.scatter(data, x=\"DayOfYear\", y=\"Temp\", color=\"Year\", width=1500, height=700,\n labels={\"DayOfYear\": \"Day of Year\", \"Temp\": \"Temperature\"},\n title=\"Q2(1) The relation between the day in the year and the temperature in Israel\")\n fig.update_xaxes(range=[0, 365], tick0=0, dtick=20)\n fig.show()\n\n std_by_month = data.groupby(\"Month\").std().reset_index()\n fig = px.bar(std_by_month, x=\"Month\", y=\"Temp\", width=1500, height=700,\n labels={\"Temp\": \"Std of the daily temperatures\"},\n title=\"Q2(2) The Standard Deviation of the Daily Temperatures Per Month in Israel\")\n fig.data[-1].text = np.round(std_by_month[\"Temp\"], 3)\n fig.update_xaxes(tick0=1, dtick=1)\n fig.update_traces(textposition='outside')\n fig.show()\n\n\ndef question_3(data):\n \"\"\" Exploring differences between countries\"\"\"\n agg_data_mean = data.groupby([\"Country\", \"Month\"]).mean().reset_index()\n agg_data_std = data.groupby([\"Country\", \"Month\"]).std().reset_index()\n\n fig = px.line(agg_data_mean, x=\"Month\", y=\"Temp\", color=\"Country\", error_y=agg_data_std[\"Temp\"],\n width=1500, height=700, labels={\"Temp\": \"Averaged Temperature\"},\n title=\"Q3 The Average Monthly Temperatures in Different Countries\")\n fig.update_xaxes(tick0=1, dtick=1)\n fig.show()\n\n\ndef question_4(data):\n \"\"\" Fitting model for different values of `k` \"\"\"\n data = data[data[\"Country\"] == \"Israel\"]\n train_X, train_y, test_X, test_y = split_train_test(data[\"DayOfYear\"], data[\"Temp\"])\n\n losses = np.array([])\n for k in range(1, 11):\n poly_fit = PolynomialFitting(k)\n poly_fit.fit(train_X.to_numpy(), train_y.to_numpy())\n loss = poly_fit.loss(test_X.to_numpy(), test_y.to_numpy())\n losses = np.append(losses, round(loss, 2))\n print(k, loss)\n\n fig = px.bar(x=range(1, 11), y=losses, width=1500, height=700,\n labels={\"x\": \"Polynomials Degrees (k)\", \"y\": \"Test Error (MSE)\"},\n title=\"Q4 Test Errors for Different Polynomials Degrees (k)\")\n fig.data[-1].text = losses\n fig.update_xaxes(tick0=1, dtick=1)\n fig.update_traces(textposition=\"outside\")\n fig.show()\n\n\ndef question_5(data):\n \"\"\" Evaluating fitted model on different countries \"\"\"\n data_israel = data[data[\"Country\"] == \"Israel\"]\n\n poly_fit = PolynomialFitting(k=5)\n poly_fit.fit(data_israel[\"DayOfYear\"], data_israel[\"Temp\"])\n\n other_countries = [\"Jordan\", \"South Africa\", \"The Netherlands\"]\n losses = np.array([])\n\n for country in other_countries:\n country_data = data[data[\"Country\"] == country]\n loss = poly_fit.loss(country_data[\"DayOfYear\"], country_data[\"Temp\"])\n losses = np.append(losses, loss)\n\n fig = px.bar(x=np.array(other_countries), y=losses, width=700, height=700,\n labels={\"x\": \"Country\", \"y\": \"Losses (MSE)\"}, title=\"Q5 Losses (MSE) per Country With k=5\")\n fig.data[-1].text = np.round(losses, 3)\n fig.update_traces(textposition=\"outside\")\n fig.show()\n\n\nif __name__ == '__main__':\n np.random.seed(0)\n # Question 1 - Load and preprocessing of city temperature dataset\n data = load_data(CITY_TEMPERATURE_DATA_PATH)\n\n # Question 2 - Exploring data for specific country\n question_2(data)\n\n # Question 3 - Exploring differences between countries\n question_3(data)\n\n # Question 4 - Fitting model for different values of `k`\n question_4(data)\n\n # Question 5 - Evaluating fitted model on different countries\n question_5(data)\n\n" ]
[ [ "pandas.read_csv", "numpy.random.seed", "numpy.round", "numpy.append", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
moriyoshi/dummydf
[ "39d82f0022ea9d072ce56724f16bf363a37b1bbf" ]
[ "dummydf/sql/dataframe.py" ]
[ "# coding: utf-8\n#\n# Copyright 2018 Moriyoshi Koizumi\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport six\nimport pandas\nfrom .column import _DataFrameColumn, _Function, _Literal, eval_column, infer_data_type, compile_to_raf, resolve_alias\nfrom .functions import SimpleAggregationFunctionSpec\nfrom .group import GroupedData\nfrom .types import StructType, StructField\n\n\nclass _Raw(object):\n def __init__(self, pdf):\n self.pdf = pdf\n\n def __call__(self, df):\n return self.pdf\n\n\nclass _Filter(object):\n def __init__(self, df, expr):\n self.df = df\n self.expr = expr\n\n def __call__(self, df):\n raf = compile_to_raf(df, self.expr)\n pdf = self.df._yield_pdf()\n return pdf.loc[raf]\n\n\nclass _Aggregation(object):\n def __init__(self, grouped_data, agg_cols):\n self.grouped_data = grouped_data\n self.agg_cols = agg_cols\n\n def __call__(self, df):\n pdf = self.grouped_data.df._yield_pdf()\n agg_fn_cols = []\n agg_variations = set()\n const_cols = []\n resolved_cols = []\n for col in self.agg_cols:\n col = resolve_alias(col)\n resolved_cols.append(col)\n if isinstance(col, _Function):\n agg_fn_cols.append(col)\n if isinstance(col.spec, SimpleAggregationFunctionSpec):\n agg_variations.add(col.spec.fn)\n else:\n raise TypeError()\n elif isinstance(col, _Literal):\n const_cols.append(col)\n else:\n raise TypeError(col.__class__)\n\n if len(self.grouped_data.cols) > 0:\n pg = pdf.groupby(\n by=[pdf.iloc[:,col.index] for col in self.grouped_data.cols]\n )\n agg_result = pg.aggregate(list(agg_variations))\n agg_result = pandas.concat([agg_result.index.to_frame(), agg_result], axis=1)\n # convert columns to a set of series\n agg_result_index = agg_result.index.to_frame()\n series_set = [\n agg_result_index[col].rename(i)\n for i, col in enumerate(agg_result_index.columns)\n ]\n for col in resolved_cols:\n if isinstance(col, _Function):\n if isinstance(col.spec, SimpleAggregationFunctionSpec):\n series = agg_result[col.operands[0].index, col.spec.fn].rename(len(series_set))\n else:\n # should never get here; already validated in the above loop\n assert False\n elif isinstance(col, _Literal):\n series = pandas.Series([col.value], name=len(series_set))\n else:\n # should never get here; already validated in the above loop\n assert False\n series_set.append(series)\n else:\n agg_result = pdf.aggregate(list(agg_variations))\n # convert columns to a set of series\n series_set = []\n for col in self.agg_cols:\n if isinstance(col, _Function):\n if isinstance(col.spec, SimpleAggregationFunctionSpec):\n series = pandas.Series([agg_result[col.operands[0].index][col.spec.fn]], name=len(series_set))\n else:\n # should never get here; already validated in the above loop\n assert False\n elif isinstance(col, _Literal):\n series = pandas.Series([col.value], name=len(series_set))\n else:\n # should never get here; already validated in the above loop\n assert False\n series_set.append(series)\n\n return pandas.concat(series_set, axis=1)\n\n\nclass _WithColumns(object):\n def __init__(self, df, name_col_pairs):\n self.df = df\n self.name_col_pairs = name_col_pairs\n\n def __call__(self, df):\n extra_fields = df.schema.fields[len(self.df.schema.fields):]\n lhs = self.df._yield_pdf()\n return pandas.concat(\n [lhs] + [\n eval_column(df, lhs, col).rename(i)\n for i, (_, col) in enumerate(self.name_col_pairs, len(self.df.columns))\n ],\n axis=1\n )\n\n\nclass _Union(object):\n def __init__(self, df, following):\n self.df = df\n self.following = following\n\n def __call__(self, df):\n return pandas.concat([self.df._yield_pdf(), self.following._yield_pdf()], axis=0)\n\n\nclass _OrderBy(object):\n def __init__(self, df, cols, ascending=None):\n self.df = df\n self.cols = cols\n self.ascending = ascending\n\n def __call__(self, df):\n assert all(isinstance(col, _DataFrameColumn) for col in self.cols)\n return self.df._yield_pdf().sort_values(by=[col.index for col in self.cols], ascending=self.ascending)\n\n\nclass Row(object):\n def __init__(self, pdf, schema, i, name_to_column_map):\n self.pdf = pdf\n self.schema = schema\n self.i = i\n self.name_to_column_map = name_to_column_map\n\n def __str__(self):\n return str(self.pdf.iloc[self.i])\n\n def __getitem__(self, i):\n if isinstance(i, six.string_types):\n return self.pdf.iloc[self.i][self.name_to_column_map[i].index]\n else:\n return self.pdf.iloc[self.i][i]\n\n\nclass DataFrame(object):\n def __init__(self, sql_ctx, schema, modifier=None):\n self.sql_ctx = sql_ctx\n self.schema = schema\n self.modifier = modifier\n self._columns = [\n _DataFrameColumn(self, f, i)\n for i, f in enumerate(schema.fields)\n ]\n self._name_to_column_map = {\n f.name: c\n for f, c in zip(schema.fields, self._columns)\n }\n\n def __getitem__(self, i):\n if isinstance(i, six.string_types):\n return self._name_to_column_map[i]\n elif isinstance(i, (int, long)):\n return self._columns[i]\n else:\n raise TypeError()\n\n def filter(self, cond):\n return DataFrame(\n self.sql_ctx,\n self.schema,\n _Filter(self, cond)\n )\n\n def groupBy(self, *cols):\n return GroupedData(self, cols)\n\n def agg(self, *exprs):\n return self.groupBy().agg(*exprs)\n\n def withColumn(self, name, col):\n return self._with_columns([(name, col)])\n\n def unionAll(self, following):\n return DataFrame(\n self.sql_ctx,\n self.schema,\n _Union(self, following)\n )\n\n def orderBy(self, *cols, **kwargs):\n ascending = kwargs.pop('ascending', None)\n return DataFrame(\n self.sql_ctx,\n self.schema,\n _OrderBy(self, cols, ascending)\n )\n\n @property\n def columns(self):\n return [col.field.name for col in self._columns]\n\n def _with_columns(self, name_col_pairs):\n return DataFrame(\n self.sql_ctx,\n StructType(\n fields=self.schema.fields + [\n StructField(\n name,\n infer_data_type(col)\n )\n for name, col in name_col_pairs\n ]\n ),\n _WithColumns(self, name_col_pairs)\n )\n\n def _yield_pdf(self):\n return self.modifier(self)\n\n def collect(self):\n pdf = self._yield_pdf()\n return [\n Row(pdf, self.schema, i, self._name_to_column_map)\n for i in range(0, len(pdf))\n ]\n" ]
[ [ "pandas.concat" ] ]
[ { "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": [] } ]
psyoblade/playground
[ "28e60c24004a84d2fd70907988b06bd46d0446ca" ]
[ "pommerman/forward_model.py" ]
[ "'''Module to manage and advanced game state'''\nfrom collections import defaultdict\n\nimport numpy as np\n\nfrom . import constants\nfrom . import characters\nfrom . import utility\n\n\nclass ForwardModel(object):\n \"\"\"Class for helping with the [forward] modeling of the game state.\"\"\"\n\n def run(self,\n num_times,\n board,\n agents,\n bombs,\n items,\n flames,\n is_partially_observable,\n agent_view_size,\n action_space,\n training_agent=None,\n is_communicative=False):\n \"\"\"Run the forward model.\n\n Args:\n num_times: The number of times to run it for. This is a maximum and\n it will stop early if we reach a done.\n board: The board state to run it from.\n agents: The agents to use to run it.\n bombs: The starting bombs.\n items: The starting items.\n flames: The starting flames.\n is_partially_observable: Whether the board is partially observable or\n not. Only applies to TeamRadio.\n agent_view_size: If it's partially observable, then the size of the\n square that the agent can view.\n action_space: The actions that each agent can take.\n training_agent: The training agent to pass to done.\n is_communicative: Whether the action depends on communication\n observations as well.\n\n Returns:\n steps: The list of step results, which are each a dict of \"obs\",\n \"next_obs\", \"reward\", \"action\".\n board: Updated board.\n agents: Updated agents, same models though.\n bombs: Updated bombs.\n items: Updated items.\n flames: Updated flames.\n done: Whether we completed the game in these steps.\n info: The result of the game if it's completed.\n \"\"\"\n steps = []\n for _ in num_times:\n obs = self.get_observations(\n board, agents, bombs, is_partially_observable, agent_view_size)\n actions = self.act(\n agents, obs, action_space, is_communicative=is_communicative)\n board, agents, bombs, items, flames = self.step(\n actions, board, agents, bombs, items, flames)\n next_obs = self.get_observations(\n board, agents, bombs, is_partially_observable, agent_view_size)\n reward = self.get_rewards(agents, game_type, step_count, max_steps)\n done = self.get_done(agents, game_type, step_count, max_steps,\n training_agent)\n info = self.get_info(done, rewards, game_type, agents)\n\n steps.append({\n \"obs\": obs,\n \"next_obs\": next_obs,\n \"reward\": reward,\n \"actions\": actions,\n })\n if done:\n # Callback to let the agents know that the game has ended.\n for agent in agents:\n agent.episode_end(reward[agent.agent_id])\n break\n return steps, board, agents, bombs, items, flames, done, info\n\n @staticmethod\n def act(agents, obs, action_space, is_communicative=False):\n \"\"\"Returns actions for each agent in this list.\n\n Args:\n agents: A list of agent objects.\n obs: A list of matching observations per agent.\n action_space: The action space for the environment using this model.\n is_communicative: Whether the action depends on communication\n observations as well.\n\n Returns a list of actions.\n \"\"\"\n\n def act_ex_communication(agent):\n '''Handles agent's move without communication'''\n if agent.is_alive:\n return agent.act(obs[agent.agent_id], action_space=action_space)\n else:\n return constants.Action.Stop.value\n\n def act_with_communication(agent):\n '''Handles agent's move with communication'''\n if agent.is_alive:\n action = agent.act(\n obs[agent.agent_id], action_space=action_space)\n if type(action) == int:\n action = [action] + [0, 0]\n assert (type(action) == list)\n return action\n else:\n return [constants.Action.Stop.value, 0, 0]\n\n ret = []\n for agent in agents:\n if is_communicative:\n ret.append(act_with_communication(agent))\n else:\n ret.append(act_ex_communication(agent))\n return ret\n\n @staticmethod\n def step(actions,\n curr_board,\n curr_agents,\n curr_bombs,\n curr_items,\n curr_flames,\n max_blast_strength=10):\n board_size = len(curr_board)\n\n # Tick the flames. Replace any dead ones with passages. If there is an\n # item there, then reveal that item.\n flames = []\n for flame in curr_flames:\n position = flame.position\n if flame.is_dead():\n item_value = curr_items.get(position)\n if item_value:\n del curr_items[position]\n else:\n item_value = constants.Item.Passage.value\n curr_board[position] = item_value\n else:\n flame.tick()\n flames.append(flame)\n curr_flames = flames\n\n # Redraw all current flames\n # Multiple flames may share a position and the map should contain\n # a flame until all flames are dead to avoid issues with bomb\n # movements and explosions.\n for flame in curr_flames:\n curr_board[flame.position] = constants.Item.Flames.value\n\n # Step the living agents and moving bombs.\n # If two agents try to go to the same spot, they should bounce back to\n # their previous spots. This is complicated with one example being when\n # there are three agents all in a row. If the one in the middle tries\n # to go to the left and bounces with the one on the left, and then the\n # one on the right tried to go to the middle one's position, she should\n # also bounce. A way of doing this is to gather all the new positions\n # before taking any actions. Then, if there are disputes, correct those\n # disputes iteratively.\n # Additionally, if two agents try to switch spots by moving into each\n # Figure out desired next position for alive agents\n alive_agents = [agent for agent in curr_agents if agent.is_alive]\n desired_agent_positions = [agent.position for agent in alive_agents]\n\n for num_agent, agent in enumerate(alive_agents):\n position = agent.position\n # We change the curr_board here as a safeguard. We will later\n # update the agent's new position.\n curr_board[position] = constants.Item.Passage.value\n action = actions[agent.agent_id]\n\n if action == constants.Action.Stop.value:\n pass\n elif action == constants.Action.Bomb.value:\n position = agent.position\n if not utility.position_is_bomb(curr_bombs, position):\n bomb = agent.maybe_lay_bomb()\n if bomb:\n curr_bombs.append(bomb)\n elif utility.is_valid_direction(curr_board, position, action):\n desired_agent_positions[num_agent] = agent.get_next_position(\n action)\n\n # Gather desired next positions for moving bombs. Handle kicks later.\n desired_bomb_positions = [bomb.position for bomb in curr_bombs]\n\n for num_bomb, bomb in enumerate(curr_bombs):\n curr_board[bomb.position] = constants.Item.Passage.value\n if bomb.is_moving():\n desired_position = utility.get_next_position(\n bomb.position, bomb.moving_direction)\n if utility.position_on_board(curr_board, desired_position) \\\n and not utility.position_is_powerup(curr_board, desired_position) \\\n and not utility.position_is_wall(curr_board, desired_position):\n desired_bomb_positions[num_bomb] = desired_position\n\n # Position switches:\n # Agent <-> Agent => revert both to previous position.\n # Bomb <-> Bomb => revert both to previous position.\n # Agent <-> Bomb => revert Bomb to previous position.\n crossings = {}\n\n def crossing(current, desired):\n '''Checks to see if an agent is crossing paths'''\n current_x, current_y = current\n desired_x, desired_y = desired\n if current_x != desired_x:\n assert current_y == desired_y\n return ('X', min(current_x, desired_x), current_y)\n assert current_x == desired_x\n return ('Y', current_x, min(current_y, desired_y))\n\n for num_agent, agent in enumerate(alive_agents):\n if desired_agent_positions[num_agent] != agent.position:\n desired_position = desired_agent_positions[num_agent]\n border = crossing(agent.position, desired_position)\n if border in crossings:\n # Crossed another agent - revert both to prior positions.\n desired_agent_positions[num_agent] = agent.position\n num_agent2, _ = crossings[border]\n desired_agent_positions[num_agent2] = alive_agents[\n num_agent2].position\n else:\n crossings[border] = (num_agent, True)\n\n for num_bomb, bomb in enumerate(curr_bombs):\n if desired_bomb_positions[num_bomb] != bomb.position:\n desired_position = desired_bomb_positions[num_bomb]\n border = crossing(bomb.position, desired_position)\n if border in crossings:\n # Crossed - revert to prior position.\n desired_bomb_positions[num_bomb] = bomb.position\n num, is_agent = crossings[border]\n if not is_agent:\n # Crossed bomb - revert that to prior position as well.\n desired_bomb_positions[num] = curr_bombs[num].position\n else:\n crossings[border] = (num_bomb, False)\n\n # Deal with multiple agents or multiple bomb collisions on desired next\n # position by resetting desired position to current position for\n # everyone involved in the collision.\n agent_occupancy = defaultdict(int)\n bomb_occupancy = defaultdict(int)\n for desired_position in desired_agent_positions:\n agent_occupancy[desired_position] += 1\n for desired_position in desired_bomb_positions:\n bomb_occupancy[desired_position] += 1\n\n # Resolve >=2 agents or >=2 bombs trying to occupy the same space.\n change = True\n while change:\n change = False\n for num_agent, agent in enumerate(alive_agents):\n desired_position = desired_agent_positions[num_agent]\n curr_position = agent.position\n # Either another agent is going to this position or more than\n # one bomb is going to this position. In both scenarios, revert\n # to the original position.\n if desired_position != curr_position and \\\n (agent_occupancy[desired_position] > 1 or bomb_occupancy[desired_position] > 1):\n desired_agent_positions[num_agent] = curr_position\n agent_occupancy[curr_position] += 1\n change = True\n\n for num_bomb, bomb in enumerate(curr_bombs):\n desired_position = desired_bomb_positions[num_bomb]\n curr_position = bomb.position\n if desired_position != curr_position and \\\n (bomb_occupancy[desired_position] > 1 or agent_occupancy[desired_position] > 1):\n desired_bomb_positions[num_bomb] = curr_position\n bomb_occupancy[curr_position] += 1\n change = True\n\n # Handle kicks.\n agent_indexed_by_kicked_bomb = {}\n kicked_bomb_indexed_by_agent = {}\n delayed_bomb_updates = []\n delayed_agent_updates = []\n\n # Loop through all bombs to see if they need a good kicking or cause\n # collisions with an agent.\n for num_bomb, bomb in enumerate(curr_bombs):\n desired_position = desired_bomb_positions[num_bomb]\n\n if agent_occupancy[desired_position] == 0:\n # There was never an agent around to kick or collide.\n continue\n\n agent_list = [\n (num_agent, agent) for (num_agent, agent) in enumerate(alive_agents) \\\n if desired_position == desired_agent_positions[num_agent]]\n if not agent_list:\n # Agents moved from collision.\n continue\n\n # The agent_list should contain a single element at this point.\n assert (len(agent_list) == 1)\n num_agent, agent = agent_list[0]\n\n if desired_position == agent.position:\n # Agent did not move\n if desired_position != bomb.position:\n # Bomb moved, but agent did not. The bomb should revert\n # and stop.\n delayed_bomb_updates.append((num_bomb, bomb.position))\n continue\n\n # NOTE: At this point, we have that the agent in question tried to\n # move into this position.\n if not agent.can_kick:\n # If we move the agent at this point, then we risk having two\n # agents on a square in future iterations of the loop. So we\n # push this change to the next stage instead.\n delayed_bomb_updates.append((num_bomb, bomb.position))\n delayed_agent_updates.append((num_agent, agent.position))\n continue\n\n # Agent moved and can kick - see if the target for the kick never had anyhing on it\n direction = constants.Action(actions[agent.agent_id])\n target_position = utility.get_next_position(desired_position,\n direction)\n if utility.position_on_board(curr_board, target_position) and \\\n agent_occupancy[target_position] == 0 and \\\n bomb_occupancy[target_position] == 0 and \\\n not utility.position_is_powerup(curr_board, target_position) and \\\n not utility.position_is_wall(curr_board, target_position):\n # Ok to update bomb desired location as we won't iterate over it again here\n # but we can not update bomb_occupancy on target position and need to check it again\n # However we need to set the bomb count on the current position to zero so\n # that the agent can stay on this position.\n bomb_occupancy[desired_position] = 0\n delayed_bomb_updates.append((num_bomb, target_position))\n agent_indexed_by_kicked_bomb[num_bomb] = num_agent\n kicked_bomb_indexed_by_agent[num_agent] = num_bomb\n bomb.moving_direction = direction\n # Bombs may still collide and we then need to reverse bomb and agent ..\n else:\n delayed_bomb_updates.append((num_bomb, bomb.position))\n delayed_agent_updates.append((num_agent, agent.position))\n\n for (num_bomb, bomb_position) in delayed_bomb_updates:\n desired_bomb_positions[num_bomb] = bomb_position\n bomb_occupancy[bomb_position] += 1\n change = True\n\n for (num_agent, agent_position) in delayed_agent_updates:\n desired_agent_positions[num_agent] = agent_position\n agent_occupancy[agent_position] += 1\n change = True\n\n while change:\n change = False\n for num_agent, agent in enumerate(alive_agents):\n desired_position = desired_agent_positions[num_agent]\n curr_position = agent.position\n # Agents and bombs can only share a square if they are both in their\n # original position (Agent dropped bomb and has not moved)\n if desired_position != curr_position and \\\n (agent_occupancy[desired_position] > 1 or bomb_occupancy[desired_position] != 0):\n # Late collisions resulting from failed kicks force this agent to stay at the\n # original position. Check if this agent successfully kicked a bomb above and undo\n # the kick.\n if num_agent in kicked_bomb_indexed_by_agent:\n num_bomb = kicked_bomb_indexed_by_agent[num_agent]\n bomb = curr_bombs[num_bomb]\n desired_bomb_positions[num_bomb] = bomb.position\n bomb_occupancy[bomb.position] += 1\n del agent_indexed_by_kicked_bomb[num_bomb]\n del kicked_bomb_indexed_by_agent[num_agent]\n desired_agent_positions[num_agent] = curr_position\n agent_occupancy[curr_position] += 1\n change = True\n\n for num_bomb, bomb in enumerate(curr_bombs):\n desired_position = desired_bomb_positions[num_bomb]\n curr_position = bomb.position\n\n # This bomb may be a boomerang, i.e. it was kicked back to the\n # original location it moved from. If it is blocked now, it\n # can't be kicked and the agent needs to move back to stay\n # consistent with other movements.\n if desired_position == curr_position and num_bomb not in agent_indexed_by_kicked_bomb:\n continue\n\n bomb_occupancy_ = bomb_occupancy[desired_position]\n agent_occupancy_ = agent_occupancy[desired_position]\n # Agents and bombs can only share a square if they are both in their\n # original position (Agent dropped bomb and has not moved)\n if bomb_occupancy_ > 1 or agent_occupancy_ != 0:\n desired_bomb_positions[num_bomb] = curr_position\n bomb_occupancy[curr_position] += 1\n num_agent = agent_indexed_by_kicked_bomb.get(num_bomb)\n if num_agent is not None:\n agent = alive_agents[num_agent]\n desired_agent_positions[num_agent] = agent.position\n agent_occupancy[agent.position] += 1\n del kicked_bomb_indexed_by_agent[num_agent]\n del agent_indexed_by_kicked_bomb[num_bomb]\n change = True\n\n for num_bomb, bomb in enumerate(curr_bombs):\n if desired_bomb_positions[num_bomb] == bomb.position and \\\n not num_bomb in agent_indexed_by_kicked_bomb:\n # Bomb was not kicked this turn and its desired position is its\n # current location. Stop it just in case it was moving before.\n bomb.stop()\n else:\n # Move bomb to the new position.\n # NOTE: We already set the moving direction up above.\n bomb.position = desired_bomb_positions[num_bomb]\n\n for num_agent, agent in enumerate(alive_agents):\n if desired_agent_positions[num_agent] != agent.position:\n agent.move(actions[agent.agent_id])\n if utility.position_is_powerup(curr_board, agent.position):\n agent.pick_up(\n constants.Item(curr_board[agent.position]),\n max_blast_strength=max_blast_strength)\n\n # Explode bombs.\n exploded_map = np.zeros_like(curr_board)\n has_new_explosions = False\n\n for bomb in curr_bombs:\n bomb.tick()\n if bomb.exploded():\n has_new_explosions = True\n elif curr_board[bomb.position] == constants.Item.Flames.value:\n bomb.fire()\n has_new_explosions = True\n\n # Chain the explosions.\n while has_new_explosions:\n next_bombs = []\n has_new_explosions = False\n for bomb in curr_bombs:\n if not bomb.exploded():\n next_bombs.append(bomb)\n continue\n\n bomb.bomber.incr_ammo()\n for _, indices in bomb.explode().items():\n for r, c in indices:\n if not all(\n [r >= 0, c >= 0, r < board_size, c < board_size]):\n break\n if curr_board[r][c] == constants.Item.Rigid.value:\n break\n exploded_map[r][c] = 1\n if curr_board[r][c] == constants.Item.Wood.value:\n break\n\n curr_bombs = next_bombs\n for bomb in curr_bombs:\n if bomb.in_range(exploded_map):\n bomb.fire()\n has_new_explosions = True\n\n # Update the board's bombs.\n for bomb in curr_bombs:\n curr_board[bomb.position] = constants.Item.Bomb.value\n\n # Update the board's flames.\n flame_positions = np.where(exploded_map == 1)\n for row, col in zip(flame_positions[0], flame_positions[1]):\n curr_flames.append(characters.Flame((row, col)))\n for flame in curr_flames:\n curr_board[flame.position] = constants.Item.Flames.value\n\n # Kill agents on flames. Otherwise, update position on curr_board.\n for agent in alive_agents:\n if curr_board[agent.position] == constants.Item.Flames.value:\n agent.die()\n else:\n curr_board[agent.position] = utility.agent_value(agent.agent_id)\n\n return curr_board, curr_agents, curr_bombs, curr_items, curr_flames\n\n def get_observations(self, curr_board, agents, bombs,\n is_partially_observable, agent_view_size, \n game_type, game_env):\n \"\"\"Gets the observations as an np.array of the visible squares.\n\n The agent gets to choose whether it wants to keep the fogged part in\n memory.\n \"\"\"\n board_size = len(curr_board)\n\n def make_bomb_maps(position):\n ''' Makes an array of an agents bombs and the bombs attributes '''\n blast_strengths = np.zeros((board_size, board_size))\n life = np.zeros((board_size, board_size))\n\n for bomb in bombs:\n x, y = bomb.position\n if not is_partially_observable \\\n or in_view_range(position, x, y):\n blast_strengths[(x, y)] = bomb.blast_strength\n life[(x, y)] = bomb.life\n return blast_strengths, life\n\n def in_view_range(position, v_row, v_col):\n '''Checks to see if a tile is in an agents viewing area'''\n row, col = position\n return all([\n row >= v_row - agent_view_size, row <= v_row + agent_view_size,\n col >= v_col - agent_view_size, col <= v_col + agent_view_size\n ])\n\n attrs = [\n 'position', 'blast_strength', 'can_kick', 'teammate', 'ammo',\n 'enemies'\n ]\n alive_agents = [\n utility.agent_value(agent.agent_id)\n for agent in agents\n if agent.is_alive\n ]\n\n observations = []\n for agent in agents:\n agent_obs = {'alive': alive_agents}\n board = curr_board\n if is_partially_observable:\n board = board.copy()\n for row in range(board_size):\n for col in range(board_size):\n if not in_view_range(agent.position, row, col):\n board[row, col] = constants.Item.Fog.value\n agent_obs['board'] = board\n bomb_blast_strengths, bomb_life = make_bomb_maps(agent.position)\n agent_obs['bomb_blast_strength'] = bomb_blast_strengths\n agent_obs['bomb_life'] = bomb_life\n agent_obs['game_type'] = game_type.value\n agent_obs['game_env'] = game_env\n\n for attr in attrs:\n assert hasattr(agent, attr)\n agent_obs[attr] = getattr(agent, attr)\n observations.append(agent_obs)\n\n return observations\n\n @staticmethod\n def get_done(agents, step_count, max_steps, game_type, training_agent):\n # print('get_done called...', training_agent)\n alive = [agent for agent in agents if agent.is_alive]\n alive_ids = sorted([agent.agent_id for agent in alive])\n if step_count >= max_steps:\n print('gameover : max timestep over')\n return True\n elif game_type == constants.GameType.FFA:\n if training_agent is not None and training_agent not in alive_ids:\n print('gameover : ffa training_agent has died')\n return True\n if len(alive) <= 1:\n print('checkout : ffa only %s player survived' % len(alive))\n return len(alive) <= 1\n elif len(alive_ids) <= 1:\n print('gameover : only one player survived')\n return True\n elif alive_ids == [0, 2]:\n print('gameover : [0,2] team won')\n return True\n elif any([ alive_ids == [1, 3] ]):\n print('gameover : [1,3] team won')\n return True\n return False\n\n @staticmethod\n def get_info(done, rewards, game_type, agents):\n if game_type == constants.GameType.FFA:\n alive = [agent for agent in agents if agent.is_alive]\n if done:\n if len(alive) != 1:\n # Either we have more than 1 alive (reached max steps) or\n # we have 0 alive (last agents died at the same time).\n return {\n 'result': constants.Result.Tie,\n }\n else:\n return {\n 'result': constants.Result.Win,\n 'winners': [num for num, reward in enumerate(rewards) \\\n if reward == 1]\n }\n else:\n return {\n 'result': constants.Result.Incomplete,\n }\n elif done:\n # We are playing a team game.\n if rewards == [-1] * 4:\n return {\n 'result': constants.Result.Tie,\n }\n else:\n return {\n 'result': constants.Result.Win,\n 'winners': [num for num, reward in enumerate(rewards) \\\n if reward == 1],\n }\n else:\n return {\n 'result': constants.Result.Incomplete,\n }\n\n @staticmethod\n def get_rewards(agents, game_type, step_count, max_steps):\n print('get_rewards called..', self.training_agent)\n\n def any_lst_equal(lst, values):\n '''Checks if list are equal'''\n return any([lst == v for v in values])\n\n alive_agents = [num for num, agent in enumerate(agents) \\\n if agent.is_alive]\n if game_type == constants.GameType.FFA:\n if len(alive_agents) == 1:\n # An agent won. Give them +1, others -1.\n return [2 * int(agent.is_alive) - 1 for agent in agents]\n elif step_count >= max_steps:\n # Game is over from time. Everyone gets -1.\n return [-1] * 4\n else:\n # Game running: 0 for alive, -1 for dead.\n return [int(agent.is_alive) - 1 for agent in agents]\n else:\n # We are playing a team game.\n if any_lst_equal(alive_agents, [[0, 2], [0], [2]]):\n # Team [0, 2] wins.\n return [1, -1, 1, -1]\n elif any_lst_equal(alive_agents, [[1, 3], [1], [3]]):\n # Team [1, 3] wins.\n return [-1, 1, -1, 1]\n elif step_count >= max_steps:\n # Game is over by max_steps. All agents tie.\n return [-1] * 4\n elif len(alive_agents) == 0:\n # Everyone's dead. All agents tie.\n return [-1] * 4\n else:\n # No team has yet won or lost.\n return [0] * 4\n" ]
[ [ "numpy.zeros_like", "numpy.where", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
klens-codes/MaskFlownet-Pytorch
[ "94d41fd20f774845a1b2df7f77ec95c44217af94" ]
[ "data_loaders/KLens.py" ]
[ "import os\nimport re\nimport struct\nimport glob\nimport numpy as np\nimport frame_utils\nimport skimage\nimport skimage.io\n\nimport torch\nfrom torch.utils.data import Dataset\n\n\nclass KLens(Dataset):\n #def __init__(self,raft_path=\"/data2/opticalflow/rnd/opticalflow/RAFT/out_klens_raft_chairs\", root_path=\"/data2/opticalflow/KLENS/images/\",root_path2=\"/data2/opticalflow/KLENS/pins/\",filenumberlist=[\"0030\",\"1106\",\"1113\",\"1132\",\"1134\",\"1167\",\"1173\"],split=\"train\",ref=\"\",meas=\"\"):\n def __init__(self,raft_path=\"/data2/opticalflow/algo_comp/flownet2/out/\", root_path=\"/data2/opticalflow/KLENS/images/\",root_path2=\"/data2/opticalflow/KLENS/pins/\",filenumberlist=[\"0030\",\"1106\",\"1113\",\"1132\",\"1134\",\"1167\",\"1173\"],split=\"train\",ref=\"\",meas=\"\"):\n super(KLens, self).__init__()\n self.split = split\n raftflowpaths = glob.glob(os.path.join(raft_path,\"*.flo\"))\n file_list = {}\n file_list['train'] = []\n file_list['valid'] = []\n file_list['test'] = []\n file_list['train+valid'] = []\n \n for filenum in filenumberlist:\n for raftflowpath in raftflowpaths:\n #print(raftflowpath)\n if \"KLE_\"+filenum in raftflowpath:\n file_list['train'].append([os.path.join(root_path,\"KLE_\"+filenum+\".jpg3.png\"),os.path.join(root_path,\"KLE_\"+filenum+\".jpg5.png\"),raftflowpath])\n file_list[\"train\"].extend([[os.path.join(root_path,\"KLE_0309_exp_sub5.jpg\"),os.path.join(root_path,\"KLE_0309_exp_sub6.jpg\")],[os.path.join(root_path,\"KLE_0730_sub5.jpg\"),os.path.join(root_path,\"KLE_0730_sub6.jpg\")],[os.path.join(root_path,\"KLE_0747_sub5.jpg\"),os.path.join(root_path,\"KLE_0747_sub6.jpg\")],[os.path.join(root_path,\"KLE_9797clean_sub5.jpg\"),os.path.join(root_path,\"KLE_9797clean_sub6.jpg\")],[os.path.join(root_path,\"KLE_9803clean_sub5.jpg\"),os.path.join(root_path,\"KLE_9803clean_sub6.jpg\")],[os.path.join(root_path,\"NKM_0063_sub5.jpg\"),os.path.join(root_path,\"NKM_0063_sub6.jpg\")],[os.path.join(root_path,\"NKM_0109_sub5.jpg\"),os.path.join(root_path,\"NKM_0109_sub6.jpg\")],[os.path.join(root_path,\"scene_1_sub5.jpg\"),os.path.join(root_path,\"scene_1_sub6.jpg\")]])\n file_list[\"valid\"].extend([[os.path.join(root_path,\"KLE_0309_exp_sub5.jpg\"),os.path.join(root_path,\"KLE_0309_exp_sub6.jpg\")],[os.path.join(root_path,\"KLE_0730_sub5.jpg\"),os.path.join(root_path,\"KLE_0730_sub6.jpg\")],[os.path.join(root_path,\"KLE_0747_sub5.jpg\"),os.path.join(root_path,\"KLE_0747_sub6.jpg\")],[os.path.join(root_path,\"KLE_9797clean_sub5.jpg\"),os.path.join(root_path,\"KLE_9797clean_sub6.jpg\")],[os.path.join(root_path,\"KLE_9803clean_sub5.jpg\"),os.path.join(root_path,\"KLE_9803clean_sub6.jpg\")],[os.path.join(root_path,\"NKM_0063_sub5.jpg\"),os.path.join(root_path,\"NKM_0063_sub6.jpg\")],[os.path.join(root_path,\"NKM_0109_sub5.jpg\"),os.path.join(root_path,\"NKM_0109_sub6.jpg\")],[os.path.join(root_path,\"scene_1_sub5.jpg\"),os.path.join(root_path,\"scene_1_sub6.jpg\")]])\n file_list[\"test\"].extend([[os.path.join(root_path,\"KLE_0309_exp_sub5.jpg\"),os.path.join(root_path,\"KLE_0309_exp_sub6.jpg\")],[os.path.join(root_path,\"KLE_0730_sub5.jpg\"),os.path.join(root_path,\"KLE_0730_sub6.jpg\")],[os.path.join(root_path,\"KLE_0747_sub5.jpg\"),os.path.join(root_path,\"KLE_0747_sub6.jpg\")],[os.path.join(root_path,\"KLE_9797clean_sub5.jpg\"),os.path.join(root_path,\"KLE_9797clean_sub6.jpg\")],[os.path.join(root_path,\"KLE_9803clean_sub5.jpg\"),os.path.join(root_path,\"KLE_9803clean_sub6.jpg\")],[os.path.join(root_path,\"NKM_0063_sub5.jpg\"),os.path.join(root_path,\"NKM_0063_sub6.jpg\")],[os.path.join(root_path,\"NKM_0109_sub5.jpg\"),os.path.join(root_path,\"NKM_0109_sub6.jpg\")],[os.path.join(root_path,\"scene_1_sub5.jpg\"),os.path.join(root_path,\"scene_1_sub6.jpg\")]])\n file_list[\"train+valid\"].extend([[os.path.join(root_path,\"KLE_0309_exp_sub5.jpg\"),os.path.join(root_path,\"KLE_0309_exp_sub6.jpg\")],[os.path.join(root_path,\"KLE_0730_sub5.jpg\"),os.path.join(root_path,\"KLE_0730_sub6.jpg\")],[os.path.join(root_path,\"KLE_0747_sub5.jpg\"),os.path.join(root_path,\"KLE_0747_sub6.jpg\")],[os.path.join(root_path,\"KLE_9797clean_sub5.jpg\"),os.path.join(root_path,\"KLE_9797clean_sub6.jpg\")],[os.path.join(root_path,\"KLE_9803clean_sub5.jpg\"),os.path.join(root_path,\"KLE_9803clean_sub6.jpg\")],[os.path.join(root_path,\"NKM_0063_sub5.jpg\"),os.path.join(root_path,\"NKM_0063_sub6.jpg\")],[os.path.join(root_path,\"NKM_0109_sub5.jpg\"),os.path.join(root_path,\"NKM_0109_sub6.jpg\")],[os.path.join(root_path,\"scene_1_sub5.jpg\"),os.path.join(root_path,\"scene_1_sub6.jpg\")]])\n #file_list[\"train\"].extend([[os.path.join(root_path2,\"9-AIT_pins_2.jpg\"),os.path.join(root_path2,\"9-AIT_pins_3.jpg\")],[os.path.join(root_path2,\"10-Hela_2.jpg\"),os.path.join(root_path2,\"10-Hela_3.jpg\")],[os.path.join(root_path2,\"11-Hela_1_2.jpg\"),os.path.join(root_path2,\"11-Hela_1_3.jpg\")],])\n #file_list[\"train\"].extend([[os.path.join(root_path2,\"9-AIT_pins_2.jpg\"),os.path.join(root_path2,\"9-AIT_pins_0.jpg\")],[os.path.join(root_path2,\"10-Hela_2.jpg\"),os.path.join(root_path2,\"10-Hela_0.jpg\")],[os.path.join(root_path2,\"11-Hela_1_2.jpg\"),os.path.join(root_path2,\"11-Hela_1_0.jpg\")],])\n #file_list[\"train\"].extend([[os.path.join(root_path2,\"9-AIT_pins_2.jpg\"),os.path.join(root_path2,\"9-AIT_pins_1.jpg\")],[os.path.join(root_path2,\"10-Hela_2.jpg\"),os.path.join(root_path2,\"10-Hela_1.jpg\")],[os.path.join(root_path2,\"11-Hela_1_2.jpg\"),os.path.join(root_path2,\"11-Hela_1_1.jpg\")],])\n #file_list[\"train\"].extend([[os.path.join(root_path2,\"9-AIT_pins_2.jpg\"),os.path.join(root_path2,\"9-AIT_pins_4.jpg\")],[os.path.join(root_path2,\"10-Hela_2.jpg\"),os.path.join(root_path2,\"10-Hela_4.jpg\")],[os.path.join(root_path2,\"11-Hela_1_2.jpg\"),os.path.join(root_path2,\"11-Hela_1_4.jpg\")],])\n self.dataset = file_list\n\n def __len__(self):\n return len(self.dataset[self.split])\n\n def __getitem__(self, idx):\n try:\n im0_path, im1_path, raftflow_path = self.dataset[self.split][idx]\n raftflow = frame_utils.readFlow(raftflow_path)\n except:\n im0_path, im1_path = self.dataset[self.split][idx]\n raftflow = np.array([])\n img0 = skimage.io.imread(im0_path)\n img1 = skimage.io.imread(im1_path)\n img0 = torch.tensor(img0/255.).float()\n img1 = torch.tensor(img1/255.).float()\n\n return img0, img1,np.array([]),np.array([]), [im0_path , im1_path],raftflow\n\n\nclass Flo:\n def __init__(self, w, h):\n self.__floec1__ = float(202021.25)\n self.__floec2__ = int(w)\n self.__floec3__ = int(h)\n self.__floheader__ = struct.pack('fii', self.__floec1__, self.__floec2__, self.__floec3__)\n self.__floheaderlen__ = len(self.__floheader__)\n self.__flow__ = w\n self.__floh__ = h\n self.__floshape__ = [self.__floh__, self.__flow__, 2]\n\n if self.__floheader__[:4] != b'PIEH':\n raise Exception('Expect machine to be LE.')\n\n def load(self, file):\n with open(file, 'rb') as fp:\n if fp.read(self.__floheaderlen__) != self.__floheader__:\n raise Exception('Bad flow header: ' + file)\n result = np.ndarray(shape=self.__floshape__,\n dtype=np.float32,\n buffer=fp.read(),\n order='C')\n return result\n\n def save(self, arr, fname):\n with open(fname, 'wb') as fp:\n fp.write(self.__floheader__)\n fp.write(arr.astype(np.float32).tobytes())\n\n" ]
[ [ "numpy.array", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
anniyanvr/nesta
[ "4b3ae79922cebde0ad33e08ac4c40b9a10e8e7c3", "4b3ae79922cebde0ad33e08ac4c40b9a10e8e7c3" ]
[ "nesta/packages/geo_utils/tests/test_geotools.py", "nesta/packages/worldbank/collect_worldbank.py" ]
[ "import pandas as pd\nfrom pandas.testing import assert_frame_equal\nimport pytest\nfrom unittest import mock\n\nfrom nesta.packages.geo_utils.geocode import geocode\nfrom nesta.packages.geo_utils.geocode import _geocode\nfrom nesta.packages.geo_utils.geocode import geocode_dataframe\nfrom nesta.packages.geo_utils.geocode import geocode_batch_dataframe\nfrom nesta.packages.geo_utils.geocode import generate_composite_key\nfrom nesta.packages.geo_utils.country_iso_code import country_iso_code\nfrom nesta.packages.geo_utils.country_iso_code import country_iso_code_dataframe\nfrom nesta.packages.geo_utils.country_iso_code import country_iso_code_to_name\nfrom nesta.packages.geo_utils.lookup import get_continent_lookup\nfrom nesta.packages.geo_utils.lookup import get_country_region_lookup\nfrom nesta.packages.geo_utils.lookup import get_country_continent_lookup\n\nREQUESTS = 'nesta.packages.geo_utils.geocode.requests.get'\nPYCOUNTRY = 'nesta.packages.geo_utils.country_iso_code.pycountry.countries.get'\nGEOCODE = 'nesta.packages.geo_utils.geocode.geocode'\n_GEOCODE = 'nesta.packages.geo_utils.geocode._geocode'\nCOUNTRY_ISO_CODE = 'nesta.packages.geo_utils.country_iso_code.country_iso_code'\n\n\nclass TestGeocoding():\n @staticmethod\n @pytest.fixture\n def mocked_osm_response():\n mocked_response = mock.Mock()\n mocked_response.json.return_value = [{'lat': '12.923432', 'lon': '-75.234569'}]\n return mocked_response\n\n def test_error_raised_when_arguments_missing(self):\n with pytest.raises(ValueError) as e:\n geocode()\n assert \"No geocode match\" in str(e.value)\n\n @mock.patch(REQUESTS)\n def test_request_includes_user_agent_in_header(self, mocked_request, mocked_osm_response):\n mocked_request.return_value = mocked_osm_response\n geocode(something='a')\n assert mocked_request.call_args[1]['headers'] == {'User-Agent': 'Nesta health data geocode'}\n\n @mock.patch(REQUESTS)\n def test_url_correct_with_city_and_country(self, mocked_request, mocked_osm_response):\n mocked_request.return_value = mocked_osm_response\n kwargs = dict(city='london', country='UK')\n geocode(**kwargs)\n assert mocked_request.call_args[1]['params'] == dict(format=\"json\", **kwargs)\n\n @mock.patch(REQUESTS)\n def test_url_correct_with_query(self, mocked_request, mocked_osm_response):\n mocked_request.return_value = mocked_osm_response\n kwargs = dict(q='my place')\n geocode(**kwargs)\n assert mocked_request.call_args[1]['params'] == dict(format=\"json\", **kwargs)\n\n @mock.patch(REQUESTS)\n def test_error_returned_if_no_match(self, mocked_request):\n mocked_response = mock.Mock()\n mocked_response.json.return_value = []\n mocked_request.return_value = mocked_response\n with pytest.raises(ValueError) as e:\n geocode(q=\"Something bad\")\n assert \"No geocode match\" in str(e.value)\n\n @mock.patch(REQUESTS)\n def test_coordinates_extracted_from_json_with_one_result(self, mocked_request, mocked_osm_response):\n mocked_request.return_value = mocked_osm_response\n assert geocode(q='somewhere') == [{'lat': '12.923432', 'lon': '-75.234569'}]\n\n @mock.patch(GEOCODE)\n def test_geocode_wrapper_rejects_invalid_query_parameters(self, mocked_geocode):\n with pytest.raises(ValueError) as e:\n _geocode(cat='dog', city='Nice')\n assert \"Invalid query parameter\" in str(e.value)\n\n @mock.patch(GEOCODE)\n def test_geocode_wrapper_rejects_both_q_and_kwargs_supplied(self, mocked_geocode):\n with pytest.raises(ValueError) as e:\n _geocode(city='London', q='somewhere')\n assert \"Supply either q OR other query parameters, they cannot be combined.\" in str(e.value)\n\n @mock.patch(GEOCODE)\n def test_geocode_wrapper_errors_if_no_query_parameters_supplied(self, mocked_geocode):\n with pytest.raises(ValueError) as e:\n _geocode()\n assert \"No query parameters supplied\" in str(e.value)\n\n @mock.patch(GEOCODE)\n def test_geocode_wrapper_calls_geocode_properly(self, mocked_geocode):\n mocked_geocode.return_value = [{'lat': 1.1, 'lon': 2.2}]\n\n _geocode('my place')\n _geocode(q='somewhere')\n _geocode(city='London', country='UK')\n _geocode(postalcode='ABC 123')\n\n expected_calls = [mock.call(q='my place'),\n mock.call(q='somewhere'),\n mock.call(city='London', country='UK'),\n mock.call(postalcode='ABC 123')\n ]\n assert mocked_geocode.mock_calls == expected_calls\n\n\nclass TestGeocodeDataFrame():\n @staticmethod\n @pytest.fixture\n def test_dataframe():\n df = pd.DataFrame({'index': [0, 1, 2],\n 'city': ['London', 'Sheffield', 'Brussels'],\n 'country': ['UK', 'United Kingdom', 'Belgium'],\n })\n return df\n\n @mock.patch(_GEOCODE)\n def test_underlying_geocoding_function_called_with_city_country(self, mocked_geocode,\n test_dataframe):\n # Generate dataframe using a mocked output\n mocked_geocode.side_effect = ['cat', 'dog', 'squirrel']\n geocoded_dataframe = geocode_dataframe(test_dataframe)\n\n # Expected outputs\n expected_dataframe = pd.DataFrame({'index': [0, 1, 2],\n 'city': ['London', 'Sheffield', 'Brussels'],\n 'country': ['UK', 'United Kingdom', 'Belgium'],\n 'coordinates': ['cat', 'dog', 'squirrel']\n })\n expected_calls = [mock.call(city='London', country='UK'),\n mock.call(city='Sheffield', country='United Kingdom'),\n mock.call(city='Brussels', country='Belgium')]\n\n # Check expected behaviours\n assert geocoded_dataframe.to_dict(orient=\"records\") == expected_dataframe.to_dict(orient=\"records\")\n assert mocked_geocode.mock_calls == expected_calls\n\n @mock.patch(_GEOCODE)\n def test_underlying_geocoding_function_called_with_query_fallback(self, mocked_geocode,\n test_dataframe):\n mocked_geocode.side_effect = [None, None, None, 'dog', 'cat', 'squirrel']\n geocoded_dataframe = geocode_dataframe(test_dataframe)\n # Expected outputs\n expected_dataframe = pd.DataFrame({'index': [0, 1, 2],\n 'city': ['London', 'Sheffield', 'Brussels'],\n 'country': ['UK', 'United Kingdom', 'Belgium'],\n 'coordinates': ['dog', 'cat', 'squirrel']\n })\n expected_calls = [mock.call(city='London', country='UK'),\n mock.call(city='Sheffield', country='United Kingdom'),\n mock.call(city='Brussels', country='Belgium'),\n mock.call('London UK'),\n mock.call('Sheffield United Kingdom'),\n mock.call('Brussels Belgium')]\n\n # Check expected behaviours\n assert geocoded_dataframe.to_dict(orient=\"records\") == expected_dataframe.to_dict(orient=\"records\")\n assert mocked_geocode.mock_calls == expected_calls\n\n @mock.patch(_GEOCODE)\n def test_duplicates_are_only_geocoded_once(self, mocked_geocode):\n test_dataframe = pd.DataFrame({'index': [0, 1, 2, 3],\n 'city': ['London', 'Brussels', 'London', 'Brussels'],\n 'country': ['UK', 'Belgium', 'UK', 'Belgium']\n })\n\n mocked_geocode.side_effect = ['LON', 'BRU']\n geocoded_dataframe = geocode_dataframe(test_dataframe)\n\n expected_dataframe = pd.DataFrame({'index': [0, 1, 2, 3],\n 'city': ['London', 'Brussels', 'London', 'Brussels'],\n 'country': ['UK', 'Belgium', 'UK', 'Belgium'],\n 'coordinates': ['LON', 'BRU', 'LON', 'BRU']\n })\n\n assert geocoded_dataframe.to_dict(orient=\"records\") == expected_dataframe.to_dict(orient=\"records\")\n assert mocked_geocode.call_count == 2\n\n\nclass TestGeocodeBatchDataframe():\n @staticmethod\n @pytest.fixture\n def test_dataframe():\n df = pd.DataFrame({'index': [0, 1, 2],\n 'city': ['London', 'Sheffield', 'Brussels'],\n 'country': ['UK', 'United Kingdom', 'Belgium'],\n })\n return df\n\n @mock.patch(_GEOCODE)\n def test_underlying_geocoding_function_called_with_city_country(self, mocked_geocode,\n test_dataframe):\n # Generate dataframe using a mocked output\n mocked_geocode.side_effect = [{'lat': '12.923432', 'lon': '-75.234569'},\n {'lat': '99.999999', 'lon': '-88.888888'},\n {'lat': '-2.202022', 'lon': '0.000000'}\n ]\n\n # Expected outputs\n expected_dataframe = pd.DataFrame({'index': [0, 1, 2],\n 'city': ['London', 'Sheffield', 'Brussels'],\n 'country': ['UK', 'United Kingdom', 'Belgium'],\n 'latitude': [12.923432, 99.999999, -2.202022],\n 'longitude': [-75.234569, -88.888888, 0.0]\n })\n expected_calls = [mock.call(city='London', country='UK'),\n mock.call(city='Sheffield', country='United Kingdom'),\n mock.call(city='Brussels', country='Belgium')]\n\n geocoded_dataframe = geocode_batch_dataframe(test_dataframe)\n\n # Check expected behaviours\n assert_frame_equal(geocoded_dataframe, expected_dataframe,\n check_like=True, check_dtype=False)\n assert mocked_geocode.mock_calls == expected_calls\n\n @mock.patch(_GEOCODE)\n def test_underlying_geocoding_function_called_with_query_fallback(self,\n mocked_geocode,\n test_dataframe):\n mocked_geocode.side_effect = [None,\n {'lat': 1, 'lon': 4},\n None,\n {'lat': 2, 'lon': 5},\n None,\n {'lat': 3, 'lon': 6}\n ]\n # Expected outputs\n expected_dataframe = pd.DataFrame({'index': [0, 1, 2],\n 'city': ['London', 'Sheffield', 'Brussels'],\n 'country': ['UK', 'United Kingdom', 'Belgium'],\n 'latitude': [1.0, 2.0, 3.0],\n 'longitude': [4.0, 5.0, 6.0],\n })\n expected_calls = [mock.call(city='London', country='UK'),\n mock.call(q='London UK'),\n mock.call(city='Sheffield', country='United Kingdom'),\n mock.call(q='Sheffield United Kingdom'),\n mock.call(city='Brussels', country='Belgium'),\n mock.call(q='Brussels Belgium')]\n\n geocoded_dataframe = geocode_batch_dataframe(test_dataframe, query_method='both')\n\n # Check expected behaviours\n assert_frame_equal(geocoded_dataframe, expected_dataframe,\n check_like=True, check_dtype=False)\n assert mocked_geocode.mock_calls == expected_calls\n\n @mock.patch(_GEOCODE)\n def test_underlying_geocoding_function_called_with_query_method_only(self,\n mocked_geocode,\n test_dataframe):\n mocked_geocode.side_effect = [{'lat': 1, 'lon': 4},\n {'lat': 2, 'lon': 5},\n {'lat': 3, 'lon': 6}\n ]\n # Expected outputs\n expected_dataframe = pd.DataFrame({'index': [0, 1, 2],\n 'city': ['London', 'Sheffield', 'Brussels'],\n 'country': ['UK', 'United Kingdom', 'Belgium'],\n 'latitude': [1.0, 2.0, 3.0],\n 'longitude': [4.0, 5.0, 6.0],\n })\n expected_calls = [mock.call(q='London UK'),\n mock.call(q='Sheffield United Kingdom'),\n mock.call(q='Brussels Belgium')]\n\n geocoded_dataframe = geocode_batch_dataframe(test_dataframe, query_method='query_only')\n\n # Check expected behaviours\n assert_frame_equal(geocoded_dataframe, expected_dataframe,\n check_like=True, check_dtype=False)\n assert mocked_geocode.mock_calls == expected_calls\n\n @mock.patch(_GEOCODE)\n def test_valueerror_raised_when_invalid_query_method_passed(self,\n mocked_geocode,\n test_dataframe):\n with pytest.raises(ValueError):\n geocode_batch_dataframe(test_dataframe, query_method='cats')\n\n with pytest.raises(ValueError):\n geocode_batch_dataframe(test_dataframe, query_method='test')\n\n with pytest.raises(ValueError):\n geocode_batch_dataframe(test_dataframe, query_method=1)\n\n @mock.patch(_GEOCODE)\n def test_output_column_names_are_applied(self, mocked_geocode, test_dataframe):\n\n # Generate dataframe using a mocked output\n mocked_geocode.side_effect = [{'lat': '12.923432', 'lon': '-75.234569'},\n {'lat': '99.999999', 'lon': '-88.888888'},\n {'lat': '-2.202022', 'lon': '0.000000'}\n ]\n\n # Expected outputs\n expected_dataframe = pd.DataFrame({'index': [0, 1, 2],\n 'city': ['London', 'Sheffield', 'Brussels'],\n 'country': ['UK', 'United Kingdom', 'Belgium'],\n 'lat': [12.923432, 99.999999, -2.202022],\n 'lon': [-75.234569, -88.888888, 0.0]\n })\n\n geocoded_dataframe = geocode_batch_dataframe(test_dataframe,\n latitude='lat',\n longitude='lon')\n\n # Check expected behaviours\n assert_frame_equal(geocoded_dataframe, expected_dataframe,\n check_like=True, check_dtype=False)\n\n\nclass TestCountryIsoCode():\n @mock.patch(PYCOUNTRY)\n def test_lookup_via_name(self, mocked_pycountry):\n mocked_pycountry.return_value = 'country_object'\n expected_calls = [mock.call(name='United Kingdom')]\n\n assert country_iso_code('United Kingdom') == 'country_object'\n assert mocked_pycountry.mock_calls == expected_calls\n assert mocked_pycountry.call_count == 1\n country_iso_code.cache_clear()\n\n @mock.patch(PYCOUNTRY)\n def test_lookup_via_common_name(self, mocked_pycountry):\n mocked_pycountry.side_effect = [KeyError(), 'country_object']\n expected_calls = [mock.call(name='United Kingdom'),\n mock.call(common_name='United Kingdom')\n ]\n\n assert country_iso_code('United Kingdom') == 'country_object'\n assert mocked_pycountry.mock_calls == expected_calls\n assert mocked_pycountry.call_count == 2\n country_iso_code.cache_clear()\n\n @mock.patch(PYCOUNTRY)\n def test_lookup_via_official_name(self, mocked_pycountry):\n mocked_pycountry.side_effect = [KeyError(), KeyError(), 'country_object']\n expected_calls = [mock.call(name='United Kingdom'),\n mock.call(common_name='United Kingdom'),\n mock.call(official_name='United Kingdom')\n ]\n\n assert country_iso_code('United Kingdom') == 'country_object'\n assert mocked_pycountry.mock_calls == expected_calls\n assert mocked_pycountry.call_count == 3\n country_iso_code.cache_clear()\n\n @mock.patch(PYCOUNTRY)\n def test_invalid_lookup_raises_keyerror(self, mocked_pycountry):\n mocked_pycountry.side_effect = [KeyError(), KeyError(), KeyError()]*2\n\n with pytest.raises(KeyError) as e:\n country_iso_code('Fake Country')\n assert 'Fake Country not found' in str(e.value)\n country_iso_code.cache_clear()\n\n @mock.patch(PYCOUNTRY)\n def test_title_case_is_applied(self, mocked_pycountry):\n expected_calls = []\n names = ['united kingdom', 'UNITED KINGDOM',\n 'United kingdom']\n mocked_pycountry.side_effect = [KeyError(), KeyError(), KeyError(), 'blah'] * len(names)\n for name in names:\n country_iso_code(name) # Find the iso codes\n raw_call = mock.call(name=name)\n common_call = mock.call(common_name=name)\n official_call = mock.call(official_name=name)\n title_call = mock.call(name='United Kingdom')\n expected_calls.append(raw_call) # The initial call\n expected_calls.append(common_call) # Tries common name call\n expected_calls.append(official_call) # Tries official name\n expected_calls.append(title_call) # The title case call\n assert mocked_pycountry.mock_calls == expected_calls\n country_iso_code.cache_clear()\n\n\nclass TestCountryIsoCodeDataframe():\n @staticmethod\n def _mocked_response(alpha_2, alpha_3, numeric, continent):\n '''Builds a mocked response for the patched country_iso_code function.'''\n response = mock.Mock()\n response.alpha_2 = alpha_2\n response.alpha_3 = alpha_3\n response.numeric = numeric\n response.continent = continent\n return response\n\n @mock.patch(COUNTRY_ISO_CODE)\n def test_valid_countries_coded(self, mocked_country_iso_code):\n test_df = pd.DataFrame({'index': [0, 1, 2],\n 'country': ['United Kingdom', 'Belgium', 'United States']\n })\n mocked_response_uk = self._mocked_response('GB', 'GBR', '123', 'EU')\n mocked_response_be = self._mocked_response('BE', 'BEL', '875', 'EU')\n mocked_response_us = self._mocked_response('US', 'USA', '014', 'NA')\n mocked_country_iso_code.side_effect = [mocked_response_uk,\n mocked_response_be,\n mocked_response_us\n ]\n expected_dataframe = pd.DataFrame(\n {'index': [0, 1, 2],\n 'country': ['United Kingdom', 'Belgium', 'United States'],\n 'country_alpha_2': ['GB', 'BE', 'US'],\n 'country_alpha_3': ['GBR', 'BEL', 'USA'],\n 'country_numeric': ['123', '875', '014'],\n 'continent': ['EU', 'EU', 'NA']\n })\n coded_df = country_iso_code_dataframe(test_df)\n assert coded_df.to_dict(orient=\"records\") == expected_dataframe.to_dict(orient=\"records\")\n\n @mock.patch(COUNTRY_ISO_CODE)\n def test_invalid_countries_data_is_none(self, mocked_country_iso_code):\n test_df = pd.DataFrame({'index': [0, 1, 2],\n 'country': ['United Kingdom', 'Belgium', 'United States']\n })\n mocked_country_iso_code.side_effect = KeyError\n expected_dataframe = pd.DataFrame(\n {'index': [0, 1, 2],\n 'country': ['United Kingdom', 'Belgium', 'United States'],\n 'country_alpha_2': [None, None, None],\n 'country_alpha_3': [None, None, None],\n 'country_numeric': [None, None, None],\n 'continent': [None, None, None]\n })\n coded_df = country_iso_code_dataframe(test_df)\n assert coded_df.to_dict(orient=\"records\") == expected_dataframe.to_dict(orient=\"records\")\n\n\nclass TestCountryIsoCodeToName():\n def test_valid_iso_code_returns_name(self):\n assert country_iso_code_to_name('ITA') == 'Italy'\n assert country_iso_code_to_name('DEU') == 'Germany'\n assert country_iso_code_to_name('GBR') == 'United Kingdom'\n\n def test_invalid_iso_code_returns_none(self):\n assert country_iso_code_to_name('FOO') is None\n assert country_iso_code_to_name('ABC') is None\n assert country_iso_code_to_name('ZZZ') is None\n\n\ndef test_generate_composite_key():\n assert generate_composite_key('London', 'United Kingdom') == 'london_united-kingdom'\n assert generate_composite_key('Paris', 'France') == 'paris_france'\n assert generate_composite_key('Name-with hyphen', 'COUNTRY') == 'name-with-hyphen_country'\n\n\ndef test_generate_composite_key_raises_error_with_invalid_input():\n with pytest.raises(ValueError):\n generate_composite_key(None, 'UK')\n\n with pytest.raises(ValueError):\n generate_composite_key('city_only')\n\n with pytest.raises(ValueError):\n generate_composite_key(1, 2)\n\n\ndef test_get_continent_lookup():\n continents = get_continent_lookup()\n assert None in continents\n assert '' in continents\n assert continents['NA'] == 'North America'\n assert len(continents) == 9 # 2 nulls + 7 continents\n\ndef test_get_country_region_lookup():\n countries = get_country_region_lookup()\n assert len(countries) > 100\n assert len(countries) < 1000\n assert all(len(k) == 2 for k in countries.keys())\n assert all(type(v) is tuple for v in countries.values())\n assert all(len(v) == 2 for v in countries.values())\n all_regions = {v[1] for v in countries.values()}\n assert len(all_regions) == 18\n\n\ndef test_country_continent_lookup():\n lookup = get_country_continent_lookup()\n non_nulls = {k: v for k, v in lookup.items()\n if k is not None and k != ''}\n # All iso2, so length == 2\n assert all(len(k) == 2 for k in non_nulls.items())\n assert all(len(v) == 2 for v in non_nulls.values())\n # Either strings or Nones\n country_types = set(type(v) for v in lookup.values())\n assert country_types == {str, type(None)}\n # Right ball-park of country and continent numbers\n assert len(non_nulls) > 100 # num countries\n assert len(non_nulls) < 1000 # num countries\n assert len(set(non_nulls.values())) == 7 # num continents\n", "\"\"\"\nCollect worldbank\n=================\n\nCollect worldbank sociodemographic data by country.\n\"\"\"\n\nimport requests\nfrom retrying import retry\nimport json\nfrom collections import defaultdict\nimport re\nimport math\nimport pandas as pd\n\nWORLDBANK_ENDPOINT = \"http://api.worldbank.org/v2/{}\"\nDEAD_RESPONSE = (None, None) # tuple to match the default python return type\n\n\ndef worldbank_request(suffix, page, per_page=10000, data_key_path=None):\n \"\"\"Hit the worldbank API and extract metadata and data from the response.\n\n Args:\n suffix (str): Suffix to append to :obj:`WORLDBANK_ENDPOINT`.\n page (int): Pagination number in API request.\n per_page (int): Number of results to return per request.\n data_key_path (list): List specifying json path to data object.\n Returns:\n metadata, data (dict, list): Metadata and data from API response.\n \"\"\"\n response = _worldbank_request(suffix=suffix, page=page, per_page=per_page)\n metadata, data = data_from_response(response=response,\n data_key_path=data_key_path)\n return metadata, data\n\n\n@retry(stop_max_attempt_number=3, wait_fixed=2000)\ndef _worldbank_request(suffix, page, per_page):\n \"\"\"Hit the worldbank API and return the response.\n\n Args:\n suffix (str): Suffix to append to :obj:`WORLDBANK_ENDPOINT`.\n page (int): Pagination number in API request.\n per_page (int): Number of results to return per request.\n Returns:\n response (:obj:`requests.Response`)\n \"\"\"\n # Hit the API\n r = requests.get(WORLDBANK_ENDPOINT.format(suffix),\n params=dict(per_page=per_page, format=\"json\", page=page))\n\n # There are some non-404 status codes which indicate invalid API request\n if r.status_code == 400:\n return DEAD_RESPONSE\n r.raise_for_status()\n\n # There are even some 200 status codes which indicate invalid API request\n # purely by returning non-json data\n response = DEAD_RESPONSE\n try:\n response = r.json()\n except json.JSONDecodeError:\n pass\n finally:\n return response\n\n\ndef data_from_response(response, data_key_path=None):\n \"\"\"Split up the response from the worldbank API.\n\n Args:\n response (tuple): Response from worldbank API, expected to be a tuple of two json items.\n data_key_path (list): List specifying json path to data object.\n Returns:\n metadata, data (dict, list): Metadata and data from API response.\n \"\"\"\n # If the data is stored ({metadata}, [datarows])\n if data_key_path is None or response == DEAD_RESPONSE:\n metadata, datarows = response\n # Otherwise if the data is stored as {metadata, path:{[to:data]}}\n # (or similar)\n else:\n metadata = response\n datarows = response.copy()\n for key in data_key_path:\n datarows = datarows[key]\n if key != data_key_path[-1] and type(datarows) is list:\n datarows = datarows[0]\n return metadata, datarows\n\n\ndef calculate_number_of_api_pages(suffix, per_page=10000, data_key_path=None):\n \"\"\"Calculate the number of API scrolls required to paginate through this\n request.\n\n Args:\n suffix (str): Suffix to append to :obj:`WORLDBANK_ENDPOINT`.\n per_page (int): Number of results to return per request.\n data_key_path (list): List specifying json path to data object.\n Returns:\n n_pages (int): Number of API scrolls required.\n \"\"\"\n # Discover the shape of the data by inspecting the metadata with\n # a tiny request (1 result, 1 page)\n metadata, _ = worldbank_request(suffix=suffix, page=1,\n per_page=1,\n data_key_path=data_key_path)\n\n # If the request was invalid, there are no pages\n if metadata is None:\n return 0\n\n # Calculate the number of pages required\n total = int(metadata[\"total\"])\n n_pages = math.floor(total / per_page) + int(total % per_page > 0)\n return n_pages\n\n\ndef worldbank_data_interval(suffix, first_page, last_page,\n per_page=10000, data_key_path=None):\n \"\"\"Yield a row of data from worldbank API in a page interval.\n Args:\n suffix (str): Suffix to append to :obj:`WORLDBANK_ENDPOINT`.\n {first, last}_page (int): First (last) page number of the API request.\n per_page (int): Number of results to return per request.\n data_key_path (list): List specifying json path to data object.\n Yields:\n row (dict): A row of data from the worldbank API.\n \"\"\"\n for page in range(first_page, last_page+1):\n _, datarows = worldbank_request(suffix=suffix, page=page,\n per_page=per_page,\n data_key_path=data_key_path)\n if datarows is None:\n continue\n for row in datarows:\n yield row\n\n\ndef worldbank_data(suffix, per_page=10000, data_key_path=None):\n \"\"\"Yield a row of data from worldbank API in a page interval.\n Args:\n suffix (str): Suffix to append to :obj:`WORLDBANK_ENDPOINT`.\n per_page (int): Number of results to return per request.\n data_key_path (list): List specifying json path to data object.\n Yields:\n row (dict): A row of data from the worldbank API.\n \"\"\"\n n_pages = calculate_number_of_api_pages(suffix=suffix,\n per_page=per_page,\n data_key_path=data_key_path)\n return worldbank_data_interval(suffix, first_page=1,\n last_page=n_pages,\n per_page=per_page,\n data_key_path=data_key_path)\n\n\ndef get_worldbank_resource(resource):\n \"\"\"Extract and flatten all data for one worldbank resource.\n\n Args:\n resource (str): One of \"countries\", \"series\" or \"source\"\n Returns:\n collection (list): A list of resource data.\n \"\"\"\n collection = []\n for row in worldbank_data(resource):\n # Flatten out any data stored by a key named \"value\"\n data = {}\n for k, v in row.items():\n if type(v) is dict:\n v = v[\"value\"]\n data[k] = v\n collection.append(data)\n return collection\n\n\ndef get_variables_by_code(codes):\n \"\"\"Discover all dataset locations for each variable id, by variable code.\n Note: one variable may exist in many datasets, which is handy in the case\n of missing data.\n\n Args:\n codes (list): The codes of all variables to be discovered.\n Returns:\n variables (dict): Mapping of variable id --> dataset names.\n \"\"\"\n key_path = [\"source\", \"concept\", \"variable\"]\n\n # Mapping variable id --> dataset names\n variables = defaultdict(list)\n sources = get_worldbank_resource(\"source\")\n for source in sources:\n # Extract variables in this \"source\" (dataset)\n suffix = f\"sources/{source['id']}/series/data\"\n data = worldbank_data(suffix, data_key_path=key_path)\n # Filter out variables that we don't want\n filtered_data = filter(lambda row: (row['id'] in codes), data)\n # Assign remaining datasets to this variable\n for row in filtered_data:\n variables[row['id']].append(source['id'])\n return variables\n\n\ndef unpack_quantity(row, concept, value):\n \"\"\"Unpack row like {\"variable\": [{\"concept\":<concept>, <value>:_i_want_this_}]}\n\n Args:\n row (dict): Row of Worldbank API data.\n concept (str): The name of the dataset containing the variable.\n value (str): The name of the variable to unpack.\n Returns:\n A value.\n \"\"\"\n for quantity in row['variable']:\n if quantity['concept'] == concept:\n return quantity[value]\n raise NameError(f\"No item found in {row['variable']} with \"\n f\"concept = {concept}\")\n\n\ndef unpack_data(row):\n \"\"\"Unpack an entire row of Worldbank API data.\n\n Args:\n row (dict): Row of Worldbank API data.\n Returns:\n country, variable, time, value\n \"\"\"\n country = unpack_quantity(row, 'Country', 'id')\n #variable = unpack_quantity(row, 'Series', 'value')\n time = unpack_quantity(row, 'Time', 'value')\n value = row['value']\n return country, time, value\n\n\ndef get_country_data(variables, aliases, time=\"all\"):\n \"\"\"Extract data for specified variables for all available\n countries, in a specified year.\n\n Args:\n variables (dict): Mapping of variable --> dataset ids.\n aliases (dict): Mapping of dirty -> clean variable name.\n time (str): String to identify time period to request.\n Returns:\n country_data (dict): Mapping of country --> variable name --> value\n \"\"\"\n # Iterate through datasets\n country_data = defaultdict(dict) # lambda: defaultdict(list))\n kwargs_list = get_country_data_kwargs(variables=variables,\n aliases=aliases,\n time=time)\n for kwargs in kwargs_list:\n _country_data = country_data_single_request(**kwargs)\n for country, data in _country_data.items():\n for var_name, data_row in data.items():\n country_data[country][var_name] = data_row\n return country_data\n\n\ndef get_country_data_kwargs(variables, aliases, time=\"all\", per_page=10000, max_pages=None):\n \"\"\"Generate every set of kwargs required to make single requests.\n Designed to be used with :obj:`country_data_single_request` in order\n to be batched.\n\n Args:\n variables (dict): Mapping of variable --> dataset ids.\n aliases (dict): Mapping of variable name aliases, to ensure\n consistent variable naming between data collections.\n per_page (int): Number of results to return per request.\n Returns:\n kwargs_list (list): kwargs list for :obj:`country_data_single_request`.\n \"\"\"\n # Iterate through datasets\n kwargs_list = []\n key_path = [\"source\", \"data\"]\n for series, sources in variables.items():\n # The name of a given variable varies subtlely across multiple\n # datasets, so we extract the variable name the first time for\n # consistency across datasets.\n alias = aliases[series]\n for source in sources:\n suffix = (f\"sources/{source}/country/all/\"\n f\"series/{series}/time/{time}/data\")\n n_pages = calculate_number_of_api_pages(suffix=suffix,\n per_page=per_page,\n data_key_path=key_path)\n for page in range(1, n_pages+1):\n if max_pages is not None and page > max_pages:\n break\n parameters = dict(alias=alias,\n suffix=suffix, first_page=page,\n last_page=page, per_page=per_page,\n data_key_path=key_path)\n kwargs_list.append(parameters)\n return kwargs_list\n\n\ndef country_data_single_request(alias, **kwargs):\n \"\"\"Extract data for all countries using kwargs generated by\n :obj:`get_country_data_kwargs`.\n\n Args:\n kwargs (dict): An item returned by :obj:`get_country_data_kwargs`.\n Returns:\n country_data (dict): Mapping of country --> variable name --> value\n \"\"\"\n country_data = defaultdict(lambda: defaultdict(list))\n done_pkeys = set()\n data = worldbank_data_interval(**kwargs)\n for country, time, value in map(unpack_data, data):\n if value is None: # Missing data for this country\n continue\n pkey = (country, time)\n if pkey in done_pkeys: # Already done this country\n continue\n done_pkeys.add(pkey)\n new_row = {\"value\": value, \"time\": time}\n country_data[country][alias].append(new_row)\n return country_data\n\n\n# def flatten_country_data(country_data, country_metadata):\n# \"\"\"Merge and flatten country data and metadata together.\n\n# Args:\n# country_data (dict): Mapping of country --> variable name --> value\n# country_metadata (list): List of country metadata.\n# Returns:\n# flat_country_data (list): Flattened country data and metadata.\n# \"\"\"\n# flat_country_data = [dict(**country_data[metadata['id']], **metadata)\n# for metadata in country_metadata\n# if metadata['id'] in country_data]\n# return flat_country_data\n\n\ndef discover_variable_name(series):\n \"\"\"Discover variable names from each series [short hand code].\n\n Args:\n series (str): The short hand code for the variable name,\n according to Worldbank API.\n Returns:\n alias (str): The variable name for the given series.\n \"\"\"\n _, data = worldbank_request(f\"en/indicator/{series}\", page=1)\n alias = data[0][\"name\"]\n return alias\n\n\ndef clean_variable_name(var_name):\n \"\"\"Clean a single variable name ready for DB storage.\n\n Args:\n var_name (str): Variable name to be cleaned\n Returns:\n new_var_name (str): A MySQL compliant variable name.\n \"\"\"\n\n # Lower, replace '%', remove non-alphanums and use '_'\n new_var_name = var_name.lower().replace(\"%\", \"pc\")\n new_var_name = re.sub('[^0-9a-zA-Z]+', ' ', new_var_name)\n new_var_name = new_var_name.lstrip().rstrip().replace(\" \", \"_\")\n # Recursively shorten from middle character until less than 64 chars long\n # (this is the default MySQL limit)\n # Middle character has been chosen to allow some readability.\n while len(new_var_name) > 64:\n # Find the longest term\n longest_term = \"\"\n for term in new_var_name.split(\"_\"):\n if len(term) <= len(longest_term):\n continue\n longest_term = term\n # Remove the middle character from the longest term\n middle = len(longest_term) - 1\n new_term = longest_term[:middle] + longest_term[middle+1:]\n new_var_name = new_var_name.replace(longest_term, new_term)\n return new_var_name\n\n\n\ndef clean_variable_names(flat_country_data):\n \"\"\"Clean variable names ready for DB storage.\n\n Args:\n flat_country_data (list): Flattened country data.\n Returns:\n out_data (list): Same as input data, with MySQL compliant field names.\n \"\"\"\n out_data = []\n for row in flat_country_data:\n new_row = {}\n for key, v in row.items():\n # Only clean names containing spaces\n if \" \" not in key:\n new_row[key] = v\n continue\n new_key = clean_variable_name(key)\n new_row[new_key] = v\n out_data.append(new_row)\n return out_data\n\n\ndef is_bad_quarter(x, bad_quarters):\n return any(q in x for q in bad_quarters)\n\n\ndef flatten_country_data(country_data, country_metadata,\n bad_quarters=(\"Q1\", \"Q3\", \"Q4\")):\n # Discover the year from the time variable.\n # Expected to be in the formats \"XXXX\" and \"XXXX QX\"\n country_metadata = {metadata[\"id\"]: metadata\n for metadata in country_metadata}\n fairly_flat_data = []\n for iso3, _ in country_metadata.items():\n for variable, data in country_data[iso3].items():\n for row in data:\n year = re.findall(r'(\\d{4})', row[\"time\"])[0]\n flatter_row = dict(country=iso3, variable=variable,\n year=year, **row)\n fairly_flat_data.append(flatter_row)\n\n # Group by country and year and remove quarters we don't want.\n very_flat_data = []\n df = pd.DataFrame(fairly_flat_data)\n for (country, year), _df in df.groupby([\"country\", \"year\"]):\n # Identify quarters we don't want\n condition = _df[\"time\"].apply(is_bad_quarter,\n bad_quarters=bad_quarters)\n if (~condition).sum() == 0:\n continue\n row = {r[\"variable\"]: r[\"value\"]\n for _, r in _df.loc[~condition].iterrows()}\n row = dict(year=year, **row, **country_metadata[country])\n very_flat_data.append(row)\n\n return very_flat_data\n\n\nif __name__ == \"__main__\":\n\n # DO ALL OF THE FOLLOWING IN A SINGLE LUIGI TASK\n variables = get_variables_by_code([\"SP.RUR.TOTL.ZS\", \"SP.URB.TOTL.IN.ZS\",\n \"SP.POP.DPND\", \"SP.POP.TOTL\",\n \"SP.DYN.LE00.IN\", \"SP.DYN.IMRT.IN\",\n \"BAR.NOED.25UP.ZS\",\n \"BAR.TER.CMPT.25UP.ZS\",\n \"NYGDPMKTPSAKD\",\n \"SI.POV.NAHC\", \"SI.POV.GINI\"])\n aliases = {series: discover_variable_name(series)\n for series, sources in variables.items()}\n\n # (EXCEPT THIS ONE)\n # country_data = get_country_data(variables, aliases)\n\n # ALSO DO THIS\n kwargs_list = get_country_data_kwargs(variables=variables,\n aliases=aliases,\n max_pages=2) # <== Test mode\n\n # THEN BATCH, FOR CHUNKS OF KWARGS\n country_data = defaultdict(dict)\n for kwargs in kwargs_list:\n _country_data = country_data_single_request(**kwargs)\n for country, data in _country_data.items():\n for var_name, data_row in data.items():\n country_data[country][var_name] = data_row\n\n\n # THEN A FINAL TASK GETS THE ABOVE RESULTS BY COUNTRY\n # AND WRITES TO DATABASE\n country_metadata = get_worldbank_resource(\"countries\")\n flat_country_data = flatten_country_data(country_data, country_metadata)\n cleaned_data = clean_variable_names(flat_country_data)\n\n # STEP AFTER PUTS THESE IN ES\n" ]
[ [ "pandas.testing.assert_frame_equal", "pandas.DataFrame" ], [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "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": [] } ]
delenamalan/covid19za
[ "414a7e0771ebb4b054809f20bff6c4efc0c24ff6" ]
[ "scripts/gp_pdf_extractor.py" ]
[ "import pdfplumber\nimport re\nimport pandas as pd\nfrom datetime import datetime\nimport sys\n\n# AUTHOR: Simon Rosen\n\n# -----------------------------------\n# DEPENDENCIES\n# This module requires 'pdfplumber'\n#\n# Install: pip install pdfplumber\n# -----------------------------------\n\n\ndef extract_data(file_path):\n pdfp_obj = pdfplumber.open(file_path)\n\n # Helper functions\n # text - string you are finding substring in\n def get_string_between_2_strings(text, string1, string2):\n # print(\"text: {}\\n string1: {}, string2:{}\".format(\"text\", string1, string2))\n try:\n regex_str = string1 + '(.+?)' + string2\n # print('regex_str: {}'.format(regex_str))\n # all_found = [x.group() for x in re.finditer(regex_str, text)]\n all_found = re.search(regex_str, text, re.DOTALL).group(1)\n # print(all_found)\n except AttributeError:\n # no text found between two substrings\n # print('Not found')\n all_found = [] # apply your error handling\n return all_found\n\n # GP data contained in paragraph under following heading\n # GAUTENG CONFIRMED COVID-19 CASES DISTRICT BREAKDOWN\n # GP cases, recoveries, deaths, contacts traced, people de-isolated & hospitalisations\n def get_gp_breakdown_data():\n district_pg =0\n first_page_txt = pdfp_obj.pages[0].extract_text()\n # GAUTENG CONFIRMED COVID-19 CASES DISTRICT BREAKDOWN\n heading_txt_1 = \"GAUTENG CONFIRMED COVID-19 CASES DISTRICT BREAKDOWN\"\n heading_txt_2 = \"BREAKDOWN PER DISTRICT\"\n breakdown_txt = get_string_between_2_strings(first_page_txt, heading_txt_1, heading_txt_2)\n if len(breakdown_txt)==0:\n breakdown_txt = get_string_between_2_strings(pdfp_obj.pages[1].extract_text(), heading_txt_1, heading_txt_2)\n district_pg=1\n if len(breakdown_txt)==0:\n breakdown_txt = get_string_between_2_strings(pdfp_obj.pages[1].extract_text(), \"^\", heading_txt_2)\n district_pg=1\n \n \n str_list = list(filter(lambda x: False if x == ' ' else True, breakdown_txt.splitlines()))\n str_body = \"\".join(str_list)\n sentences = str_body.split('.')\n\n def find_date(text):\n return re.search(r'(\\d{2}|\\d{1}) [a-zA-Z]* \\d{4}', text).group(0)\n\n def get_nums(text, exclude_texts=['COVID-19']):\n for exclude_text in exclude_texts:\n text = text.replace(exclude_text, '')\n num_tuples = re.findall(r'(\\d{3}|\\d{2}|\\d{1})( \\d{3}|\\d{2}|\\d{1})*', text)\n num_list = [int(x[0] + x[1].replace(' ', '')) for x in num_tuples]\n return num_list\n\n date_txt = get_string_between_2_strings(pdfp_obj.pages[0].extract_text(), heading_txt_1, \"$\")\n sentences = \"\".join(date_txt).split(\".\")\n\n\n _gp_covid_stats = {\"date\": find_date(date_txt)} \n\n\n # First Sentence\n tmp_dict = dict(zip(['cases', 'recoveries', 'deaths'], get_nums(sentences[0])[2:]))\n _gp_covid_stats.update(tmp_dict)\n\n # Second Sentence\n tmp_dict = dict(zip(['traced', 'de_isolated'], get_nums(sentences[1])[:2]))\n _gp_covid_stats.update(tmp_dict)\n\n # Third Sentence\n tmp_dict = dict(zip(['hospitalised'], get_nums(sentences[2])))\n _gp_covid_stats.update(tmp_dict)\n\n return district_pg, _gp_covid_stats\n\n district_pg, gp_covid_stats = get_gp_breakdown_data()\n\n # DISTRICT BREAKDOWN\n def get_district_data():\n district_table_list = pdfp_obj.pages[district_pg].extract_tables()[0]\n print(type(district_table_list))\n dl = []\n for i, row in enumerate(district_table_list):\n print(i,row)\n dl.append(list(filter(lambda x: x != None and len(x) !=0, row)))\n dl[-2]=dl[-2]+[0,0,0]\n print(dl)\n all_list = [[x[i] for x in dl] for i in range(0, len(dl[0]))]\n print(all_list,\"*******\")\n gp_breakdown_dict = {curr_list[0]: curr_list[1:] for curr_list in all_list}\n gp_breakdown_df = pd.DataFrame.from_dict(gp_breakdown_dict)\n print(gp_breakdown_df)\n gp_breakdown_df.fillna(0, inplace=True)\n gp_breakdown_df.set_index(\"DISTRICT\", inplace=True)\n gp_breakdown_df.rename(inplace=True, columns={gp_breakdown_df.columns[0]: \"CASES\",\n gp_breakdown_df.columns[1]: \"NEW CASES\"})\n for i in range(0, 4):\n gp_breakdown_df.iloc[:, i] = gp_breakdown_df.iloc[:, i].apply(lambda x: x if type(x)==int else x.replace(' ', ''))\n return gp_breakdown_df\n\n gp_district_df = get_district_data()\n\n # ---------------\n # SUB-DISTRICTS\n # ---------------\n\n def get_extracted_raw_list(page_no):\n currPage = pdfp_obj.pages[page_no]\n bounding_box = (300, 0, currPage.width, currPage.height)\n cropped_page = currPage.crop(bounding_box)\n # table_settings = {\"vertical_strategy\": \"text\"}\n table_settings = {\"snap_tolerance\": 10, \"join_tolerance\": 15}\n extracted_raw_list = cropped_page.extract_tables(table_settings)[0]\n return extracted_raw_list\n\n def get_sub_districts_data(raw_list):\n sub_districts_list = []\n curr_sub_district = []\n prev_sub_district = []\n for i in range(1, len(raw_list)):\n curr_list = raw_list[i]\n if curr_sub_district == [] or not (curr_list[0] == None or curr_list[0] == ''):\n # print(prev_sub_district)\n if prev_sub_district != []:\n sub_districts_list.append(curr_sub_district)\n\n curr_sub_district = curr_list\n prev_sub_district = curr_sub_district\n # print(curr_sub_district)\n\n if (curr_sub_district[1] == '' and curr_list[1] != '' and curr_list[1] != None):\n curr_sub_district[1] = curr_list[1]\n\n if (curr_sub_district[2] == '' and curr_list[2] != '' and curr_list[2] != None):\n curr_sub_district[2] = curr_list[2]\n\n if (i == len(raw_list) - 1):\n sub_districts_list.append(curr_sub_district)\n\n # Check if first item of list is valid e.g. total and/or recoveries has values\n prev_sub_district = sub_districts_list[0]\n if (prev_sub_district[1] == '' or prev_sub_district[1] == None) and (prev_sub_district[2] == '' or \\\n prev_sub_district[2] == None):\n sub_districts_list.pop(0)\n return sub_districts_list\n\n def get_table_list(page_no):\n currPage = pdfp_obj.pages[page_no]\n bounding_box = (300, 0, currPage.width, currPage.height)\n cropped_page = currPage.crop(bounding_box)\n # table_settings = {\"vertical_strategy\": \"text\"}\n table_settings = {\"snap_tolerance\": 10, \"join_tolerance\": 15}\n extracted_raw_list = cropped_page.extract_tables(table_settings)[0]\n return extracted_raw_list\n\n def get_all_sub_districts(page_start, page_end):\n all_sub_districts = []\n for i in range(page_start, page_end + 1):\n all_sub_districts.extend(get_sub_districts_data(get_table_list(i)))\n\n def remove_spaces(str_no):\n if type(str_no)==str:\n return str_no.replace(\" \", \"\")\n else:\n return str_no\n\n all_sub_districts = [[x[0], remove_spaces(x[1]), remove_spaces(x[2])] for x in all_sub_districts]\n\n return all_sub_districts\n\n all_sub_dists = get_all_sub_districts(district_pg+1, district_pg+4)\n\n pdfp_obj.close()\n\n def get_district_map():\n # Johannesburg\n jhb_dict = dict(zip(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'Unallocated'],\n [[x[1], x[2]] for x in all_sub_dists[0:8]]))\n # Tshwane\n tsh_keys = list(range(1, 8))\n tsh_keys.append('Unallocated')\n tsh_dict = dict(zip(tsh_keys, [[x[1], x[2]] for x in all_sub_dists[8:16]]))\n\n # Ekurhuleni\n eku_keys = \"e1 e2 n1 n2 s1 s2 Unallocated\".split(\" \")\n eku_dict = dict(zip(eku_keys, [[x[1], x[2]] for x in all_sub_dists[16:23]]))\n\n # Sedibeng\n sed_keys = \"Lesedi Emfuleni Midvaal Unallocated\".split(\" \")\n sed_dict = dict(zip(sed_keys, [[x[1], x[2]] for x in all_sub_dists[23:27]]))\n\n # West Rand\n wr_keys = \"Mogale Rand_West Merafong Unallocated\".split(\" \")\n wr_dict = dict(zip(wr_keys, [[x[1], x[2]] for x in all_sub_dists[27:31]]))\n\n # All Districts\n district_map = {\n 'Johannesburg': jhb_dict,\n 'Tshwane': tsh_dict,\n 'Ekurhuleni': eku_dict,\n 'Sedibeng': sed_dict,\n 'West Rand': wr_dict\n }\n return district_map\n\n district_map = get_district_map()\n\n # DATE\n curr_date = datetime.strptime(gp_covid_stats['date'], '%d %B %Y')\n date_formatted = datetime.strftime(curr_date, '%d-%m-%Y')\n date_yyyymmdd = datetime.strftime(curr_date, '%Y%m%d')\n # print(gp_covid_stats['date'], date_formatted, date_yyyymmdd)\n\n ##############################\n # OUT LIST #\n # DETERMINES ORDER OF OUTPUT #\n ##############################\n\n # List later gets converted to formatted string\n\n jhb_districts = [x for x in 'ABCDEFG']+['Unallocated']\n tsh_districts = [x for x in range(1,8)]+['Unallocated']\n wr_districts=['Mogale',\"Rand_West\",\"Merafong\",\"Unallocated\"]\n \n out_list = [\n # Date\n date_yyyymmdd, date_formatted,\n\n # Gauteng Data\n gp_covid_stats['cases'], 'Check', 'Check',\n gp_covid_stats['recoveries'], gp_covid_stats['deaths'], 'Check','Check',\n gp_covid_stats['hospitalised'],\n\n # DISTRICT TOTALS DATA\n # ----------------------\n\n # Johannesburg\n gp_district_df.loc['Johannesburg']['CASES'],\n gp_district_df.loc['Ekurhuleni']['CASES'],\n gp_district_df.loc['Tshwane']['CASES'],\n gp_district_df.loc['Sedibeng']['CASES'],\n gp_district_df.loc['West Rand']['CASES'],\n gp_district_df.loc['Unallocated']['CASES'],\n ' Check',\n gp_district_df.loc['Johannesburg']['DEATHS'],\n gp_district_df.loc['Ekurhuleni']['DEATHS'],\n gp_district_df.loc['Tshwane']['DEATHS'],\n gp_district_df.loc['Sedibeng']['DEATHS'],\n gp_district_df.loc['West Rand']['DEATHS'],\n \n gp_district_df.loc['Johannesburg']['RECOVERIES'],\n gp_district_df.loc['Ekurhuleni']['RECOVERIES'],\n gp_district_df.loc['Tshwane']['RECOVERIES'],\n gp_district_df.loc['Sedibeng']['RECOVERIES'],\n gp_district_df.loc['West Rand']['RECOVERIES'], ' Check', ' Check'] + \\\n [district_map['Johannesburg'][x][0] for x in jhb_districts]+\\\n ['Check']+\\\n [district_map['Johannesburg'][x][1] for x in jhb_districts]+\\\n ['Check']+\\\n [district_map['Tshwane'][x][0] for x in tsh_districts]+\\\n ['Check']+\\\n [district_map['Tshwane'][x][1] for x in tsh_districts]+\\\n ['Check']+\\\n [district_map['Ekurhuleni'][x][0] for x in ['e1','e2','n1','n2','s1','s2','Unallocated']]+\\\n ['Check']+\\\n [district_map['Ekurhuleni'][x][1] for x in ['e1','e2','n1','n2','s1','s2','Unallocated']]+\\\n ['Check']+\\\n [district_map['Sedibeng'][x][0] for x in ['Lesedi','Emfuleni','Midvaal','Unallocated']]+\\\n ['Check']+\\\n [district_map['Sedibeng'][x][1] for x in ['Lesedi','Emfuleni','Midvaal','Unallocated']]+\\\n ['Check']+\\\n [district_map['West Rand'][x][0] for x in wr_districts]+\\\n [district_map['West Rand'][x][1] for x in wr_districts]+\\\n ['Check']\n\n\n def list_to_formatted(in_list, delimiter='\\t'):\n return delimiter.join(map(str, in_list))\n\n out_str = list_to_formatted(out_list)\n # return district_map\n return out_str\n\n\nif __name__ == \"__main__\":\n print(extract_data(sys.argv[1]))\n" ]
[ [ "pandas.DataFrame.from_dict" ] ]
[ { "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": [] } ]
ericwang0701/Graphonomy
[ "1942bd41723ec48e5133f932082a49d1c17050ad" ]
[ "exp/inference/inference_dir.py" ]
[ "import socket\nimport timeit\nimport numpy as np\nfrom PIL import Image\nfrom datetime import datetime\nimport os\nimport sys\nfrom collections import OrderedDict\nsys.path.append('./')\n# PyTorch includes\nimport torch\nfrom torch.autograd import Variable\nfrom torchvision import transforms\nimport cv2\n\n\n# Custom includes\nfrom networks import deeplab_xception_transfer, graph\nfrom dataloaders import custom_transforms as tr\n\n#\nimport argparse\nimport torch.nn.functional as F\n\nlabel_colours = [(0,0,0)\n , (128,0,0), (255,0,0), (0,85,0), (170,0,51), (255,85,0), (0,0,85), (0,119,221), (85,85,0), (0,85,85), (85,51,0), (52,86,128), (0,128,0)\n , (0,0,255), (51,170,221), (0,255,255), (85,255,170), (170,255,85), (255,255,0), (255,170,0)]\n\n\ndef flip(x, dim):\n indices = [slice(None)] * x.dim()\n indices[dim] = torch.arange(x.size(dim) - 1, -1, -1,\n dtype=torch.long, device=x.device)\n return x[tuple(indices)]\n\ndef flip_cihp(tail_list):\n '''\n\n :param tail_list: tail_list size is 1 x n_class x h x w\n :return:\n '''\n # tail_list = tail_list[0]\n tail_list_rev = [None] * 20\n for xx in range(14):\n tail_list_rev[xx] = tail_list[xx].unsqueeze(0)\n tail_list_rev[14] = tail_list[15].unsqueeze(0)\n tail_list_rev[15] = tail_list[14].unsqueeze(0)\n tail_list_rev[16] = tail_list[17].unsqueeze(0)\n tail_list_rev[17] = tail_list[16].unsqueeze(0)\n tail_list_rev[18] = tail_list[19].unsqueeze(0)\n tail_list_rev[19] = tail_list[18].unsqueeze(0)\n return torch.cat(tail_list_rev,dim=0)\n\n\ndef decode_labels(mask, num_images=1, num_classes=20):\n \"\"\"Decode batch of segmentation masks.\n\n Args:\n mask: result of inference after taking argmax.\n num_images: number of images to decode from the batch.\n num_classes: number of classes to predict (including background).\n\n Returns:\n A batch with num_images RGB images of the same size as the input.\n \"\"\"\n n, h, w = mask.shape\n assert (n >= num_images), 'Batch size %d should be greater or equal than number of images to save %d.' % (\n n, num_images)\n outputs = np.zeros((num_images, h, w, 3), dtype=np.uint8)\n for i in range(num_images):\n img = Image.new('RGB', (len(mask[i, 0]), len(mask[i])))\n pixels = img.load()\n for j_, j in enumerate(mask[i, :, :]):\n for k_, k in enumerate(j):\n if k < num_classes:\n pixels[k_, j_] = label_colours[k]\n outputs[i] = np.array(img)\n return outputs\n\ndef read_img(img_path):\n _img = Image.open(img_path).convert('RGB') # return is RGB pic\n return _img\n\ndef img_transform(img, transform=None):\n sample = {'image': img, 'label': 0}\n\n sample = transform(sample)\n return sample\n\ndef get_img_paths(imgs_dir):\n img_paths = []\n for dirpath, dirnames, filenames in os.walk(imgs_dir):\n for filename in [f for f in filenames if f.endswith('.png') or f.endswith('.PNG') or f.endswith('.jpg') or f.endswith('.JPG') or f.endswith('.jpeg') or f.endswith('.JPEG')]:\n img_paths.append(os.path.join(dirpath,filename))\n img_paths.sort()\n\n return img_paths\n\ndef inference(net, img_path='', output_path='./', output_name='f', use_gpu=True):\n '''\n\n :param net:\n :param img_path:\n :param output_path:\n :return:\n '''\n # adj\n adj2_ = torch.from_numpy(graph.cihp2pascal_nlp_adj).float()\n adj2_test = adj2_.unsqueeze(0).unsqueeze(0).expand(1, 1, 7, 20).cuda().transpose(2, 3)\n\n adj1_ = Variable(torch.from_numpy(graph.preprocess_adj(graph.pascal_graph)).float())\n adj3_test = adj1_.unsqueeze(0).unsqueeze(0).expand(1, 1, 7, 7).cuda()\n\n cihp_adj = graph.preprocess_adj(graph.cihp_graph)\n adj3_ = Variable(torch.from_numpy(cihp_adj).float())\n adj1_test = adj3_.unsqueeze(0).unsqueeze(0).expand(1, 1, 20, 20).cuda()\n\n # multi-scale\n scale_list = [1, 0.5, 0.75, 1.25, 1.5, 1.75]\n img = read_img(img_path)\n testloader_list = []\n testloader_flip_list = []\n for pv in scale_list:\n composed_transforms_ts = transforms.Compose([\n tr.Scale_only_img(pv),\n tr.Normalize_xception_tf_only_img(),\n tr.ToTensor_only_img()])\n\n composed_transforms_ts_flip = transforms.Compose([\n tr.Scale_only_img(pv),\n tr.HorizontalFlip_only_img(),\n tr.Normalize_xception_tf_only_img(),\n tr.ToTensor_only_img()])\n\n testloader_list.append(img_transform(img, composed_transforms_ts))\n # print(img_transform(img, composed_transforms_ts))\n testloader_flip_list.append(img_transform(img, composed_transforms_ts_flip))\n # print(testloader_list)\n start_time = timeit.default_timer()\n # One testing epoch\n net.eval()\n # 1 0.5 0.75 1.25 1.5 1.75 ; flip:\n\n for iii, sample_batched in enumerate(zip(testloader_list, testloader_flip_list)):\n inputs, labels = sample_batched[0]['image'], sample_batched[0]['label']\n inputs_f, _ = sample_batched[1]['image'], sample_batched[1]['label']\n inputs = inputs.unsqueeze(0)\n inputs_f = inputs_f.unsqueeze(0)\n inputs = torch.cat((inputs, inputs_f), dim=0)\n if iii == 0:\n _, _, h, w = inputs.size()\n # assert inputs.size() == inputs_f.size()\n\n # Forward pass of the mini-batch\n inputs = Variable(inputs, requires_grad=False)\n\n with torch.no_grad():\n if use_gpu >= 0:\n inputs = inputs.cuda()\n # outputs = net.forward(inputs)\n outputs = net.forward(inputs, adj1_test.cuda(), adj3_test.cuda(), adj2_test.cuda())\n outputs = (outputs[0] + flip(flip_cihp(outputs[1]), dim=-1)) / 2\n outputs = outputs.unsqueeze(0)\n\n if iii > 0:\n outputs = F.upsample(outputs, size=(h, w), mode='bilinear', align_corners=True)\n outputs_final = outputs_final + outputs\n else:\n outputs_final = outputs.clone()\n ################ plot pic\n predictions = torch.max(outputs_final, 1)[1]\n results = predictions.cpu().numpy()\n vis_res = decode_labels(results)\n\n parsing_im = Image.fromarray(vis_res[0])\n parsing_im.save(output_path+'/{}.png'.format(output_name))\n \n #we don't need the gray image\n #cv2.imwrite(output_path+'/{}_gray.png'.format(output_name), results[0, :, :])\n\n end_time = timeit.default_timer()\n print('time used for the multi-scale image inference' + ' is :' + str(end_time - start_time))\n\nif __name__ == '__main__':\n '''argparse begin'''\n parser = argparse.ArgumentParser()\n # parser.add_argument('--loadmodel',default=None,type=str)\n parser.add_argument('--loadmodel', default='', type=str)\n parser.add_argument('--imgs_dir', default='', type=str)\n parser.add_argument('--output_dir', default='', type=str)\n parser.add_argument('--use_gpu', default=1, type=int)\n opts = parser.parse_args()\n\n net = deeplab_xception_transfer.deeplab_xception_transfer_projection_savemem(n_classes=20,\n hidden_layers=128,\n source_classes=7, )\n if not opts.loadmodel == '':\n x = torch.load(opts.loadmodel)\n net.load_source_model(x)\n print('load model:', opts.loadmodel)\n else:\n print('no model load !!!!!!!!')\n raise RuntimeError('No model!!!!')\n\n if opts.use_gpu >0 :\n net.cuda()\n use_gpu = True\n else:\n use_gpu = False\n raise RuntimeError('must use the gpu!!!!')\n\n img_paths = get_img_paths(opts.imgs_dir)\n for idx, path in enumerate(img_paths):\n filename = os.path.splitext(os.path.basename(path))[0]\n output_name = filename +\"_seg\"\n inference(net=net, img_path=path, output_path=opts.output_dir , output_name=output_name, use_gpu=use_gpu)\n\n" ]
[ [ "torch.nn.functional.upsample", "torch.max", "torch.cat", "torch.load", "torch.from_numpy", "torch.no_grad", "numpy.array", "numpy.zeros", "torch.autograd.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
sdpython/jupytalk
[ "34abdf128de24becb21a9f08f243c3a74dadbfd9" ]
[ "_unittests/ut_talk_examples/test_pydata2016_animation.py" ]
[ "\"\"\"\n@brief test log(time=20s)\n\"\"\"\n\nimport sys\nimport os\nimport unittest\nfrom pyquickhelper.loghelper import fLOG, run_cmd\nfrom pyquickhelper.pycode import get_temp_folder, fix_tkinter_issues_virtualenv, skipif_appveyor, skipif_travis\nfrom pyquickhelper.pycode import add_missing_development_version\n\n\nclass TestPyData2016Animation(unittest.TestCase):\n\n @skipif_appveyor(\"no ffmpeg installed\")\n @skipif_travis(\"issue with datashader.bokeh_ext, skipping\")\n @skipif_appveyor(\"issue with pyproj\")\n def test_matplotlib_example(self):\n fLOG(\n __file__,\n self._testMethodName,\n OutputPrint=__name__ == \"__main__\")\n\n progs = [\"ffmpeg\"]\n if not sys.platform.startswith(\"win\"):\n progs.append(\"avconv\")\n errs = []\n prog = None\n for prog in progs:\n out, err = run_cmd(prog, wait=True, fLOG=fLOG)\n exps = \"usage:\"\n if (exps not in out and exps not in err) or err is None or len(err) == 0:\n errs.append((prog, err))\n else:\n break\n\n if len(errs) >= len(progs):\n if sys.platform.startswith(\"win\"):\n fLOG(\"download ffmpeg\")\n add_missing_development_version(\n [\"pyensae\"], __file__, hide=True)\n from pyensae.datasource import download_data\n download_data(\"ffmpeg.zip\", website=\"xd\")\n else:\n raise FileNotFoundError(\n \"Unable to find '{1}'.\\nPATH='{0}'\\n--------\\n[OUT]\\n{2}\\n[ERR]\\n{3}\".format(\n os.environ[\"PATH\"], prog, out,\n \"\\n----\\n\".join(\"{0}:\\n{1}\".format(*_) for _ in errs)))\n\n temp = get_temp_folder(__file__, \"temp_example_example\")\n fix_tkinter_issues_virtualenv()\n\n # update a distribution based on new data.\n import numpy as np\n import matplotlib.pyplot as plt\n import scipy.stats as ss\n from matplotlib.animation import FuncAnimation, writers\n\n # To get the list of available writers\n if not writers.is_available(prog):\n writers.register(prog)\n fLOG(writers.list())\n\n class UpdateDist:\n\n def __init__(self, ax, prob=0.5):\n self.success = 0\n self.prob = prob\n self.line, = ax.plot([], [], 'k-')\n self.x = np.linspace(0, 1, 200)\n self.ax = ax\n\n # Set up plot parameters\n self.ax.set_xlim(0, 1)\n self.ax.set_ylim(0, 15)\n self.ax.grid(True)\n\n # This vertical line represents the theoretical value, to\n # which the plotted distribution should converge.\n self.ax.axvline(prob, linestyle='--', color='black')\n\n def init(self):\n self.success = 0\n self.line.set_data([], [])\n return self.line,\n\n def __call__(self, i):\n # This way the plot can continuously run and we just keep\n # watching new realizations of the process\n if i == 0:\n return self.init()\n\n # Choose success based on exceed a threshold with a uniform\n # pick\n if np.random.rand(1,) < self.prob: # pylint: disable=W0143\n self.success += 1\n y = ss.beta.pdf(self.x, self.success + 1,\n (i - self.success) + 1)\n self.line.set_data(self.x, y)\n return self.line,\n\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n ud = UpdateDist(ax, prob=0.7)\n anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init,\n interval=100, blit=True)\n\n try:\n Writer = writers[prog]\n except KeyError as e:\n if prog == \"avconv\":\n from matplotlib.animation import AVConvWriter\n Writer = AVConvWriter\n else:\n raise e\n writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)\n anim.save(os.path.join(temp, 'lines2.mp4'), writer=writer)\n\n plt.close('all')\n fLOG(\"end\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "matplotlib.animation.writers.register", "matplotlib.animation.writers.is_available", "numpy.linspace", "scipy.stats.beta.pdf", "numpy.arange", "numpy.random.rand", "matplotlib.pyplot.close", "matplotlib.animation.writers.list", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mhd53/vgg-from-torch
[ "fbcca53432648a492550fb14d2c42c10230d76f5" ]
[ "vgg/test.py" ]
[ "import argparse\nimport torch\nfrom tqdm import tqdm\nimport vgg.data_loader.data_loaders as module_data\nimport vgg.model.loss as module_loss\nimport vgg.model.metric as module_metric\nimport vgg.model.model as module_arch\nfrom vgg.parse_config import ConfigParser\n\n\ndef main(config):\n logger = config.get_logger('test')\n\n # setup data_loader instances\n data_loader = getattr(module_data, config['data_loader']['type'])(\n config['data_loader']['args']['data_dir'],\n batch_size=512,\n shuffle=False,\n validation_split=0.0,\n training=False,\n num_workers=2\n )\n\n # build model architecture\n model = config.init_obj('arch', module_arch)\n logger.info(model)\n\n # get function handles of loss and metrics\n loss_fn = getattr(module_loss, config['loss'])\n metric_fns = [getattr(module_metric, met) for met in config['metrics']]\n\n logger.info('Loading checkpoint: {} ...'.format(config.resume))\n checkpoint = torch.load(config.resume)\n state_dict = checkpoint['state_dict']\n if config['n_gpu'] > 1:\n model = torch.nn.DataParallel(model)\n model.load_state_dict(state_dict)\n\n # prepare model for testing\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model = model.to(device)\n model.eval()\n\n total_loss = 0.0\n total_metrics = torch.zeros(len(metric_fns))\n\n with torch.no_grad():\n for i, (data, target) in enumerate(tqdm(data_loader)):\n data, target = data.to(device), target.to(device)\n output = model(data)\n\n #\n # save sample images, or do something with output here\n #\n\n # computing loss, metrics on test set\n loss = loss_fn(output, target)\n batch_size = data.shape[0]\n total_loss += loss.item() * batch_size\n for i, metric in enumerate(metric_fns):\n total_metrics[i] += metric(output, target) * batch_size\n\n n_samples = len(data_loader.sampler)\n log = {'loss': total_loss / n_samples}\n log.update({\n met.__name__: total_metrics[i].item() / n_samples for i, met in enumerate(metric_fns)\n })\n logger.info(log)\n\n\nif __name__ == '__main__':\n args = argparse.ArgumentParser(description='PyTorch Template')\n args.add_argument('-c', '--config', default=None, type=str,\n help='config file path (default: None)')\n args.add_argument('-r', '--resume', default=None, type=str,\n help='path to latest checkpoint (default: None)')\n args.add_argument('-d', '--device', default=None, type=str,\n help='indices of GPUs to enable (default: all)')\n\n config = ConfigParser.from_args(args)\n main(config)\n" ]
[ [ "torch.nn.DataParallel", "torch.no_grad", "torch.cuda.is_available", "torch.load" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
lukapecnik/NiaPy
[ "a40ac08a4c06a13019ec5e39cc137461884928b0", "a40ac08a4c06a13019ec5e39cc137461884928b0", "a40ac08a4c06a13019ec5e39cc137461884928b0", "a40ac08a4c06a13019ec5e39cc137461884928b0" ]
[ "docs/source/conf.py", "NiaPy/algorithms/basic/mfo.py", "NiaPy/algorithms/other/sa.py", "NiaPy/tests/test_hde.py" ]
[ "# -*- coding: utf-8 -*-\n#\n# Configuration file for the Sphinx documentation builder.\n#\n# This file does only contain a selection of the most common options. For a\n# full list see the documentation:\n# http://www.sphinx-doc.org/en/stable/config\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath('../../'))\n\nprint(sys.path)\n\n# -- Project information -----------------------------------------------------\n\nproject = u'NiaPy'\ncopyright = u'2018, NiaOrg'\nauthor = u'Grega Vrbančič, Lucija Brezočnik, Uroš Mlakar, Dušan Fister, Iztok Fister Jr., Klemen Berkovič, Jan Popič'\n\n# The short X.Y version\nversion = u''\n# The full version, including alpha/beta/rc tags\nrelease = u'0.0.0.'\n\n\n# -- General configuration ---------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.doctest',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.todo',\n 'sphinx.ext.coverage',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.ifconfig',\n 'sphinx.ext.viewcode',\n 'sphinx.ext.napoleon'\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\n# source_suffix = ['.rst', '.md']\nsource_suffix = '.rst'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = None\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path .\nexclude_patterns = []\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'sphinx_rtd_theme'\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#\n# html_theme_options = {}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# The default sidebars (for documents that don't match any pattern) are\n# defined by theme itself. Builtin themes are using these templates by\n# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',\n# 'searchbox.html']``.\n#\n# html_sidebars = {}\n\n\n# -- Options for HTMLHelp output ---------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'NiaPydoc'\n\n\n# -- Options for LaTeX output ------------------------------------------------\n\nlatex_elements = {\n # The paper size ('letterpaper' or 'a4paper').\n #\n # 'papersize': 'letterpaper',\n\n # The font size ('10pt', '11pt' or '12pt').\n #\n # 'pointsize': '10pt',\n\n # Additional stuff for the LaTeX preamble.\n #\n # 'preamble': '',\n\n # Latex figure (float) alignment\n #\n # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n (master_doc, 'NiaPy.tex', u'NiaPy Documentation',\n u'Grega Vrbančič, Lucija Brezočnik, Uroš Mlakar, Dušan Fister, Iztok Fister Jr.', 'manual'),\n]\n\n\n# -- Options for manual page output ------------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n (master_doc, 'niapy', u'NiaPy Documentation',\n [author], 1)\n]\n\n\n# -- Options for Texinfo output ----------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n (master_doc, 'NiaPy', u'NiaPy Documentation',\n author, 'NiaPy', 'One line description of project.',\n 'Miscellaneous'),\n]\n\n\n# -- Extension configuration -------------------------------------------------\nautoclass_content = 'both'\n\n# -- Options for intersphinx extension ---------------------------------------\n\n# Example configuration for intersphinx: refer to the Python standard library.\nintersphinx_mapping = {'https://docs.python.org/': None}\n\n# -- Options for todo extension ----------------------------------------------\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = True\n\n# A boolean that decides whether parentheses are appended to function and method role text (e.g. the content of :func:`input`) to signify that the name is callable. Default is True\nadd_function_parentheses = True\n\n# Napolen settings\n# chekc https://sphinxcontrib-napoleon.readthedocs.io/en/latest/sphinxcontrib.napoleon.html\nnapoleon_google_docstring = True\nnapoleon_numpy_docstring = False\nnapoleon_include_init_with_doc = True\nnapoleon_include_private_with_doc = True\nnapoleon_include_special_with_doc = True\nnapoleon_use_admonition_for_examples = False\nnapoleon_use_admonition_for_notes = False\nnapoleon_use_admonition_for_references = False\nnapoleon_use_ivar = True\nnapoleon_use_param = True\nnapoleon_use_rtype = True\nnapoleon_use_keyword = True\nnapoleon_custom_sections = None\n\nimport matplotlib\nmatplotlib.use('agg')\n", "# encoding=utf8\n# pylint: disable=mixed-indentation, trailing-whitespace, multiple-statements, attribute-defined-outside-init, logging-not-lazy, no-self-use, line-too-long, arguments-differ, bad-continuation\nimport logging\n\nfrom numpy import apply_along_axis, zeros, argsort, concatenate, array, exp, cos, pi\n\nfrom NiaPy.algorithms.algorithm import Algorithm\n\nlogging.basicConfig()\nlogger = logging.getLogger('NiaPy.algorithms.basic')\nlogger.setLevel('INFO')\n\n__all__ = ['MothFlameOptimizer']\n\nclass MothFlameOptimizer(Algorithm):\n\tr\"\"\"MothFlameOptimizer of Moth flame optimizer.\n\n\tAlgorithm:\n\t\tMoth flame optimizer\n\n\tDate:\n\t\t2018\n\n\tAuthor:\n\t\tKivanc Guckiran and Klemen Berkovič\n\n\tLicense:\n\t\tMIT\n\n\tReference paper:\n\t\tMirjalili, Seyedali. \"Moth-flame optimization algorithm: A novel nature-inspired heuristic paradigm.\" Knowledge-Based Systems 89 (2015): 228-249.\n\n\tAttributes:\n\t\tName (List[str]): List of strings representing algorithm name.\n\n\tSee Also:\n\t\t* :class:`NiaPy.algorithms.algorithm.Algorithm`\n\t\"\"\"\n\tName = ['MothFlameOptimizer', 'MFO']\n\n\t@staticmethod\n\tdef algorithmInfo():\n\t\tr\"\"\"Get basic information of algorithm.\n\n\t\tReturns:\n\t\t\tstr: Basic information.\n\n\t\tSee Also:\n\t\t\t* :func:`NiaPy.algorithms.Algorithm.algorithmInfo`\n\t\t\"\"\"\n\t\treturn r\"\"\"Mirjalili, Seyedali. \"Moth-flame optimization algorithm: A novel nature-inspired heuristic paradigm.\" Knowledge-Based Systems 89 (2015): 228-249.\"\"\"\n\n\t@staticmethod\n\tdef typeParameters():\n\t\tr\"\"\"Get dictionary with functions for checking values of parameters.\n\n\t\tReturns:\n\t\t\tDict[str, Callable]: TODO\n\n\t\tSee Also:\n\t\t\t* :func:`NiaPy.algorithms.algorithm.Algorithm.typeParameters`\n\t\t\"\"\"\n\t\treturn Algorithm.typeParameters()\n\n\tdef setParameters(self, NP=25, **ukwargs):\n\t\tr\"\"\"Set the algorithm parameters.\n\n\t\tArguments:\n\t\t\tNP (int): Number of individuals in population\n\n\t\tSee Also:\n\t\t\t* :func:`NiaPy.algorithms.algorithm.Algorithm.setParameters`\n\t\t\"\"\"\n\t\tAlgorithm.setParameters(self, NP=NP, **ukwargs)\n\t\tif ukwargs: logger.info('Unused arguments: %s' % (ukwargs))\n\n\tdef initPopulation(self, task):\n\t\tr\"\"\"Initialize starting population.\n\n\t\tArgs:\n\t\t\ttask (Task): Optimization task\n\n\t\tReturns:\n\t\t\tTuple[numpy.ndarray, numpy.ndarray[float], Dict[str, Any]]:\n\t\t\t\t1. Initialized population\n\t\t\t\t2. Initialized population function/fitness values\n\t\t\t\t3. Additional arguments:\n\t\t\t\t\t* best_flames (numpy.ndarray): Best individuals\n\t\t\t\t\t* best_flame_fitness (numpy.ndarray): Best individuals fitness/function values\n\t\t\t\t\t* previous_population (numpy.ndarray): Previous population\n\t\t\t\t\t* previous_fitness (numpy.ndarray[float]): Previous population fitness/function values\n\n\t\tSee Also:\n\t\t\t* :func:`NiaPy.algorithms.algorithm.Algorithm.initPopulation`\n\t\t\"\"\"\n\t\tmoth_pos, moth_fitness, d = Algorithm.initPopulation(self, task)\n\t\t# Create best population\n\t\tindexes = argsort(moth_fitness)\n\t\tbest_flames, best_flame_fitness = moth_pos[indexes], moth_fitness[indexes]\n\t\t# Init previous population\n\t\tprevious_population, previous_fitness = zeros((self.NP, task.D)), zeros(self.NP)\n\t\td.update({'best_flames': best_flames, 'best_flame_fitness': best_flame_fitness, 'previous_population': previous_population, 'previous_fitness': previous_fitness})\n\t\treturn moth_pos, moth_fitness, d\n\n\tdef runIteration(self, task, moth_pos, moth_fitness, xb, fxb, best_flames, best_flame_fitness, previous_population, previous_fitness, **dparams):\n\t\tr\"\"\"Core function of MothFlameOptimizer algorithm.\n\n\t\tArgs:\n\t\t\ttask (Task): Optimization task.\n\t\t\tmoth_pos (numpy.ndarray): Current population.\n\t\t\tmoth_fitness (numpy.ndarray[float]): Current population fitness/function values.\n\t\t\txb (numpy.ndarray): Current population best individual.\n\t\t\tfxb (float): Current best individual\n\t\t\tbest_flames (numpy.ndarray): Best found individuals\n\t\t\tbest_flame_fitness (numpy.ndarray[float]): Best found individuals fitness/function values\n\t\t\tprevious_population (numpy.ndarray): Previous population\n\t\t\tprevious_fitness (numpy.ndarray[float]): Previous population fitness/function values\n\t\t\t**dparams (Dict[str, Any]): Additional parameters\n\n\t\tReturns:\n\t\t\tTuple[numpy.ndarray, numpy.ndarray[float], Dict[str, Any]]:\n\t\t\t\t1. New population.\n\t\t\t\t2. New population fitness/function values.\n\t\t\t\t3. Additional arguments:\n\t\t\t\t\t* best_flames (numpy.ndarray): Best individuals.\n\t\t\t\t\t* best_flame_fitness (numpy.ndarray[float]): Best individuals fitness/function values.\n\t\t\t\t\t* previous_population (numpy.ndarray): Previous population.\n\t\t\t\t\t* previous_fitness (numpy.ndarray[float]): Previous population fitness/function values.\n\t\t\"\"\"\n\t\t# Previous positions\n\t\tprevious_population, previous_fitness = moth_pos, moth_fitness\n\t\t# Create sorted population\n\t\tindexes = argsort(moth_fitness)\n\t\tsorted_population = moth_pos[indexes]\n\t\t# Some parameters\n\t\tflame_no, a = round(self.NP - task.Iters * ((self.NP - 1) / task.nGEN)), -1 + task.Iters * ((-1) / task.nGEN)\n\t\tfor i in range(self.NP):\n\t\t\tfor j in range(task.D):\n\t\t\t\tdistance_to_flame, b, t = abs(sorted_population[i, j] - moth_pos[i, j]), 1, (a - 1) * self.rand() + 1\n\t\t\t\tif i <= flame_no: moth_pos[i, j] = distance_to_flame * exp(b * t) * cos(2 * pi * t) + sorted_population[i, j]\n\t\t\t\telse: moth_pos[i, j] = distance_to_flame * exp(b * t) * cos(2 * pi * t) + sorted_population[flame_no, j]\n\t\tmoth_pos = apply_along_axis(task.repair, 1, moth_pos, self.Rand)\n\t\tmoth_fitness = apply_along_axis(task.eval, 1, moth_pos)\n\t\tdouble_population, double_fitness = concatenate((previous_population, best_flames), axis=0), concatenate((previous_fitness, best_flame_fitness), axis=0)\n\t\tindexes = argsort(double_fitness)\n\t\tdouble_sorted_fitness, double_sorted_population = double_fitness[indexes], double_population[indexes]\n\t\tfor newIdx in range(2 * self.NP): double_sorted_population[newIdx] = array(double_population[indexes[newIdx], :])\n\t\tbest_flame_fitness, best_flames = double_sorted_fitness[:self.NP], double_sorted_population[:self.NP]\n\t\treturn moth_pos, moth_fitness, {'best_flames': best_flames, 'best_flame_fitness': best_flame_fitness, 'previous_population': previous_population, 'previous_fitness': previous_fitness}\n\n# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3\n", "# encoding=utf8\n# pylint: disable=mixed-indentation, trailing-whitespace, multiple-statements, attribute-defined-outside-init, logging-not-lazy, unused-argument, arguments-differ, bad-continuation\nimport logging\n\nfrom numpy import exp\n\nfrom NiaPy.algorithms.algorithm import Algorithm\n\nlogging.basicConfig()\nlogger = logging.getLogger('NiaPy.algorithms.other')\nlogger.setLevel('INFO')\n\n__all__ = ['SimulatedAnnealing', 'coolDelta', 'coolLinear']\n\ndef coolDelta(currentT, T, deltaT, nFES, **kwargs):\n\tr\"\"\"Calculate new temperature by differences.\n\n\tArgs:\n\t\tcurrentT (float):\n\t\tT (float):\n\t\tkwargs (Dict[str, Any]): Additional arguments.\n\n\tReturns:\n\t\tfloat: New temperature.\n\t\"\"\"\n\treturn currentT - deltaT\n\ndef coolLinear(currentT, T, deltaT, nFES, **kwargs):\n\tr\"\"\"Calculate temperature with linear function.\n\n\tArgs:\n\t\tcurrentT (float): Current temperature.\n\t\tT (float):\n\t\tdeltaT (float):\n\t\tnFES (int): Number of evaluations done.\n\t\tkwargs (Dict[str, Any]): Additional arguments.\n\n\tReturns:\n\t\tfloat: New temperature.\n\t\"\"\"\n\treturn currentT - T / nFES\n\nclass SimulatedAnnealing(Algorithm):\n\tr\"\"\"Implementation of Simulated Annealing Algorithm.\n\n\tAlgorithm:\n\t\tSimulated Annealing Algorithm\n\n\tDate:\n\t\t2018\n\n\tAuthors:\n\t\tJan Popič and Klemen Berkovič\n\n\tLicense:\n\t\tMIT\n\n\tReference URL:\n\n\tReference paper:\n\n\tAttributes:\n\t\tName (List[str]): List of strings representing algorithm name.\n\t\tdelta (float): Movement for neighbour search.\n\t\tT (float); Starting temperature.\n\t\tdeltaT (float): Change in temperature.\n\t\tcoolingMethod (Callable): Neighbourhood function.\n\t\tepsilon (float): Error value.\n\n\tSee Also:\n\t\t* :class:`NiaPy.algorithms.Algorithm`\n\t\"\"\"\n\tName = ['SimulatedAnnealing', 'SA']\n\n\t@staticmethod\n\tdef algorithmInfo():\n\t\tr\"\"\"Get basic information of algorithm.\n\n\t\tReturns:\n\t\t\tstr: Basic information of algorithm.\n\n\t\tSee Also:\n\t\t\t* :func:`NiaPy.algorithms.Algorithm.algorithmInfo`\n\t\t\"\"\"\n\t\treturn r\"\"\"None\"\"\"\n\n\t@staticmethod\n\tdef typeParameters():\n\t\tr\"\"\"Get dictionary with functions for checking values of parameters.\n\n\t\tReturns:\n\t\t\tDict[str, Callable]:\n\t\t\t\t* delta (Callable[[Union[float, int], bool]): TODO\n\t\t\"\"\"\n\t\treturn {\n\t\t\t'delta': lambda x: isinstance(x, (int, float)) and x > 0,\n\t\t\t'T': lambda x: isinstance(x, (int, float)) and x > 0,\n\t\t\t'deltaT': lambda x: isinstance(x, (int, float)) and x > 0,\n\t\t\t'epsilon': lambda x: isinstance(x, float) and 0 < x < 1\n\t\t}\n\n\tdef setParameters(self, delta=0.5, T=2000, deltaT=0.8, coolingMethod=coolDelta, epsilon=1e-23, **ukwargs):\n\t\tr\"\"\"Set the algorithm parameters/arguments.\n\n\t\tArguments:\n\t\t\tdelta (Optional[float]): Movement for neighbour search.\n\t\t\tT (Optional[float]); Starting temperature.\n\t\t\tdeltaT (Optional[float]): Change in temperature.\n\t\t\tcoolingMethod (Optional[Callable]): Neighbourhood function.\n\t\t\tepsilon (Optional[float]): Error value.\n\n\t\tSee Also\n\t\t\t* :func:`NiaPy.algorithms.Algorithm.setParameters`\n\t\t\"\"\"\n\t\tukwargs.pop('NP', None)\n\t\tAlgorithm.setParameters(self, NP=1, **ukwargs)\n\t\tself.delta, self.T, self.deltaT, self.cool, self.epsilon = delta, T, deltaT, coolingMethod, epsilon\n\t\tif ukwargs: logger.info('Unused arguments: %s' % (ukwargs))\n\n\tdef initPopulation(self, task):\n\t\tx = task.Lower + task.bcRange() * self.rand(task.D)\n\t\tcurT, xfit = self.T, task.eval(x)\n\t\treturn x, xfit, {'curT': curT}\n\n\tdef runIteration(self, task, x, xfit, xb, fxb, curT, **dparams):\n\t\tc = task.repair(x - self.delta / 2 + self.rand(task.D) * self.delta, rnd=self.Rand)\n\t\tcfit = task.eval(c)\n\t\tdeltaFit, r = cfit - xfit, self.rand()\n\t\tif deltaFit < 0 or r < exp(deltaFit / curT): x, xfit = c, cfit\n\t\tcurT = self.cool(curT, self.T, deltaT=self.deltaT, nFES=task.nFES)\n\t\treturn x, xfit, {'curT': curT}\n\n# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3\n", "# encoding=utf8\n\nfrom numpy import random as rnd, array_equal\n\nfrom NiaPy.algorithms.modified import DifferentialEvolutionMTS, DifferentialEvolutionMTSv1, MultiStrategyDifferentialEvolutionMTS, MultiStrategyDifferentialEvolutionMTSv1, DynNpMultiStrategyDifferentialEvolutionMTS, DynNpMultiStrategyDifferentialEvolutionMTSv1, DynNpDifferentialEvolutionMTS, DynNpDifferentialEvolutionMTSv1\nfrom NiaPy.algorithms.modified.hde import MtsIndividual\n\nfrom NiaPy.tests.test_algorithm import AlgorithmTestCase, MyBenchmark, IndividualTestCase\n\nclass MtsIndividualTestCase(IndividualTestCase):\n\tdef setUp(self):\n\t\tIndividualTestCase.setUp(self)\n\t\tself.s1, self.s2, self.s3, self.s4 = MtsIndividual(x=self.x, task=self.task, e=False), MtsIndividual(task=self.task, SR=self.task.bRange / 10, rand=rnd), MtsIndividual(task=self.task), MtsIndividual()\n\n\tdef test_default_values_init_ok(self):\n\t\tself.assertIsNone(self.s4.SR)\n\t\tself.assertTrue(array_equal(self.task.bRange / 10, self.s2.SR))\n\t\tself.assertTrue(array_equal(self.task.bRange / 4, self.s1.SR))\n\t\tself.assertEqual(0, self.s1.grade)\n\t\tself.assertTrue(self.s1.enable)\n\t\tself.assertFalse(self.s1.improved)\n\nclass DEMTSTestCase(AlgorithmTestCase):\n\tdef test_type_parameters_fine(self):\n\t\td = DifferentialEvolutionMTS.typeParameters()\n\t\tself.assertIsNotNone(d.get('NoEnabled', None))\n\t\tself.assertIsNotNone(d.get('NoLs', None))\n\t\tself.assertIsNotNone(d.get('NoLsTests', None))\n\n\tdef test_custom_works_fine(self):\n\t\tca_custom = DifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tca_customc = DifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_custom, ca_customc, MyBenchmark())\n\n\tdef test_griewank_works_fine(self):\n\t\tca_griewank = DifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tca_griewankc = DifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_griewank, ca_griewankc)\n\nclass DEMTSv1TestCase(AlgorithmTestCase):\n\tdef test_custom_works_fine(self):\n\t\tca_custom = DifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tca_customc = DifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_custom, ca_customc, MyBenchmark())\n\n\tdef test_griewank_works_fine(self):\n\t\tca_griewank = DifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tca_griewankc = DifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_griewank, ca_griewankc)\n\nclass DynNpDEMTSTestCase(AlgorithmTestCase):\n\tdef test_custom_works_fine(self):\n\t\tca_custom = DynNpDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tca_customc = DynNpDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_custom, ca_customc, MyBenchmark())\n\n\tdef test_griewank_works_fine(self):\n\t\tca_griewank = DynNpDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tca_griewankc = DynNpDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_griewank, ca_griewankc)\n\nclass DynNpDEMTSv1TestCase(AlgorithmTestCase):\n\tdef test_custom_works_fine(self):\n\t\tca_custom = DynNpDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tca_customc = DynNpDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_custom, ca_customc, MyBenchmark())\n\n\tdef test_griewank_works_fine(self):\n\t\tca_griewank = DynNpDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tca_griewankc = DynNpDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_griewank, ca_griewankc)\n\nclass MSDEMTSTestCase(AlgorithmTestCase):\n\tdef test_custom_works_fine(self):\n\t\tca_custom = MultiStrategyDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tca_customc = MultiStrategyDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_custom, ca_customc, MyBenchmark())\n\n\tdef test_griewank_works_fine(self):\n\t\tca_griewank = MultiStrategyDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tca_griewankc = MultiStrategyDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_griewank, ca_griewankc)\n\nclass MSDEMTSv1STestCase(AlgorithmTestCase):\n\tdef test_custom_works_fine(self):\n\t\tca_custom = MultiStrategyDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tca_customc = MultiStrategyDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_custom, ca_customc, MyBenchmark())\n\n\tdef test_griewank_works_fine(self):\n\t\tca_griewank = MultiStrategyDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tca_griewankc = MultiStrategyDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_griewank, ca_griewankc)\n\nclass DynNpMSDEMTSTestCase(AlgorithmTestCase):\n\tdef test_custom_works_fine(self):\n\t\tca_custom = DynNpMultiStrategyDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tca_customc = DynNpMultiStrategyDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_custom, ca_customc, MyBenchmark())\n\n\tdef test_griewank_works_fine(self):\n\t\tca_griewank = DynNpMultiStrategyDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tca_griewankc = DynNpMultiStrategyDifferentialEvolutionMTS(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_griewank, ca_griewankc)\n\nclass DynNpMSDEMTSv1TestCase(AlgorithmTestCase):\n\tdef test_custom_works_fine(self):\n\t\tca_custom = DynNpMultiStrategyDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tca_customc = DynNpMultiStrategyDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_custom, ca_customc, MyBenchmark())\n\n\tdef test_griewank_works_fine(self):\n\t\tca_griewank = DynNpMultiStrategyDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tca_griewankc = DynNpMultiStrategyDifferentialEvolutionMTSv1(NP=40, seed=self.seed)\n\t\tAlgorithmTestCase.algorithm_run_test(self, ca_griewank, ca_griewankc)\n\n# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3\n" ]
[ [ "matplotlib.use" ], [ "numpy.cos", "numpy.concatenate", "numpy.apply_along_axis", "numpy.exp", "numpy.argsort", "numpy.array", "numpy.zeros" ], [ "numpy.exp" ], [ "numpy.array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jason-sa/Toucans
[ "d5ba3b215482cb1044e6b38833068ba93f2852f3", "d5ba3b215482cb1044e6b38833068ba93f2852f3" ]
[ "find_schedule.py", "top_stations.py" ]
[ "import pandas as pd\nimport read_mta_turnstile as t\n\n# This function generally generates a schedule for all stations in the df_top.csv file in a pivot table format.\ndef find_schedule():\n # Read the stations with highest Toucan scores and select columns relavant\n # to our schedule algorithm\n top_stations = pd.read_csv('df_top.csv')\n top_stations.rename(columns={'name':'STATION'}, inplace = True)\n top_stations1 = top_stations.loc[:,['STATION','toucan_score']] \n \n # Read the turnstile data and select the columns relavant to schedule algorithm\n turnstile_data = t.read_mta_turnstile(start='20180501', end='20180531')\n turnstile_data1 = turnstile_data.loc[:,['STATION','DATE','TIME','hourly_entries','hourly_exits']]\n \n # Merge the two DataFrames to have hourly entries and exits of stations with top Toucan scores\n turnstile_data2 = turnstile_data1.merge(top_stations1, on = 'STATION')\n \n # Format dataframe and give it \"day of week\" and \"hour of day\" values and\n # aggergate hourly entries of each station by date\n schedule = pd.DataFrame(columns = ['STATION', 'hour_of_day', 'day_name', 'hourly_entries'])\n agg = turnstile_data1.groupby(['STATION','DATE','TIME'])[['hourly_entries']].sum().reset_index()\n agg.DATE = pd.to_datetime(agg.DATE, format='%m/%d/%Y')\n agg.TIME = pd.to_datetime(agg.TIME, format='%H:%M:%S')\n agg['day_name'] = agg.DATE.dt.day_name()\n agg['hour_of_day'] = agg.TIME.dt.hour\n \n # Remove 0, 4, and 20 hours of day. Only want 8:00am, 12:00pm, and 4:00pm\n agg = agg[(agg['hour_of_day'] > 5) & (agg['hour_of_day'] < 19 )]\n \n # Segment hours of day into three different shifts: Morning, Afternoon and Evening\n l_times = []\n for h in agg.hour_of_day:\n if int(h) <= 11:\n l_times.append('Morning')\n elif int(h) >= 15:\n l_times.append('Evening')\n else:\n l_times.append('Afternoon')\n agg.hour_of_day = l_times\n \n # For each station in the top station list, this for loop generates a schedule, which identifies \n # three shifts with the highest number of entries during the week. Volunteers should be at the station\n # at these three shifts.\n for station_name in top_stations1.STATION.unique():\n # Aggergate each station's hourly entries by day of the week, shifts of the day and \n # pivot the DataFrame as shift vs. day\n hm = agg.loc[agg.STATION == station_name,['hour_of_day','day_name','hourly_entries']]\n hm = hm.groupby(['hour_of_day','day_name'])['hourly_entries'].mean().reset_index()\n hm = hm.pivot(index='hour_of_day',columns='day_name',values='hourly_entries')\n\n # Calculate three shifts with highest throughput\n sc = hm.stack().nlargest(3).reset_index() \n sc.rename(columns={0:'hourly_entries'}, inplace=True)\n sc['STATION'] = [station_name]*3\n schedule = schedule.append(sc) # This is a schedule for all stations in the top station list.\n\n # Make a pivot table of the schedule\n schedule['p'] = [1]*schedule.shape[0]\n schedule_pivot = schedule.pivot_table(index=['STATION'],columns=['day_name','hour_of_day'],values='p') \n \n return schedule_pivot", "import pandas as pd\ndef top_stations(station_companies, col='mean_entries', sort=False, top=5):\n ''' Calculates the top station company pairing based on given col, sort criteria, \n and number of records to return.\n\n station_companies = df of merge company and station data\n col = column in the data frame to perform the top n analysis\n sort = True:Descending, False:Ascending\n top = top n rows of data\n\n return pd.DataFrame subset of station_companie and filterd to top n\n '''\n df_top = pd.DataFrame(columns=station_companies.columns)\n \n groups = station_companies.groupby(['COMPANY'])\n for name, group in groups:\n if sort:\n df_top = df_top.append(group.nsmallest(top, col))\n else:\n df_top = df_top.append(group.nlargest(top, col))\n \n return df_top" ]
[ [ "pandas.read_csv", "pandas.to_datetime", "pandas.DataFrame" ], [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
Curli-quan/oneshot-medical-landmark
[ "572926077fffbe9832aa16baa98bd046ec326700" ]
[ "utils/eval.py" ]
[ "import numpy as np\r\n\r\nfrom .utils import make_dir\r\n\r\n\r\nclass Evaluater(object):\r\n def __init__(self, logger, size, original_size, tag='paper_figure'):\r\n self.pixel_spaceing = 0.1\r\n self.tag = tag\r\n make_dir(tag)\r\n self.tag += '/'\r\n\r\n self.logger = logger\r\n self.scale_rate_y = original_size[0] / size[0]\r\n self.scale_rate_x = original_size[1] / size[1]\r\n\r\n self.RE_list = list()\r\n\r\n self.recall_radius = [2, 2.5, 3, 4] # 2mm etc\r\n self.recall_rate = list()\r\n\r\n self.Attack_RE_list = list()\r\n self.Defend_RE_list = list()\r\n\r\n self.dict_Attack = dict()\r\n self.dict_Defend = dict()\r\n self.total_list = dict()\r\n\r\n self.mode_list = [0, 1, 2, 3]\r\n self.mode_dict = {0: \"Iterative FGSM\", 1: \"Adaptive Iterative FGSM\", \\\r\n 2: \"Adaptive_Rate\", 3: \"Proposed\"}\r\n\r\n for mode in self.mode_list:\r\n self.dict_Defend[mode] = dict()\r\n self.dict_Attack[mode] = dict()\r\n self.total_list[mode] = list()\r\n self.best_mre = 100.0\r\n\r\n def reset(self):\r\n self.RE_list.clear()\r\n for mode in self.mode_list:\r\n self.dict_Defend[mode] = dict()\r\n self.dict_Attack[mode] = dict()\r\n self.total_list[mode] = list()\r\n self.Attack_RE_list.clear()\r\n self.Defend_RE_list.clear()\r\n\r\n def record(self, pred, landmark):\r\n # n = batchsize = 1\r\n # pred : list[ c(y) ; c(x) ]\r\n # landmark: list [ (x , y) * c]\r\n c = pred[0].shape[0]\r\n diff = np.zeros([c, 2], dtype=float) # y, x\r\n for i in range(c):\r\n diff[i][0] = abs(pred[0][i] - landmark[i][1]) * self.scale_rate_y\r\n diff[i][1] = abs(pred[1][i] - landmark[i][0]) * self.scale_rate_x\r\n Radial_Error = np.sqrt(np.power(diff[:, 0], 2) + np.power(diff[:, 1], 2))\r\n Radial_Error *= self.pixel_spaceing\r\n self.RE_list.append(Radial_Error)\r\n # for i in range(len(Radial_Error)):\r\n # if Radial_Error[i] > 10:\r\n # print(\"Landmark {} RE {}\".format(i, Radial_Error[i]))\r\n # if Radial_Error.max() > 10:\r\n # return Radial_Error.argmax()\r\n return None\r\n\r\n def record_attack(self, pred, landmark, attack_list, mode=0, iteration=0):\r\n # n = batchsize = 1\r\n # pred : list[ c(y) ; c(x) ]\r\n # landmark: list [ (x , y) * c]\r\n assert (mode in [0, 1, 2, 3])\r\n\r\n c = pred[0].shape[0]\r\n diff = np.zeros([c, 2], dtype=float) # y, x\r\n attack_temp = list()\r\n defend_temp = list()\r\n for i in range(c):\r\n diff[i][0] = abs(pred[0][i] - landmark[i][1]) * self.scale_rate_y\r\n diff[i][1] = abs(pred[1][i] - landmark[i][0]) * self.scale_rate_x\r\n Radial_Error = np.sqrt(np.power(diff[i, 0], 2) + np.power(diff[i, 1], 2))\r\n if i in attack_list:\r\n attack_temp.append([i, Radial_Error * self.pixel_spaceing])\r\n else:\r\n defend_temp.append([i, Radial_Error * self.pixel_spaceing])\r\n\r\n if iteration not in self.dict_Attack[mode].keys():\r\n self.dict_Attack[mode][iteration] = list()\r\n self.dict_Attack[mode][iteration].append(attack_temp)\r\n if iteration not in self.dict_Defend[mode].keys():\r\n self.dict_Defend[mode][iteration] = list()\r\n self.dict_Defend[mode][iteration].append(defend_temp)\r\n\r\n def cal_metrics(self, ex=False):\r\n # calculate MRE SDR\r\n temp = np.array(self.RE_list)\r\n Mean_RE_channel = temp.mean(axis=0)\r\n self.logger.info(Mean_RE_channel)\r\n # with open('./tmp/results.csv', 'w') as f:\r\n # writer = csv.writer(f)\r\n # writer.writerow(Mean_RE_channel.tolist())\r\n mre = Mean_RE_channel.mean()\r\n self.logger.info(\"ALL MRE {}\".format(mre))\r\n\r\n for radius in self.recall_radius:\r\n total = temp.size\r\n shot = (temp < radius).sum()\r\n self.logger.info(\"ALL SDR {}mm {}\".format\\\r\n (radius, shot * 100 / total))\r\n if ex:\r\n return mre, None\r\n return mre\r\n\r\n " ]
[ [ "numpy.array", "numpy.zeros", "numpy.power" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ustc-recsys/Torchrec
[ "4d62ee42018c12961850936cfd8f4f8d3c6a8dbc" ]
[ "recstudio/model/seq/hgn.py" ]
[ "import torch\nfrom recstudio.ann import sampler\nfrom recstudio.data import dataset\nfrom recstudio.model import basemodel, loss_func, scorer\n\nr\"\"\"\nHGN\n########\n\nPaper Reference:\n Chen ma, et al. \"HGN: Hierarchical Gating Networks for Sequential Recommendation\" in KDD2019.\n https://dl.acm.org/doi/abs/10.1145/3292500.3330984\n\"\"\"\n\nclass HGNQueryEncoder(torch.nn.Module):\n \n def __init__(self, fuid, fiid, num_users, embed_dim, max_seq_len, item_encoder, pooling_type='mean') -> None:\n super().__init__()\n self.fuid = fuid\n self.fiid = fiid\n self.item_encoder = item_encoder\n self.pooling_type = pooling_type\n self.user_embedding = torch.nn.Embedding(num_users, embed_dim, 0)\n self.W_g_1 = torch.nn.Linear(embed_dim, embed_dim, bias=False)\n self.W_g_2 = torch.nn.Linear(embed_dim, embed_dim, bias=False)\n self.b_g = torch.nn.Parameter(torch.empty(embed_dim), requires_grad=True)\n self.w_g_3 = torch.nn.Linear(embed_dim, 1, bias=False)\n self.W_g_4 = torch.nn.Linear(embed_dim, max_seq_len)\n\n\n def forward(self, batch):\n U = self.user_embedding(batch[self.fuid])\n S = self.item_encoder(batch['in_'+self.fiid])\n S_F = S * torch.sigmoid(self.W_g_1(S) + self.W_g_2(U).view(U.size(0), 1, -1) + self.b_g)\n weight = torch.sigmoid(self.w_g_3(S_F) + ([email protected]_g_4.weight[:S.size(1)].T).view(U.size(0), -1, 1)) # BxLx1\n S_I = S_F * weight\n if self.pooling_type == 'mean':\n s = S_I.sum(1) / weight.sum(1)\n elif self.pooling_type == 'max':\n s = torch.max(S_I, dim=1).values\n else:\n raise ValueError(\"`pooling_type` only support `avg` and `max`\")\n query = U + s + S.sum(1)\n return query\n\n\n\nclass HGN(basemodel.BaseRetriever):\n r\"\"\"HGN proposes a hierarchical gating network, integrated with the Bayesian Personalized Ranking\n (BPR) to capture both the long-term and short-term user interests. HGN consists of a feature\n gating module, an instance gating module, and an item-item product module.\"\"\"\n\n def _get_dataset_class(self):\n r\"\"\"The dataset is SeqDataset.\"\"\"\n return dataset.SeqDataset\n\n \n def _get_query_encoder(self, train_data):\n return HGNQueryEncoder(self.fuid, self.fiid, train_data.num_users, self.embed_dim, \\\n train_data.config['max_seq_len'], self.item_encoder, self.config['pooling_type'])\n\n\n def _get_scorer_func(self):\n return scorer.InnerProductScorer()\n\n\n def _get_loss_func(self):\n r\"\"\"BPR loss is used.\"\"\"\n return loss_func.BPRLoss()\n\n\n def _get_sampler(self, train_data):\n return sampler.UniformSampler(train_data.num_items-1)\n" ]
[ [ "torch.nn.Linear", "torch.max", "torch.empty", "torch.nn.Embedding" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wesselb/wbml
[ "06bf71777ab9a75ef71845f95f91755626b37ddf" ]
[ "wbml/data/data.py" ]
[ "import datetime\nimport os\nimport shutil\nimport subprocess\nimport urllib.request\nfrom contextlib import closing\n\nimport numpy as np\nimport pandas as pd\nimport requests\n\nimport wbml.out\n\n__all__ = [\n \"DependencyError\",\n \"resource\",\n \"dependency\",\n \"asserted_dependency\",\n \"split_df\",\n \"data_path\",\n \"date_to_decimal_year\",\n]\n\n\nclass DependencyError(AssertionError):\n \"\"\"Exception raised in case of an erroneous dependency.\"\"\"\n\n\ndef resource(target, url, post=False, **kw_args):\n \"\"\"Specify a dependency on an online resource.\n\n Further takes in keyword arguments that are passed to the appropriate method\n from :mod:`requests` or :mod:`urllib`.\n\n Args:\n target (str): Target file.\n url (str): Source URL.\n post (bool, optional): Make a POST request instead of a GET request.\n Only applicable if the URL starts with \"http\" or \"https\". Defaults\n to `False`.\n \"\"\"\n if not os.path.exists(target):\n with wbml.out.Section(\"Downloading file\"):\n wbml.out.kv(\"Source\", url)\n wbml.out.kv(\"Target\", target)\n\n # Ensure that all directories in the path exist.\n make_dirs(target)\n\n # If the URL starts with \"ftp\", use the :mod:`urllib` library.\n if url.startswith(\"ftp\"):\n with closing(urllib.request.urlopen(url, **kw_args)) as r:\n with open(target, \"wb\") as f:\n shutil.copyfileobj(r, f)\n\n # By default, use the :mod:`requests` library.\n else:\n request = requests.post if post else requests.get\n with request(url, stream=True, **kw_args) as r:\n with open(target, \"wb\") as f:\n shutil.copyfileobj(r.raw, f)\n\n\ndef dependency(target, source, commands):\n \"\"\"Specify a dependency that is generated from an existing file.\n\n Args:\n target (str): Target file.\n source (str): Source file.\n commands (list[str]): List of commands to generate target file.\n \"\"\"\n if not os.path.exists(target):\n with wbml.out.Section(\"Generating file\"):\n wbml.out.kv(\"Source\", source)\n wbml.out.kv(\"Target\", target)\n\n # Check that the source exists.\n if not os.path.exists(source):\n raise DependencyError(\n f'Source \"{source}\" asserted to exist, but it does not.'\n )\n\n # Save current working directory.\n current_wd = os.getcwd()\n\n # Ensure that all directories in the path exist.\n make_dirs(target)\n\n # Perform commands.\n for command in commands:\n wbml.out.out(command)\n\n # Change working directory to directory of target file, run\n # command, and restore working directory afterwards.\n os.chdir(os.path.dirname(target))\n subprocess.call(command, shell=True)\n os.chdir(current_wd)\n\n\ndef asserted_dependency(target):\n \"\"\"Specify a dependency that cannot be fetched.\n\n Args:\n target (str): Target file.\n \"\"\"\n if not os.path.exists(target):\n raise DependencyError(\n f'Dependency \"{target}\" is asserted to exist, '\n f\"but it does not, and it cannot be \"\n f\"automatically fetched. Please put the file \"\n f\"into place manually.\"\n )\n\n\ndef make_dirs(path):\n \"\"\"Make the directories in the path of a file.\n\n Args:\n path (url): Path of a file.\n \"\"\"\n os.makedirs(os.path.dirname(path), exist_ok=True)\n\n\ndef data_path(*xs):\n \"\"\"Get the path of a data file.\n\n Args:\n *xs (str): Parts of the path.\n\n Returns:\n str: Absolute path.\n \"\"\"\n return os.path.abspath(\n os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, \"data\", *xs)\n )\n\n\ndef split_df(df, index_range, columns, iloc=False):\n \"\"\"Split a data frame by selecting from columns a particular range.\n\n Args:\n df (:class:`pd.DataFrame`): Data frame to split.\n index_range (tuple): Tuple containing lower and upper limit of the\n range to split the index by. If `index_range = (a, b)`, then\n `[a, b)` is taken.\n columns (list[object]): Columns to select.\n iloc (bool, optional): The index range is the integer location instead\n of the index value. Defaults to `False`.\n\n Returns:\n tuple[:class:`pd.DataFrame`]: Selected rows from selected columns\n and the remainder.\n \"\"\"\n if iloc:\n inds = np.arange(df.shape[0])\n rows = (inds >= index_range[0]) & (inds < index_range[1])\n else:\n rows = (df.index >= index_range[0]) & (df.index < index_range[1])\n selected = pd.DataFrame([df[name][rows] for name in columns]).T\n remainder = pd.DataFrame(\n [df[name][~rows] for name in columns]\n + [df[name] for name in set(df.columns) - set(columns)]\n ).T\n\n # Fix order of columns.\n selected_inds = [i for i, c in enumerate(df.columns) if c in columns]\n selected = selected.reindex(df.columns[np.array(selected_inds)], axis=1)\n remainder = remainder.reindex(df.columns, axis=1)\n\n return selected, remainder\n\n\ndef date_to_decimal_year(date, format=None):\n \"\"\"Convert a date to decimal year.\n\n Args:\n date (str): Date as a string.\n format (str, optional): Format of the date if a conversion is needed.\n\n Returns:\n float: Decimal year corresponding to the date.\n \"\"\"\n if format:\n date = datetime.datetime.strptime(date, format)\n start = datetime.date(date.year, 1, 1).toordinal()\n year_length = datetime.date(date.year + 1, 1, 1).toordinal() - start\n\n # Account for subday time.\n subday_time = 0\n if hasattr(date, \"hour\"):\n subday_time += date.hour / year_length / 24\n if hasattr(date, \"minute\"):\n subday_time += date.minute / year_length / 24 / 60\n if hasattr(date, \"second\"):\n subday_time += date.second / year_length / 24 / 60 / 60\n\n return date.year + float(date.toordinal() - start) / year_length + subday_time\n" ]
[ [ "numpy.arange", "numpy.array", "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": [] } ]
anorthman/mmdetection
[ "52e28154364f0e19d11c206bb357d88f29fc4a2d", "52e28154364f0e19d11c206bb357d88f29fc4a2d" ]
[ "mmdet/datasets/classify/imagenet.py", "mmdet/models/anchor_heads/knowledge_distilling/kd_retina_head.py" ]
[ "import os\nimport cv2\nfrom PIL import Image\nimport torch\n\nimport mmcv\nimport numpy as np\nfrom torch.utils.data import Dataset\nimport torchvision.transforms as T\nfrom torchvision.datasets import ImageFolder\n\n\nclass ImageNetDataset(Dataset):\n\n def __init__(self,\n data_root,\n test_mode=False,**kwargs):\n self.classes = list(range(1000))\n normalize = T.Normalize(mean=[0.456], std=[1.0])\n #normalize = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n if not test_mode:\n traindir = os.path.join(data_root, 'train')\n self.dataset = ImageFolder(traindir, T.Compose([\n T.Grayscale(num_output_channels=1),\n T.RandomResizedCrop(224, scale=(0.8, 1.0)),\n T.RandomHorizontalFlip(),\n T.ToTensor(),\n normalize,\n ]))\n else:\n valdir = os.path.join(data_root, 'val')\n self.dataset = ImageFolder(valdir, T.Compose([\n T.Resize(256),\n T.CenterCrop(224),\n T.ToTensor(),\n normalize,\n ]))\n if not test_mode:\n self._set_group_flag()\n \n def _set_group_flag(self):\n \"\"\"Set flag according to image aspect ratio.\n\n Images with aspect ratio greater than 1 will be set as group 1,\n otherwise group 0.\n \"\"\"\n self.flag = np.zeros(len(self), dtype=np.uint8)\n\n def __getitem__(self, idx):\n d = dict(img=self.dataset[idx][0], label=torch.tensor([self.dataset[idx][1]], dtype=torch.long))\n return d\n\n def __len__(self):\n return len(self.dataset)\n \n \n \n \n", "# author huangchuanhong\nfrom __future__ import division\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom mmcv.cnn import normal_init\n\nfrom mmdet.core import (AnchorGenerator, anchor_target, delta2bbox,\n multi_apply, weighted_cross_entropy, weighted_smoothl1,\n weighted_binary_cross_entropy,\n weighted_sigmoid_focal_loss,\n weighted_sigmoid_kldiv_focal_loss,\n weighted_sigmoid_kldiv, \n multiclass_nms, attention_loss)\nfrom ...registry import HEADS\n\nfrom ..retina_head import RetinaHead\n\[email protected]_module\nclass KDRetinaHead(RetinaHead):\n '''\n add kd_loss to loss, implemented only for retinanet\n '''\n def loss_single(self, cls_score, bbox_pred, teacher_cls_scores,\n teacher_bbox_preds, labels, label_weights,\n bbox_targets, bbox_weights, num_total_samples, cfg):\n # classification loss \n if self.use_sigmoid_cls:\n labels = labels.reshape(-1, self.cls_out_channels)\n label_weights = label_weights.reshape(-1, self.cls_out_channels)\n else:\n raise NotImplementedError\n cls_score = cls_score.permute(0, 2, 3, 1).reshape(\n -1, self.cls_out_channels)\n teacher_cls_scores = teacher_cls_scores.permute(0, 2, 3, 1).reshape(\n -1, self.cls_out_channels)\n if self.use_sigmoid_cls:\n if self.use_focal_loss:\n cls_criterion = weighted_sigmoid_focal_loss\n #if cfg.teacher.kd_with_focal:\n # kd_cls_criterion = weighted_sigmoid_kldiv_focal_loss\n #else:\n # kd_cls_criterion = weighted_sigmoid_kldiv\n else:\n raise NotImplementedError\n else:\n if self.use_focal_loss:\n raise NotImplementedError\n else:\n raise NotImplementedError\n if self.use_focal_loss:\n if cfg.focal_loss == 0.:\n loss_cls = torch.zeros([]).cuda() \n else:\n loss_cls = cls_criterion(\n cls_score,\n labels,\n label_weights,\n gamma=cfg.gamma,\n alpha=cfg.alpha,\n avg_factor=num_total_samples)\n if cfg.teacher.kd_with_focal:\n loss_kd_cls = weighted_sigmoid_kldiv_focal_loss(\n cls_score,\n teacher_cls_scores,\n label_weights,\n temperature=cfg.teacher.temperature,\n gamma=cfg.gamma,\n alpha=cfg.alpha,\n teacher_alpha=cfg.teacher.alpha,\n avg_factor=num_total_samples)\n else:\n loss_kd_cls = weighted_sigmoid_kldiv(\n cls_score,\n teacher_cls_scores,\n label_weights,\n temperature=cfg.teacher.temperature,\n teacher_alpha=cfg.teacher.alpha,\n avg_factor=num_total_samples)\n else:\n raise NotImplementedError\n # regression loss\n bbox_targets = bbox_targets.reshape(-1, 4)\n bbox_weights = bbox_weights.reshape(-1, 4)\n bbox_pred = bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4)\n loss_reg = weighted_smoothl1(\n bbox_pred,\n bbox_targets,\n bbox_weights,\n beta=cfg.smoothl1_beta,\n avg_factor=num_total_samples)\n return loss_cls, loss_kd_cls, loss_reg\n\n def loss(self,\n features,\n cls_scores,\n bbox_preds,\n teacher_features,\n teacher_cls_scores,\n teacher_bbox_preds,\n gt_bboxes,\n gt_labels,\n img_metas,\n cfg,\n gt_bboxes_ignore=None):\n featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]\n assert len(featmap_sizes) == len(self.anchor_generators)\n\n anchor_list, valid_flag_list = self.get_anchors(\n featmap_sizes, img_metas)\n sampling = False if self.use_focal_loss else True\n label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1\n cls_reg_targets = anchor_target(\n anchor_list,\n valid_flag_list,\n gt_bboxes,\n img_metas,\n self.target_means,\n self.target_stds,\n cfg,\n gt_bboxes_ignore_list=gt_bboxes_ignore,\n gt_labels_list=gt_labels,\n label_channels=label_channels,\n sampling=sampling)\n if cls_reg_targets is None:\n return None\n (labels_list, label_weights_list, bbox_targets_list, bbox_weights_list,\n num_total_pos, num_total_neg) = cls_reg_targets\n num_total_samples = (num_total_pos if self.use_focal_loss else\n num_total_pos + num_total_neg)\n losses_cls, losses_kd_cls, losses_reg = multi_apply(\n self.loss_single,\n cls_scores,\n bbox_preds,\n teacher_cls_scores,\n teacher_bbox_preds,\n labels_list,\n label_weights_list,\n bbox_targets_list,\n bbox_weights_list,\n num_total_samples=num_total_samples,\n cfg=cfg)\n losses_at, = multi_apply(\n attention_loss,\n features,\n teacher_features,\n beta=cfg.teacher.beta)\n return dict(loss_cls=losses_cls, loss_kd_cls=losses_kd_cls, loss_reg=losses_reg,\n loss_at=losses_at)\n" ]
[ [ "torch.tensor" ], [ "torch.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
pystatgen/sgk
[ "f39e1b1bc3b16d05c5043ab5d445076424dad229" ]
[ "sgkit/io/bgen/bgen_reader.py" ]
[ "\"\"\"BGEN reader implementation (using bgen_reader)\"\"\"\nimport logging\nimport tempfile\nimport time\nfrom pathlib import Path\nfrom typing import (\n Any,\n Dict,\n Hashable,\n List,\n Mapping,\n MutableMapping,\n Optional,\n Tuple,\n Union,\n)\n\nimport dask\nimport dask.array as da\nimport dask.dataframe as dd\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport zarr\nfrom cbgen import bgen_file, bgen_metafile\nfrom rechunker import api as rechunker_api\nfrom xarray import Dataset\n\nfrom sgkit import create_genotype_dosage_dataset\nfrom sgkit.io.utils import dataframe_to_dict, encode_contigs\nfrom sgkit.typing import ArrayLike, DType, NDArray, PathType\n\nlogger = logging.getLogger(__name__)\n\nGT_DATA_VARS = [\n \"call_genotype_probability\",\n \"call_genotype_probability_mask\",\n \"call_dosage\",\n \"call_dosage_mask\",\n]\n\nMETAFILE_DTYPE = dict(\n [\n (\"id\", \"S\"),\n (\"rsid\", \"S\"),\n (\"chrom\", \"S\"),\n (\"pos\", \"int32\"),\n (\"a1\", \"S\"),\n (\"a2\", \"S\"),\n (\"offset\", \"int64\"),\n ]\n)\n\n\nclass BgenReader:\n\n name = \"bgen_reader\"\n\n def __init__(\n self,\n path: PathType,\n metafile_path: Optional[PathType] = None,\n dtype: DType = \"float32\",\n ) -> None:\n self.path = Path(path)\n self.metafile_path = (\n Path(metafile_path) if metafile_path else self.path.with_suffix(\".metafile\")\n )\n\n with bgen_file(self.path) as bgen:\n self.n_variants = bgen.nvariants\n self.n_samples = bgen.nsamples\n\n if not self.metafile_path.exists():\n start = time.time()\n logger.info(\n f\"Generating BGEN metafile for '{self.path}' (this may take a while)\"\n )\n bgen.create_metafile(self.metafile_path, verbose=False)\n stop = time.time()\n logger.info(\n f\"BGEN metafile generation complete ({stop - start:.0f} seconds)\"\n )\n\n with bgen_metafile(self.metafile_path) as mf:\n assert self.n_variants == mf.nvariants\n self.npartitions = mf.npartitions\n self.partition_size = mf.partition_size\n\n self.shape = (self.n_variants, self.n_samples, 3)\n self.dtype = np.dtype(dtype)\n self.precision = 64 if self.dtype.itemsize >= 8 else 32\n self.ndim = 3\n\n def __getitem__(self, idx: Any) -> NDArray:\n if not isinstance(idx, tuple):\n raise IndexError(f\"Indexer must be tuple (received {type(idx)})\")\n if len(idx) != self.ndim:\n raise IndexError(\n f\"Indexer must have {self.ndim} items (received {len(idx)} slices)\"\n )\n if not all(isinstance(i, slice) or isinstance(i, int) for i in idx):\n raise IndexError(\n f\"Indexer must contain only slices or ints (received types {[type(i) for i in idx]})\"\n )\n # Determine which dims should have unit size in result\n squeeze_dims = tuple(i for i in range(len(idx)) if isinstance(idx[i], int))\n # Convert all indexers to slices\n idx = tuple(slice(i, i + 1) if isinstance(i, int) else i for i in idx)\n\n if idx[0].start == idx[0].stop:\n return np.empty((0,) * self.ndim, dtype=self.dtype)\n\n # Determine start and end partitions that correspond to the\n # given variant dimension indexer\n start_partition = idx[0].start // self.partition_size\n start_partition_offset = idx[0].start % self.partition_size\n end_partition = (idx[0].stop - 1) // self.partition_size\n end_partition_offset = (idx[0].stop - 1) % self.partition_size\n\n # Create a list of all offsets into the underlying file at which\n # data for each variant begins\n all_vaddr = []\n with bgen_metafile(self.metafile_path) as mf:\n for i in range(start_partition, end_partition + 1):\n partition = mf.read_partition(i)\n start_offset = start_partition_offset if i == start_partition else 0\n end_offset = (\n end_partition_offset + 1\n if i == end_partition\n else self.partition_size\n )\n vaddr = partition.variants.offset\n all_vaddr.extend(vaddr[start_offset:end_offset].tolist())\n\n # Read the probabilities for each variant, apply indexer for\n # samples dimension to give probabilities for all genotypes,\n # and then apply final genotype dimension indexer\n with bgen_file(self.path) as bgen:\n res = None\n for i, vaddr in enumerate(all_vaddr):\n probs = bgen.read_probability(vaddr, precision=self.precision)[idx[1]]\n assert len(probs.shape) == 2 and probs.shape[1] == 3\n if res is None:\n res = np.zeros((len(all_vaddr), len(probs), 3), dtype=self.dtype)\n res[i] = probs\n res = res[..., idx[2]] # type: ignore[index]\n return np.squeeze(res, axis=squeeze_dims)\n\n\ndef _split_alleles(allele_ids: bytes) -> List[bytes]:\n alleles = allele_ids.split(b\",\")\n if len(alleles) != 2:\n raise NotImplementedError(\n f\"Bgen reads only supported for biallelic variants (found non-biallelic variant '{str(allele_ids)}')\"\n )\n return alleles\n\n\ndef _read_metafile_partition(path: Path, partition: int) -> pd.DataFrame:\n with bgen_metafile(path) as mf:\n part = mf.read_partition(partition)\n v = part.variants\n allele_ids = np.array([_split_alleles(aid) for aid in v.allele_ids])\n data = {\n \"id\": v.id,\n \"rsid\": v.rsid,\n \"chrom\": v.chromosome,\n \"pos\": v.position,\n \"a1\": allele_ids[:, 0],\n \"a2\": allele_ids[:, 1],\n \"offset\": v.offset,\n }\n return pd.DataFrame(data).astype(METAFILE_DTYPE)\n\n\ndef read_metafile(path: PathType) -> dd.DataFrame:\n \"\"\"Read cbgen metafile containing partitioned variant info\"\"\"\n with bgen_metafile(path) as mf:\n divisions = [mf.partition_size * i for i in range(mf.npartitions)] + [\n mf.nvariants - 1\n ]\n dfs = [\n dask.delayed(_read_metafile_partition)(path, i)\n for i in range(mf.npartitions)\n ]\n meta = dd.utils.make_meta(METAFILE_DTYPE)\n return dd.from_delayed(dfs, meta=meta, divisions=divisions)\n\n\ndef read_samples(path: PathType) -> pd.DataFrame:\n \"\"\"Read BGEN .sample file\"\"\"\n df = pd.read_csv(path, sep=\" \", skiprows=[1], usecols=[0])\n df.columns = [\"sample_id\"]\n return df\n\n\ndef read_bgen(\n path: PathType,\n metafile_path: Optional[PathType] = None,\n sample_path: Optional[PathType] = None,\n chunks: Union[str, int, Tuple[int, int, int]] = \"auto\",\n lock: bool = False,\n persist: bool = True,\n contig_dtype: DType = \"str\",\n gp_dtype: DType = \"float32\",\n) -> Dataset:\n \"\"\"Read BGEN dataset.\n\n Loads a single BGEN dataset as dask arrays within a Dataset\n from a ``.bgen`` file.\n\n Parameters\n ----------\n path\n Path to BGEN file.\n metafile_path\n Path to companion index file used to determine BGEN byte offsets.\n Defaults to ``path`` + \".metafile\" if not provided.\n This file is necessary for reading BGEN genotype probabilities and it will be\n generated the first time the file is read if it does not already exist.\n If it needs to be created, it can make the first call to this function\n much slower than subsequent calls.\n sample_path\n Path to ``.sample`` file, by default None. This is used to fetch sample identifiers\n and when provided it is preferred over sample identifiers embedded in the ``.bgen`` file.\n chunks\n Chunk size for genotype probability data (3 dimensions),\n by default \"auto\".\n lock\n Whether or not to synchronize concurrent reads of\n file blocks, by default False. This is passed through to\n [dask.array.from_array](https://docs.dask.org/en/latest/array-api.html#dask.array.from_array).\n persist\n Whether or not to persist variant information in memory, by default True.\n This is an important performance consideration as the metadata file for this data will\n be read multiple times when False.\n contig_dtype\n Data type for contig names, by default \"str\".\n This may also be an integer type (e.g. \"int\"), but will fail if any of the contig names\n cannot be converted to integers.\n gp_dtype\n Data type for genotype probabilities, by default \"float32\".\n\n Warnings\n --------\n Only bi-allelic, diploid BGEN files are currently supported.\n\n Returns\n -------\n A dataset containing the following variables:\n\n - :data:`sgkit.variables.variant_id_spec` (variants)\n - :data:`sgkit.variables.variant_contig_spec` (variants)\n - :data:`sgkit.variables.variant_position_spec` (variants)\n - :data:`sgkit.variables.variant_allele_spec` (variants)\n - :data:`sgkit.variables.sample_id_spec` (samples)\n - :data:`sgkit.variables.call_dosage_spec` (variants, samples)\n - :data:`sgkit.variables.call_dosage_mask_spec` (variants, samples)\n - :data:`sgkit.variables.call_genotype_probability_spec` (variants, samples, genotypes)\n - :data:`sgkit.variables.call_genotype_probability_mask_spec` (variants, samples, genotypes)\n\n \"\"\"\n if isinstance(chunks, tuple) and len(chunks) != 3:\n raise ValueError(f\"`chunks` must be tuple with 3 items, not {chunks}\")\n if not np.issubdtype(gp_dtype, np.floating):\n raise ValueError(\n f\"`gp_dtype` must be a floating point data type, not {gp_dtype}\"\n )\n if not np.issubdtype(contig_dtype, np.integer) and np.dtype(\n contig_dtype\n ).kind not in {\"U\", \"S\"}:\n raise ValueError(\n f\"`contig_dtype` must be of string or int type, not {contig_dtype}\"\n )\n\n path = Path(path)\n sample_path = Path(sample_path) if sample_path else path.with_suffix(\".sample\")\n\n if sample_path.exists():\n sample_id = read_samples(sample_path).sample_id.values.astype(\"U\")\n else:\n sample_id = _default_sample_ids(path)\n\n bgen_reader = BgenReader(path, metafile_path=metafile_path, dtype=gp_dtype)\n\n df = read_metafile(bgen_reader.metafile_path)\n if persist:\n df = df.persist()\n arrs = dataframe_to_dict(df, METAFILE_DTYPE)\n\n variant_id = arrs[\"id\"]\n variant_contig: ArrayLike = arrs[\"chrom\"].astype(contig_dtype)\n variant_contig, variant_contig_names = encode_contigs(variant_contig)\n variant_contig_names = list(variant_contig_names)\n variant_position = arrs[\"pos\"]\n variant_allele = da.hstack((arrs[\"a1\"][:, np.newaxis], arrs[\"a2\"][:, np.newaxis]))\n\n call_genotype_probability = da.from_array(\n bgen_reader,\n chunks=chunks,\n lock=lock,\n fancy=False,\n asarray=False,\n name=f\"{bgen_reader.name}:read_bgen:{path}\",\n )\n call_dosage = _to_dosage(call_genotype_probability)\n\n ds: Dataset = create_genotype_dosage_dataset(\n variant_contig_names=variant_contig_names,\n variant_contig=variant_contig,\n variant_position=variant_position,\n variant_allele=variant_allele,\n sample_id=sample_id,\n call_dosage=call_dosage,\n call_genotype_probability=call_genotype_probability,\n variant_id=variant_id,\n )\n\n return ds\n\n\ndef _default_sample_ids(path: PathType) -> ArrayLike:\n \"\"\"Fetch or generate sample ids\"\"\"\n with bgen_file(path) as bgen:\n if bgen.contain_samples:\n return bgen.read_samples()\n else:\n return np.char.add(b\"sample_\", np.arange(bgen.nsamples).astype(\"S\")) # type: ignore[no-untyped-call]\n\n\ndef _to_dosage(probs: ArrayLike) -> ArrayLike:\n \"\"\"Calculate the dosage from genotype likelihoods (probabilities)\"\"\"\n assert (\n probs.shape[-1] == 3\n ), f\"Expecting genotype (trailing) dimension of size 3, got array of shape {probs.shape}\"\n return probs[..., 1] + 2 * probs[..., 2]\n\n\n########################\n# Rechunking Functions #\n########################\n\n\ndef encode_variables(\n ds: Dataset,\n chunk_length: int,\n chunk_width: int,\n compressor: Optional[Any] = zarr.Blosc(cname=\"zstd\", clevel=7, shuffle=2),\n probability_dtype: Optional[Any] = \"uint8\",\n) -> Dict[Hashable, Dict[str, Any]]:\n encoding = {}\n for v in ds:\n e = {}\n if compressor is not None:\n e.update({\"compressor\": compressor})\n if v in GT_DATA_VARS:\n e.update({\"chunks\": (chunk_length, chunk_width) + ds[v].shape[2:]})\n if probability_dtype is not None and v == \"call_genotype_probability\":\n dtype = np.dtype(probability_dtype)\n # Xarray will decode into float32 so any int greater than\n # 16 bits will cause overflow/underflow\n # See https://en.wikipedia.org/wiki/Floating-point_arithmetic#Internal_representation\n # *bits precision column for single precision floats\n if dtype not in [np.uint8, np.uint16]: # type: ignore[comparison-overlap]\n raise ValueError(\n \"Probability integer dtype invalid, must \"\n f\"be uint8 or uint16 not {probability_dtype}\"\n )\n divisor = np.iinfo(dtype).max - 1\n e.update(\n {\n \"dtype\": probability_dtype,\n \"add_offset\": -1.0 / divisor,\n \"scale_factor\": 1.0 / divisor,\n \"_FillValue\": 0,\n }\n )\n if e:\n encoding[v] = e\n return encoding\n\n\ndef pack_variables(ds: Dataset) -> Dataset:\n # Remove dosage as it is unnecessary and should be redefined\n # based on encoded probabilities later (w/ reduced precision)\n ds = ds.drop_vars([\"call_dosage\", \"call_dosage_mask\"], errors=\"ignore\")\n\n # Remove homozygous reference GP and redefine mask\n gp = ds[\"call_genotype_probability\"][..., 1:]\n gp_mask = ds[\"call_genotype_probability_mask\"].any(dim=\"genotypes\")\n ds = ds.drop_vars([\"call_genotype_probability\", \"call_genotype_probability_mask\"])\n ds = ds.assign(call_genotype_probability=gp, call_genotype_probability_mask=gp_mask)\n return ds\n\n\ndef unpack_variables(ds: Dataset, dtype: DType = \"float32\") -> Dataset:\n # Restore homozygous reference GP\n gp = ds[\"call_genotype_probability\"].astype(dtype)\n if gp.sizes[\"genotypes\"] != 2:\n raise ValueError(\n \"Expecting variable 'call_genotype_probability' to have genotypes \"\n f\"dimension of size 2 (received sizes = {dict(gp.sizes)})\"\n )\n ds = ds.drop_vars(\"call_genotype_probability\")\n ds[\"call_genotype_probability\"] = xr.concat(\n [1 - gp.sum(dim=\"genotypes\", skipna=False), gp], dim=\"genotypes\"\n )\n\n # Restore dosage\n ds[\"call_dosage\"] = gp[..., 0] + 2 * gp[..., 1]\n ds[\"call_dosage_mask\"] = ds[\"call_genotype_probability_mask\"]\n ds[\"call_genotype_probability_mask\"] = ds[\n \"call_genotype_probability_mask\"\n ].broadcast_like(ds[\"call_genotype_probability\"])\n return ds\n\n\ndef rechunk_bgen(\n ds: Dataset,\n output: Union[PathType, MutableMapping[str, bytes]],\n *,\n chunk_length: int = 10_000,\n chunk_width: int = 1_000,\n compressor: Optional[Any] = zarr.Blosc(cname=\"zstd\", clevel=7, shuffle=2),\n probability_dtype: Optional[DType] = \"uint8\",\n max_mem: str = \"4GB\",\n pack: bool = True,\n tempdir: Optional[PathType] = None,\n) -> Dataset:\n \"\"\"Rechunk BGEN dataset as Zarr.\n\n This function will use the algorithm https://rechunker.readthedocs.io/en/latest/\n to rechunk certain fields in a provided Dataset for better downstream performance.\n Depending on the system memory available (and the `max_mem` setting) this\n rechunking may occur without the need of any intermediate data store. Otherwise,\n approximately as much disk space is required as was needed to store the original\n BGEN data. Experiments show that this Zarr representation is ~20% larger even\n with all available optimizations and fairly aggressive compression (i.e. the\n default `clevel` 7).\n\n Note that this function is not evaluated lazily. The rechunking algorithm\n will run inline so calls to it may be slow. The resulting Dataset is\n generated based on the final, serialized Zarr data.\n\n Parameters\n ----------\n ds\n Dataset to rechunk, typically the result from `read_bgen`.\n output\n Zarr store or path to directory in file system.\n chunk_length\n Length (number of variants) of chunks in which data are stored, by default 10_000.\n chunk_width\n Width (number of samples) to use when storing chunks in output, by default 1_000.\n compressor\n Zarr compressor, no compression is used when set as None.\n probability_dtype\n Data type used to encode genotype probabilities, must be either uint8 or uint16.\n Setting this parameter results in a loss of precision. If None, probabilities\n will not be altered when stored.\n max_mem\n The amount of memory (in bytes) that workers are allowed to use. A string\n (e.g. 100MB) can also be used.\n pack\n Whether or not to optimize variable representations by removing unnecessary\n dimensions and elements. This includes storing 2 genotypes instead of 3, omitting\n dosage and collapsing the genotype probability mask to 2 dimensions. All of\n the above are restored in the resulting Dataset at the expense of extra\n computations on read.\n tempdir\n Temporary directory where intermediate files are stored. The default None means\n use the system default temporary directory.\n\n Warnings\n --------\n This functional is only applicable to diploid, bi-allelic BGEN datasets.\n\n Returns\n -------\n Dataset\n The rechunked dataset.\n \"\"\"\n if isinstance(output, Path):\n output = str(output)\n\n chunk_length = min(chunk_length, ds.dims[\"variants\"])\n chunk_width = min(chunk_width, ds.dims[\"samples\"])\n\n if pack:\n ds = pack_variables(ds)\n\n encoding = encode_variables(\n ds,\n chunk_length=chunk_length,\n chunk_width=chunk_width,\n compressor=compressor,\n probability_dtype=probability_dtype,\n )\n target_chunks = {\n var: encoding[var][\"chunks\"] for var in encoding if \"chunks\" in encoding[var]\n }\n target_options = {\n var: {k: v for k, v in encoding[var].items() if k != \"chunks\"}\n for var in encoding\n }\n with tempfile.TemporaryDirectory(\n prefix=\"bgen_to_zarr_\", suffix=\".zarr\", dir=tempdir\n ) as tmpdir:\n rechunked = rechunker_api.rechunk(\n ds,\n max_mem=max_mem,\n target_chunks=target_chunks,\n target_store=output,\n target_options=target_options,\n temp_store=tmpdir,\n executor=\"dask\",\n )\n rechunked.execute()\n\n zarr.consolidate_metadata(output)\n\n ds: Dataset = xr.open_zarr(output, concat_characters=False) # type: ignore[no-untyped-call]\n if pack:\n ds = unpack_variables(ds)\n\n return ds\n\n\ndef bgen_to_zarr(\n input: PathType,\n output: Union[PathType, MutableMapping[str, bytes]],\n region: Optional[Mapping[Hashable, Any]] = None,\n chunk_length: int = 10_000,\n chunk_width: int = 1_000,\n temp_chunk_length: int = 100,\n compressor: Optional[Any] = zarr.Blosc(cname=\"zstd\", clevel=7, shuffle=2),\n probability_dtype: Optional[DType] = \"uint8\",\n max_mem: str = \"4GB\",\n pack: bool = True,\n tempdir: Optional[PathType] = None,\n) -> Dataset:\n \"\"\"Convert a BGEN file to a Zarr on-disk store.\n\n This function is a convenience for calling :func:`read_bgen` followed by\n :func:`rechunk_bgen`.\n\n Parameters\n ----------\n input\n Path to local BGEN dataset.\n output\n Zarr store or path to directory in file system.\n region\n Indexers on dataset dimensions used to define a subset of data to convert.\n Must be None or a dict with keys matching dimension names and values\n equal to integers or slice objects. This is passed directly to `Dataset.isel`\n so it has the same semantics.\n chunk_length\n Length (number of variants) of chunks in which data are stored, by default 10_000.\n chunk_width\n Width (number of samples) to use when storing chunks in output, by default 1_000.\n temp_chunk_length\n Length of chunks used in raw BGEN read, by default 100. This defines the vertical\n chunking (i.e. in the variants dimension) used when reading the raw data and because\n there is no horizontal chunking at this phase (i.e. in the samples dimension), this\n value should be much smaller than the target `chunk_length`.\n compressor\n Zarr compressor, by default Blosc + zstd with compression level 7. No compression\n is used when set as None.\n probability_dtype\n Data type used to encode genotype probabilities, must be either uint8 or uint16.\n Setting this parameter results in a loss of precision. If None, probabilities\n will not be altered when stored.\n max_mem\n The amount of memory (in bytes) that workers are allowed to use. A string\n (e.g. 100MB) can also be used.\n pack\n Whether or not to optimize variable representations by removing unnecessary\n dimensions and elements. This includes storing 2 genotypes instead of 3, omitting\n dosage and collapsing the genotype probability mask to 2 dimensions. All of\n the above are restored in the resulting Dataset at the expense of extra\n computations on read.\n tempdir\n Temporary directory where intermediate files are stored. The default None means\n use the system default temporary directory.\n\n Warnings\n --------\n This functional is only applicable to diploid, bi-allelic BGEN datasets.\n\n Returns\n -------\n Dataset\n The rechunked dataset.\n \"\"\"\n ds = read_bgen(input, chunks=(temp_chunk_length, -1, -1))\n if region is not None:\n ds = ds.isel(indexers=region)\n return rechunk_bgen(\n ds,\n output,\n chunk_length=chunk_length,\n chunk_width=chunk_width,\n compressor=compressor,\n probability_dtype=probability_dtype,\n max_mem=max_mem,\n pack=pack,\n tempdir=tempdir,\n )\n" ]
[ [ "pandas.read_csv", "numpy.arange", "numpy.issubdtype", "numpy.squeeze", "numpy.dtype", "pandas.DataFrame", "numpy.iinfo", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
mzeidhassan/doctr
[ "14b376e07d31b09b6bd31bceebf6ffb477c30f08", "14b376e07d31b09b6bd31bceebf6ffb477c30f08", "14b376e07d31b09b6bd31bceebf6ffb477c30f08" ]
[ "api/tests/routes/test_detection.py", "test/pytorch/test_models_preprocessor_pt.py", "doctr/datasets/sroie.py" ]
[ "# Copyright (C) 2021, Mindee.\n\n# This program is licensed under the Apache License version 2.\n# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.\n\nimport pytest\nimport numpy as np\nfrom scipy.optimize import linear_sum_assignment\nfrom doctr.utils.metrics import box_iou\n\n\[email protected]\nasync def test_text_detection(test_app_asyncio, mock_detection_image):\n\n response = await test_app_asyncio.post(\"/detection\", files={'file': mock_detection_image})\n assert response.status_code == 200\n json_response = response.json()\n\n gt_boxes = np.array([[1240, 430, 1355, 470], [1360, 430, 1495, 470]], dtype=np.float32)\n gt_boxes[:, [0, 2]] = gt_boxes[:, [0, 2]] / 1654\n gt_boxes[:, [1, 3]] = gt_boxes[:, [1, 3]] / 2339\n\n # Check that IoU with GT if reasonable\n assert isinstance(json_response, list) and len(json_response) == gt_boxes.shape[0]\n pred_boxes = np.array([elt['box'] for elt in json_response])\n iou_mat = box_iou(gt_boxes, pred_boxes)\n gt_idxs, pred_idxs = linear_sum_assignment(-iou_mat)\n is_kept = iou_mat[gt_idxs, pred_idxs] >= 0.8\n assert gt_idxs[is_kept].shape[0] == gt_boxes.shape[0]\n", "import pytest\n\nimport numpy as np\nimport torch\nfrom doctr.models.preprocessor import PreProcessor\n\n\[email protected](\n \"batch_size, output_size, input_tensor, expected_batches, expected_value\",\n [\n [2, (128, 128), np.full((3, 256, 128, 3), 255, dtype=np.uint8), 1, .5], # numpy uint8\n [2, (128, 128), np.ones((3, 256, 128, 3), dtype=np.float32), 1, .5], # numpy fp32\n [2, (128, 128), np.ones((3, 256, 128, 3), dtype=np.float16), 1, .5], # numpy fp16\n [2, (128, 128), torch.full((3, 3, 256, 128), 255, dtype=torch.uint8), 1, .5], # torch uint8\n [2, (128, 128), torch.ones((3, 3, 256, 128), dtype=torch.float32), 1, .5], # torch fp32\n [2, (128, 128), torch.ones((3, 3, 256, 128), dtype=torch.float16), 1, .5], # torch fp16\n [2, (128, 128), [np.full((256, 128, 3), 255, dtype=np.uint8)] * 3, 2, .5], # list of numpy uint8\n [2, (128, 128), [np.ones((256, 128, 3), dtype=np.float32)] * 3, 2, .5], # list of numpy fp32\n [2, (128, 128), [np.ones((256, 128, 3), dtype=np.float16)] * 3, 2, .5], # list of numpy fp16\n [2, (128, 128), [torch.full((3, 256, 128), 255, dtype=torch.uint8)] * 3, 2, .5], # list of torch uint8\n [2, (128, 128), [torch.ones((3, 256, 128), dtype=torch.float32)] * 3, 2, .5], # list of torch fp32\n [2, (128, 128), [torch.ones((3, 256, 128), dtype=torch.float16)] * 3, 2, .5], # list of torch fp32\n ],\n)\ndef test_preprocessor(batch_size, output_size, input_tensor, expected_batches, expected_value):\n\n processor = PreProcessor(output_size, batch_size)\n\n # Invalid input type\n with pytest.raises(TypeError):\n processor(42)\n # 4D check\n with pytest.raises(AssertionError):\n processor(np.full((256, 128, 3), 255, dtype=np.uint8))\n with pytest.raises(TypeError):\n processor(np.full((1, 256, 128, 3), 255, dtype=np.int32))\n # 3D check\n with pytest.raises(AssertionError):\n processor([np.full((3, 256, 128, 3), 255, dtype=np.uint8)])\n with pytest.raises(TypeError):\n processor([np.full((256, 128, 3), 255, dtype=np.int32)])\n\n with torch.no_grad():\n out = processor(input_tensor)\n assert isinstance(out, list) and len(out) == expected_batches\n assert all(isinstance(b, torch.Tensor) for b in out)\n assert all(b.dtype == torch.float32 for b in out)\n assert all(b.shape[-2:] == output_size for b in out)\n assert all(torch.all(b == expected_value) for b in out)\n assert len(repr(processor).split('\\n')) == 4\n\n # Check FP16\n processor = PreProcessor(output_size, batch_size, fp16=True)\n with torch.no_grad():\n out = processor(input_tensor)\n assert all(b.dtype == torch.float16 for b in out)\n", "# Copyright (C) 2021, Mindee.\n\n# This program is licensed under the Apache License version 2.\n# See LICENSE or go to <https://www.apache.org/licenses/LICENSE-2.0.txt> for full license details.\n\nimport os\nimport csv\nimport numpy as np\nfrom pathlib import Path\nfrom typing import List, Dict, Any, Tuple, Optional, Callable\n\nfrom .datasets import VisionDataset\n\n__all__ = ['SROIE']\n\n\nclass SROIE(VisionDataset):\n \"\"\"SROIE dataset from `\"ICDAR2019 Competition on Scanned Receipt OCR and Information Extraction\"\n <https://arxiv.org/pdf/2103.10213.pdf>`_.\n\n Example::\n >>> from doctr.datasets import SROIE\n >>> train_set = SROIE(train=True, download=True)\n >>> img, target = train_set[0]\n\n Args:\n train: whether the subset should be the training one\n sample_transforms: composable transformations that will be applied to each image\n rotated_bbox: whether polygons should be considered as rotated bounding box (instead of straight ones)\n **kwargs: keyword arguments from `VisionDataset`.\n \"\"\"\n\n TRAIN = ('https://github.com/mindee/doctr/releases/download/v0.1.1/sroie2019_train_task1.zip',\n 'd4fa9e60abb03500d83299c845b9c87fd9c9430d1aeac96b83c5d0bb0ab27f6f')\n TEST = ('https://github.com/mindee/doctr/releases/download/v0.1.1/sroie2019_test.zip',\n '41b3c746a20226fddc80d86d4b2a903d43b5be4f521dd1bbe759dbf8844745e2')\n\n def __init__(\n self,\n train: bool = True,\n sample_transforms: Optional[Callable[[Any], Any]] = None,\n rotated_bbox: bool = False,\n **kwargs: Any,\n ) -> None:\n\n url, sha256 = self.TRAIN if train else self.TEST\n super().__init__(url, None, sha256, True, **kwargs)\n self.sample_transforms = sample_transforms\n self.train = train\n\n if rotated_bbox:\n raise NotImplementedError\n\n # # List images\n tmp_root = os.path.join(self.root, 'images')\n self.data: List[Tuple[str, Dict[str, Any]]] = []\n np_dtype = np.float16 if self.fp16 else np.float32\n for img_path in os.listdir(tmp_root):\n # File existence check\n if not os.path.exists(os.path.join(tmp_root, img_path)):\n raise FileNotFoundError(f\"unable to locate {os.path.join(tmp_root, img_path)}\")\n stem = Path(img_path).stem\n _targets = []\n with open(os.path.join(self.root, 'annotations', f\"{stem}.txt\"), encoding='latin') as f:\n for row in csv.reader(f, delimiter=','):\n # Safeguard for blank lines\n if len(row) > 0:\n # Label may contain commas\n label = \",\".join(row[8:])\n # Reduce 8 coords to 4\n p1_x, p1_y, p2_x, p2_y, p3_x, p3_y, p4_x, p4_y = map(int, row[:8])\n left, right = min(p1_x, p2_x, p3_x, p4_x), max(p1_x, p2_x, p3_x, p4_x)\n top, bot = min(p1_y, p2_y, p3_y, p4_y), max(p1_y, p2_y, p3_y, p4_y)\n if len(label) > 0:\n _targets.append((label, [left, top, right, bot]))\n\n text_targets, box_targets = zip(*_targets)\n\n self.data.append((img_path, dict(boxes=np.asarray(box_targets, dtype=np_dtype), labels=text_targets)))\n self.root = tmp_root\n\n def extra_repr(self) -> str:\n return f\"train={self.train}\"\n" ]
[ [ "scipy.optimize.linear_sum_assignment", "numpy.array" ], [ "torch.all", "torch.ones", "torch.full", "numpy.ones", "numpy.full", "torch.no_grad" ], [ "numpy.asarray" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.4", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
fariasfc/solo-learn
[ "f53ff40edbc7e96e06db5238d8c3a44f7b8965c1", "b75ba6faf5269b0849120bfb89593f9bc23e09bc", "b75ba6faf5269b0849120bfb89593f9bc23e09bc", "b75ba6faf5269b0849120bfb89593f9bc23e09bc", "b75ba6faf5269b0849120bfb89593f9bc23e09bc" ]
[ "solo/utils/classification_dataloader.py", "tests/utils/test_pretrain_dataloader.py", "solo/losses/vicreg.py", "tests/losses/test_moco.py", "solo/losses/simclr.py" ]
[ "import os\nfrom pathlib import Path\nfrom typing import Callable, Optional, Tuple, Union\n\nimport torchvision\nfrom torch import nn\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision import transforms\nfrom torchvision.datasets import STL10, ImageFolder\n\n\ndef build_custom_pipeline():\n \"\"\"Builds augmentation pipelines for custom data.\n If you want to do exoteric augmentations, you can just re-write this function.\n Needs to return a dict with the same structure.\n \"\"\"\n\n pipeline = {\n \"T_train\": transforms.Compose(\n [\n transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.228, 0.224, 0.225)),\n ]\n ),\n \"T_val\": transforms.Compose(\n [\n transforms.Resize(256), # resize shorter\n transforms.CenterCrop(224), # take center crop\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.228, 0.224, 0.225)),\n ]\n ),\n }\n return pipeline\n\n\ndef prepare_transforms(dataset: str) -> Tuple[nn.Module, nn.Module]:\n \"\"\"Prepares pre-defined train and test transformation pipelines for some datasets.\n\n Args:\n dataset (str): dataset name.\n\n Returns:\n Tuple[nn.Module, nn.Module]: training and validation transformation pipelines.\n \"\"\"\n\n cifar_pipeline = {\n \"T_train\": transforms.Compose(\n [\n transforms.RandomResizedCrop(size=32, scale=(0.08, 1.0)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261)),\n ]\n ),\n \"T_val\": transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.247, 0.243, 0.261)),\n ]\n ),\n }\n\n stl_pipeline = {\n \"T_train\": transforms.Compose(\n [\n transforms.RandomResizedCrop(size=96, scale=(0.08, 1.0)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4823, 0.4466), (0.247, 0.243, 0.261)),\n ]\n ),\n \"T_val\": transforms.Compose(\n [\n transforms.Resize((96, 96)),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4823, 0.4466), (0.247, 0.243, 0.261)),\n ]\n ),\n }\n\n imagenet_pipeline = {\n \"T_train\": transforms.Compose(\n [\n transforms.RandomResizedCrop(size=224, scale=(0.08, 1.0)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.228, 0.224, 0.225)),\n ]\n ),\n \"T_val\": transforms.Compose(\n [\n transforms.Resize(256), # resize shorter\n transforms.CenterCrop(224), # take center crop\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.228, 0.224, 0.225)),\n ]\n ),\n }\n\n custom_pipeline = build_custom_pipeline()\n\n pipelines = {\n \"cifar10\": cifar_pipeline,\n \"cifar100\": cifar_pipeline,\n \"stl10\": stl_pipeline,\n \"imagenet100\": imagenet_pipeline,\n \"imagenet\": imagenet_pipeline,\n \"custom\": custom_pipeline,\n }\n\n assert dataset in pipelines\n\n pipeline = pipelines[dataset]\n T_train = pipeline[\"T_train\"]\n T_val = pipeline[\"T_val\"]\n\n return T_train, T_val\n\n\ndef prepare_datasets(\n dataset: str,\n T_train: Callable,\n T_val: Callable,\n data_dir: Optional[Union[str, Path]] = None,\n train_dir: Optional[Union[str, Path]] = None,\n val_dir: Optional[Union[str, Path]] = None,\n) -> Tuple[Dataset, Dataset]:\n \"\"\"Prepares train and val datasets.\n\n Args:\n dataset (str): dataset name.\n T_train (Callable): pipeline of transformations for training dataset.\n T_val (Callable): pipeline of transformations for validation dataset.\n data_dir Optional[Union[str, Path]]: path where to download/locate the dataset.\n train_dir Optional[Union[str, Path]]: subpath where the training data is located.\n val_dir Optional[Union[str, Path]]: subpath where the validation data is located.\n\n Returns:\n Tuple[Dataset, Dataset]: training dataset and validation dataset.\n \"\"\"\n\n if data_dir is None:\n sandbox_dir = Path(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\n data_dir = sandbox_dir / \"datasets\"\n else:\n data_dir = Path(data_dir)\n\n if train_dir is None:\n train_dir = Path(f\"{dataset}/train\")\n else:\n train_dir = Path(train_dir)\n\n if val_dir is None:\n val_dir = Path(f\"{dataset}/val\")\n else:\n val_dir = Path(val_dir)\n\n assert dataset in [\"cifar10\", \"cifar100\", \"stl10\", \"imagenet\", \"imagenet100\", \"custom\"]\n\n if dataset in [\"cifar10\", \"cifar100\"]:\n DatasetClass = vars(torchvision.datasets)[dataset.upper()]\n train_dataset = DatasetClass(\n data_dir / train_dir,\n train=True,\n download=True,\n transform=T_train,\n )\n\n val_dataset = DatasetClass(\n data_dir / val_dir,\n train=False,\n download=True,\n transform=T_val,\n )\n\n elif dataset == \"stl10\":\n train_dataset = STL10(\n data_dir / train_dir,\n split=\"train\",\n download=True,\n transform=T_train,\n )\n val_dataset = STL10(\n data_dir / val_dir,\n split=\"test\",\n download=True,\n transform=T_val,\n )\n\n elif dataset in [\"imagenet\", \"imagenet100\", \"custom\"]:\n train_dir = data_dir / train_dir\n val_dir = data_dir / val_dir\n\n train_dataset = ImageFolder(train_dir, T_train)\n val_dataset = ImageFolder(val_dir, T_val)\n\n return train_dataset, val_dataset\n\n\ndef prepare_dataloaders(\n train_dataset: Dataset, val_dataset: Dataset, batch_size: int = 64, num_workers: int = 4\n) -> Tuple[DataLoader, DataLoader]:\n \"\"\"Wraps a train and a validation dataset with a DataLoader.\n\n Args:\n train_dataset (Dataset): object containing training data.\n val_dataset (Dataset): object containing validation data.\n batch_size (int): batch size.\n num_workers (int): number of parallel workers.\n Returns:\n Tuple[DataLoader, DataLoader]: training dataloader and validation dataloader.\n \"\"\"\n\n train_loader = DataLoader(\n train_dataset,\n batch_size=batch_size,\n shuffle=True,\n num_workers=num_workers,\n pin_memory=True,\n drop_last=True,\n )\n val_loader = DataLoader(\n val_dataset,\n batch_size=batch_size,\n num_workers=num_workers,\n pin_memory=True,\n drop_last=False,\n )\n return train_loader, val_loader\n\n\ndef prepare_data(\n dataset: str,\n transform: Optional[Callable] = None,\n data_dir: Optional[Union[str, Path]] = None,\n train_dir: Optional[Union[str, Path]] = None,\n val_dir: Optional[Union[str, Path]] = None,\n batch_size: int = 64,\n num_workers: int = 4,\n) -> Tuple[DataLoader, DataLoader]:\n \"\"\"Prepares transformations, creates dataset objects and wraps them in dataloaders.\n\n Args:\n dataset (str): dataset name.\n data_dir (Optional[Union[str, Path]], optional): path where to download/locate the dataset.\n Defaults to None.\n train_dir (Optional[Union[str, Path]], optional): subpath where the\n training data is located. Defaults to None.\n val_dir (Optional[Union[str, Path]], optional): subpath where the\n validation data is located. Defaults to None.\n batch_size (int, optional): batch size. Defaults to 64.\n num_workers (int, optional): number of parallel workers. Defaults to 4.\n\n Returns:\n Tuple[DataLoader, DataLoader]: prepared training and validation dataloader;.\n \"\"\"\n\n if transform is None:\n T_train, T_val = prepare_transforms(dataset)\n else:\n T_train = transform\n T_val = transform\n\n train_dataset, val_dataset = prepare_datasets(\n dataset,\n T_train,\n T_val,\n data_dir=data_dir,\n train_dir=train_dir,\n val_dir=val_dir,\n )\n train_loader, val_loader = prepare_dataloaders(\n train_dataset,\n val_dataset,\n batch_size=batch_size,\n num_workers=num_workers,\n )\n return train_loader, val_loader\n", "import numpy as np\nfrom PIL import Image\nfrom solo.utils.pretrain_dataloader import (\n prepare_dataloader,\n prepare_datasets,\n prepare_multicrop_transform,\n prepare_n_crop_transform,\n prepare_transform,\n)\nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets.cifar import CIFAR10\n\n\ndef test_transforms():\n\n kwargs = dict(\n brightness=0.5,\n contrast=0.5,\n saturation=0.4,\n hue=0.2,\n gaussian_prob=0.5,\n solarization_prob=0.4,\n )\n\n im = np.random.rand(100, 100, 3) * 255\n im = Image.fromarray(im.astype(\"uint8\")).convert(\"RGB\")\n\n T = prepare_transform(\"cifar10\", multicrop=False, **kwargs)\n assert T(im).size(1) == 32\n\n T = prepare_transform(\"stl10\", multicrop=False, **kwargs)\n assert T(im).size(1) == 96\n\n T = prepare_transform(\"imagenet100\", multicrop=False, **kwargs)\n assert T(im).size(1) == 224\n\n num_crops = 10\n assert len(prepare_n_crop_transform(T, num_crops=num_crops)(im)) == num_crops\n\n T = prepare_transform(\"imagenet100\", multicrop=True, **kwargs)\n num_crops = [3, 9]\n sizes = [224, 96]\n T = prepare_multicrop_transform(T, sizes, num_crops=num_crops)\n crops = T(im)\n cur = 0\n for i, crop in enumerate(crops):\n assert crop.size(1) == sizes[cur]\n if i + 1 >= num_crops[cur] and len(num_crops) > cur + 1:\n cur += 1\n\n\ndef test_data():\n\n kwargs = dict(\n brightness=0.5,\n contrast=0.5,\n saturation=0.4,\n hue=0.2,\n gaussian_prob=0.5,\n solarization_prob=0.4,\n )\n\n T = prepare_transform(\"cifar10\", multicrop=False, **kwargs)\n T = prepare_n_crop_transform(T, num_crops=2)\n train_dataset = prepare_datasets(\"cifar10\", T, data_dir=\"./datasets\")\n\n assert isinstance(train_dataset, CIFAR10)\n assert len(train_dataset[0]) == 3\n\n bs = 64\n num_samples_train = len(train_dataset)\n num_batches_train = num_samples_train // bs\n\n train_loader = prepare_dataloader(train_dataset, batch_size=bs, num_workers=0)\n\n assert isinstance(train_loader, DataLoader)\n assert num_batches_train == len(train_loader)\n", "import torch\nimport torch.nn.functional as F\n\n\ndef invariance_loss(z1: torch.Tensor, z2: torch.Tensor) -> torch.Tensor:\n \"\"\"Computes mse loss given batch of projected features z1 from view 1 and\n projected features z2 from view 2.\n\n Args:\n z1 (torch.Tensor): NxD Tensor containing projected features from view 1.\n z2 (torch.Tensor): NxD Tensor containing projected features from view 2.\n\n Returns:\n torch.Tensor: invariance loss (mean squared error).\n \"\"\"\n\n return F.mse_loss(z1, z2)\n\n\ndef variance_loss(z1: torch.Tensor, z2: torch.Tensor) -> torch.Tensor:\n \"\"\"Computes variance loss given batch of projected features z1 from view 1 and\n projected features z2 from view 2.\n\n Args:\n z1 (torch.Tensor): NxD Tensor containing projected features from view 1.\n z2 (torch.Tensor): NxD Tensor containing projected features from view 2.\n\n Returns:\n torch.Tensor: variance regularization loss.\n \"\"\"\n\n eps = 1e-4\n std_z1 = torch.sqrt(z1.var(dim=0) + eps)\n std_z2 = torch.sqrt(z2.var(dim=0) + eps)\n std_loss = torch.mean(F.relu(1 - std_z1)) + torch.mean(F.relu(1 - std_z2))\n return std_loss\n\n\ndef covariance_loss(z1: torch.Tensor, z2: torch.Tensor) -> torch.Tensor:\n \"\"\"Computes covariance loss given batch of projected features z1 from view 1 and\n projected features z2 from view 2.\n\n Args:\n z1 (torch.Tensor): NxD Tensor containing projected features from view 1.\n z2 (torch.Tensor): NxD Tensor containing projected features from view 2.\n\n Returns:\n torch.Tensor: covariance regularization loss.\n \"\"\"\n\n N, D = z1.size()\n\n z1 = z1 - z1.mean(dim=0)\n z2 = z2 - z2.mean(dim=0)\n cov_z1 = (z1.T @ z1) / (N - 1)\n cov_z2 = (z2.T @ z2) / (N - 1)\n\n diag = torch.eye(D, device=z1.device)\n cov_loss = cov_z1[~diag.bool()].pow_(2).sum() / D + cov_z2[~diag.bool()].pow_(2).sum() / D\n return cov_loss\n\n\ndef vicreg_loss_func(\n z1: torch.Tensor,\n z2: torch.Tensor,\n sim_loss_weight: float = 25.0,\n var_loss_weight: float = 25.0,\n cov_loss_weight: float = 1.0,\n) -> torch.Tensor:\n \"\"\"Computes VICReg's loss given batch of projected features z1 from view 1 and\n projected features z2 from view 2.\n\n Args:\n z1 (torch.Tensor): NxD Tensor containing projected features from view 1.\n z2 (torch.Tensor): NxD Tensor containing projected features from view 2.\n sim_loss_weight (float): invariance loss weight.\n var_loss_weight (float): variance loss weight.\n cov_loss_weight (float): covariance loss weight.\n\n Returns:\n torch.Tensor: VICReg loss.\n \"\"\"\n\n sim_loss = invariance_loss(z1, z2)\n var_loss = variance_loss(z1, z2)\n cov_loss = covariance_loss(z1, z2)\n\n loss = sim_loss_weight * sim_loss + var_loss_weight * var_loss + cov_loss_weight * cov_loss\n return loss\n", "import torch\nfrom solo.losses import moco_loss_func\n\n\ndef test_moco_loss():\n b, f, q = 32, 128, 15000\n query = torch.randn(b, f).requires_grad_()\n key = torch.randn(b, f).requires_grad_()\n queue = torch.randn(f, q)\n\n loss = moco_loss_func(query, key, queue, temperature=0.1)\n initial_loss = loss.item()\n assert loss != 0\n\n for i in range(20):\n loss = moco_loss_func(query, key, queue, temperature=0.1)\n loss.backward()\n query.data.add_(-0.5 * query.grad)\n key.data.add_(-0.5 * key.grad)\n\n query.grad = key.grad = None\n\n assert loss < initial_loss\n", "import torch\nimport torch.nn.functional as F\nfrom typing import Optional\n\n\ndef simclr_loss_func(\n z1: torch.Tensor,\n z2: torch.Tensor,\n temperature: float = 0.1,\n extra_pos_mask: Optional[torch.Tensor] = None,\n) -> torch.Tensor:\n \"\"\"Computes SimCLR's loss given batch of projected features z1 from view 1 and\n projected features z2 from view 2.\n\n Args:\n z1 (torch.Tensor): NxD Tensor containing projected features from view 1.\n z2 (torch.Tensor): NxD Tensor containing projected features from view 2.\n temperature (float): temperature factor for the loss. Defaults to 0.1.\n extra_pos_mask (Optional[torch.Tensor]): boolean mask containing extra positives other\n than normal across-view positives. Defaults to None.\n\n Returns:\n torch.Tensor: SimCLR loss.\n \"\"\"\n\n device = z1.device\n\n b = z1.size(0)\n z = torch.cat((z1, z2), dim=0)\n z = F.normalize(z, dim=-1)\n\n logits = torch.einsum(\"if, jf -> ij\", z, z) / temperature\n logits_max, _ = torch.max(logits, dim=1, keepdim=True)\n logits = logits - logits_max.detach()\n\n # positive mask are matches i, j (i from aug1, j from aug2), where i == j and matches j, i\n pos_mask = torch.zeros((2 * b, 2 * b), dtype=torch.bool, device=device)\n pos_mask[:, b:].fill_diagonal_(True)\n pos_mask[b:, :].fill_diagonal_(True)\n\n # if we have extra \"positives\"\n if extra_pos_mask is not None:\n pos_mask = torch.bitwise_or(pos_mask, extra_pos_mask)\n\n # all matches excluding the main diagonal\n logit_mask = torch.ones_like(pos_mask, device=device).fill_diagonal_(0)\n\n exp_logits = torch.exp(logits) * logit_mask\n log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True))\n\n # compute mean of log-likelihood over positives\n mean_log_prob_pos = (pos_mask * log_prob).sum(1) / pos_mask.sum(1)\n # loss\n loss = -mean_log_prob_pos.mean()\n return loss\n\n\ndef manual_simclr_loss_func(\n z: torch.Tensor, pos_mask: torch.Tensor, neg_mask: torch.Tensor, temperature: float = 0.1\n) -> torch.Tensor:\n \"\"\"Manually computes SimCLR's loss given batch of projected features z\n from different views, a positive boolean mask of all positives and\n a negative boolean mask of all negatives.\n\n Args:\n z (torch.Tensor): NxViewsxD Tensor containing projected features from the views.\n pos_mask (torch.Tensor): boolean mask containing all positives for z * z.T.\n neg_mask (torch.Tensor): boolean mask containing all negatives for z * z.T.\n temperature (float): temperature factor for the loss.\n\n Return:\n torch.Tensor: manual SimCLR loss.\n \"\"\"\n\n z = F.normalize(z, dim=-1)\n\n logits = torch.einsum(\"if, jf -> ij\", z, z) / temperature\n logits_max, _ = torch.max(logits, dim=1, keepdim=True)\n logits = logits - logits_max.detach()\n\n negatives = torch.sum(torch.exp(logits) * neg_mask, dim=1, keepdim=True)\n exp_logits = torch.exp(logits)\n log_prob = torch.log(exp_logits / (exp_logits + negatives))\n\n # compute mean of log-likelihood over positive\n mean_log_prob_pos = (pos_mask * log_prob).sum(1)\n\n indexes = pos_mask.sum(1) > 0\n pos_mask = pos_mask[indexes]\n mean_log_prob_pos = mean_log_prob_pos[indexes] / pos_mask.sum(1)\n\n # loss\n loss = -mean_log_prob_pos.mean()\n return loss\n" ]
[ [ "torch.utils.data.DataLoader" ], [ "numpy.random.rand" ], [ "torch.nn.functional.mse_loss", "torch.nn.functional.relu", "torch.eye" ], [ "torch.randn" ], [ "torch.nn.functional.normalize", "torch.max", "torch.zeros", "torch.cat", "torch.einsum", "torch.bitwise_or", "torch.exp", "torch.log", "torch.ones_like" ] ]
[ { "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": [] } ]
tmartin2/EnsembleSplice-Inactive
[ "a161ff007b47ceadd3a21376f2eac2971bb81d90" ]
[ "sub_models.py" ]
[ "# -----------------------------------------------------------------------------\n# Copyright (c) 2021 Trevor P. Martin. All rights reserved.\n# Distributed under the MIT License.\n# -----------------------------------------------------------------------------\nfrom Data import encode_data\n# from utils import cross_validation\nfrom Models import utils\nfrom Models import build_models\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import Perceptron\nfrom sklearn.svm import LinearSVC\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as font_manager\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport copy\n\n\nclass CNN01(tf.keras.Model):\n @staticmethod\n def build(rows, columns, channels, classes):\n model = tf.keras.Sequential()\n input_shape = (rows, columns, channels)\n model.add(tf.keras.layers.InputLayer(input_shape=input_shape))\n model.add(tf.keras.layers.Conv2D(\n filters=32,\n kernel_size=(3,3),\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.Conv2D(\n filters=64,\n kernel_size=(3,3),\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(tf.keras.layers.Conv2D(\n filters=128,\n kernel_size=(3,3),\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dropout(0.5))\n model.add(tf.keras.layers.Dense(classes, activation=\"softmax\"))\n return model\n\nclass CNN02(tf.keras.Model):\n @staticmethod\n def build(rows, columns, classes):\n model = tf.keras.Sequential()\n input_shape = (rows, columns)\n model.add(tf.keras.layers.InputLayer(input_shape=input_shape))\n model.add(tf.keras.layers.Conv1D(\n filters=32,\n kernel_size=3,\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.Conv1D(\n filters=64,\n kernel_size=3,\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.MaxPooling1D(pool_size=2))\n model.add(tf.keras.layers.Conv1D(\n filters=128,\n kernel_size=3,\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.MaxPooling1D(pool_size=2))\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dropout(0.5))\n model.add(tf.keras.layers.Dense(classes, activation=\"softmax\"))\n return model\n\nclass CNN03(tf.keras.Model):\n @staticmethod\n def build(rows, columns, classes):\n model = tf.keras.Sequential()\n input_shape = (rows, columns)\n model.add(tf.keras.layers.InputLayer(input_shape=input_shape))\n model.add(tf.keras.layers.Conv1D(\n filters=32,\n kernel_size=3,\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.MaxPooling1D(pool_size=2))\n model.add(tf.keras.layers.Conv1D(\n filters=64,\n kernel_size=3,\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.MaxPooling1D(pool_size=2))\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dropout(0.5))\n model.add(tf.keras.layers.Dense(classes, activation=\"softmax\"))\n return model\n\nclass CNN04(tf.keras.Model):\n @staticmethod\n def build(rows, columns, classes):\n model = tf.keras.Sequential()\n input_shape = (rows, columns)\n model.add(tf.keras.layers.InputLayer(input_shape=input_shape))\n model.add(tf.keras.layers.Conv1D(\n filters=32,\n kernel_size=3,\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.MaxPooling1D(pool_size=2))\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dropout(0.5))\n model.add(tf.keras.layers.Dense(classes, activation=\"softmax\"))\n return model\n\nclass CNN05(tf.keras.Model):\n @staticmethod\n def build(rows, columns, channels, classes):\n model = tf.keras.Sequential()\n input_shape = (rows, columns, channels)\n model.add(tf.keras.layers.InputLayer(input_shape=input_shape))\n model.add(tf.keras.layers.Conv2D(\n filters=32,\n kernel_size=(3,3),\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.Conv2D(\n filters=64,\n kernel_size=(3,3),\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.Conv2D(\n filters=64,\n kernel_size=(3,3),\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(tf.keras.layers.Conv2D(\n filters=128,\n kernel_size=(3,3),\n activation=\"relu\",\n padding=\"same\"\n )\n )\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dropout(0.5))\n model.add(tf.keras.layers.Dense(classes, activation=\"softmax\"))\n return model\n\nclass DNN01(tf.keras.Model):\n @staticmethod\n def build(rows, columns, units, classes):\n model = tf.keras.Sequential()\n input_shape = (rows, columns)\n model.add(tf.keras.layers.InputLayer(input_shape=input_shape))\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dense(units=units, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001)))\n model.add(tf.keras.layers.Dense(units=units//2, kernel_regularizer=tf.keras.regularizers.l2(0.001)))\n model.add(tf.keras.layers.Dropout(rate=0.15))\n model.add(tf.keras.layers.Dense(units=units//4, kernel_regularizer=tf.keras.regularizers.l2(0.001)))\n model.add(tf.keras.layers.Dense(classes, activation=\"softmax\"))\n return model\n\nclass DNN02(tf.keras.Model):\n @staticmethod\n def build(rows, columns, units, classes):\n model = tf.keras.Sequential()\n input_shape = (rows, columns)\n model.add(tf.keras.layers.InputLayer(input_shape=input_shape))\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dense(units=units, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001)))\n model.add(tf.keras.layers.Dropout(rate=0.50))\n model.add(tf.keras.layers.Dense(units=units//2, kernel_regularizer=tf.keras.regularizers.l2(0.001)))\n model.add(tf.keras.layers.Dense(classes, activation=\"softmax\"))\n return model\n\nclass DNN03(tf.keras.Model):\n @staticmethod\n def build(rows, columns, units, classes):\n model = tf.keras.Sequential()\n input_shape = (rows, columns)\n model.add(tf.keras.layers.InputLayer(input_shape=input_shape))\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dense(units=units*2, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001)))\n model.add(tf.keras.layers.Dropout(rate=0.50))\n model.add(tf.keras.layers.Dense(classes, activation=\"softmax\"))\n return model\n\nclass RNN(tf.keras.Model):\n @staticmethod\n def build(rows, columns, units, classes):\n model = tf.keras.Sequential()\n input_shape = (rows, columns)\n model.add(tf.keras.layers.InputLayer(input_shape=input_shape))\n model.add(tf.keras.layers.LSTM(\n units=units,\n activation='tanh',\n return_sequences=True,\n )\n )\n model.add(tf.keras.layers.Dropout(rate=0.20))\n model.add(tf.keras.layers.LSTM(\n units=units//2,\n activation='tanh',\n )\n )\n model.add(tf.keras.layers.Dropout(rate=0.20))\n model.add(tf.keras.layers.Dense(64, activation=\"relu\"))\n model.add(tf.keras.layers.Dense(classes, activation=\"softmax\"))\n return model\n\n\ndef run(datasets,\n splice_sites,\n sub_models,\n save,\n vis,\n iter,\n metrics,\n summary,\n config,\n num_folds,\n bal,\n imbal,\n imbal_t,\n imbal_f,\n batch_size,\n epochs\n ):\n \"\"\"\n Parameters\n ----------\n dataset: a string {nn269, ce, hs3d} indicating which dataset to use\n splice_site_type: a string {acceptor, donor} indicating which splice\n site to train on\n model_architecture: a string {cnn, dnn, rnn} indicating which model\n architecture to use for training\n save_model: boolean, whether to save the current model\n bal: boolean, whether to balance the dataset\n summary: boolean, whether to print out the model architecture summary\n config: boolean, whether to print out the model's configuration\n visualize: boolean, whether to save a performance graph of the model\n metrics: boolean, whether to print out the evaluation metrics for the model\n num_folds: int (default 10), the number of folds for k-fold cross validation\n epochs: int (default 15), the number of epochs for the chosen model\n batch_size: int (default 32), the model batch size\n model_iter: integer, the iteration of the current model architecture (e.g.\n if this is the third cnn architecture you are testing, use 3)\n \"\"\"\n # (acceptor row len, donor row len) by dataset\n network_rows = {\n 'acceptor':{\n 'nn269':90, 'ce':141,\n 'hs3d':140, 'hs2':602,\n 'ce2':602, 'dm':602,\n 'ar':602, 'or':602,\n },\n\n 'donor':{\n 'nn269':15, 'ce':141,\n 'hs3d':140, 'hs2':602,\n 'ce2':602, 'dm':602,\n 'ar':602, 'or':602,\n },\n\n }\n\n # initialize selected sub models\n to_run = dict(\n [\n (sub_model,{\n 'nn269':'', 'ce':'',\n 'hs3d':'', 'hs2':'',\n 'ce2':'', 'dm':'',\n 'ar':'', 'or':''\n }) for sub_model in sub_models\n ]\n )\n\n # results dictionary\n results = copy.deepcopy(to_run)\n\n # populate sub models with encoded data\n for sub_model in sub_models:\n for dataset in datasets:\n # encode datasets -> return (acc_x, acc_y, don_x, don_y)\n to_run[sub_model][dataset] = encode_data.encode(dataset, sub_model, bal)\n\n # get a metrics dictionary\n evals = dict(\n [\n (sub_model, {\n 'f1':'', 'precision':'',\n 'sensitivity':'', 'specificity':'',\n 'recall':'', 'mcc':'',\n 'err_rate':''\n }) for sub_model in sub_models\n ]\n )\n\n # accumulate results from running cross validation\n for sub_model in sub_models:\n for dataset in datasets:\n if to_run[sub_model][dataset] == '':\n pass\n else:\n results[sub_model][dataset] = utils.cross_validation(\n num_folds,\n sub_model,\n splice_sites,\n dataset,\n to_run[sub_model][dataset],# encoded data for dataset (ds)\n network_rows, # donor, acceptor rows for ds\n evals,\n summary,\n config,\n batch_size,\n epochs,\n save,\n )\n # if vis:\n\n print(results)\n return results\n\n\n # plot results\n\n\n # loss_acc_sub_models(\n # results,\n # datasets,\n # sub_models,\n # epochs,\n # num_folds,\n # bal\n # )\n\n\n\n\n\n\n # # different by splice site type\n # if splice_site_type == 'acceptor':\n # cnn_X_train, cnn_y_train = cnn_acc_x, acc_y\n # # same name to preserve for loop structure\n # X_train, y_train = rd_acc_x, acc_y\n # dataset_row_num = network_rows[dataset][0]\n # if splice_site_type == 'donor':\n # cnn_X_train, cnn_y_train = cnn_don_x, don_y\n # X_train, y_train = rd_don_x, don_y\n # dataset_row_num = network_rows[dataset][1]\n #\n #\n # # if tune_rnn:\n # # tune_rnn()\n #\n # # perform cross validation\n # # general\n # trn_fold_accs, trn_fold_losses = [], []\n # val_fold_accs, val_fold_losses = [], []\n # # esplice\n # rnn_va, rnn_vl, cnn_vl, cnn_va, dnn_vl, dnn_va = [],[],[],[],[],[]\n # rnn_ta, rnn_tl, cnn_tl, cnn_ta, dnn_tl, dnn_ta = [],[],[],[],[],[]\n #\n # # this loop inspired by https://www.machinecurve.com/\n # #index.php/2020/02/18/how-to-use-k-fold-cross-validation-with-keras/\n # k_fold = KFold(n_splits=num_folds, shuffle=False)\n # fold = 1\n # for train, test in k_fold.split(X_train, y_train):\n # if model_architecture != 'esplice':\n # X_trn, y_trn = X_train[train], y_train[train]\n # X_val, y_val = X_train[test], y_train[test]\n # if model_architecture=='cnn':\n # history, model = build_cnn(\n # dataset_row_num,\n # summary,\n # X_trn,\n # y_trn,\n # batch_size,\n # epochs,\n # X_val,#becomes X_val\n # y_val,#becomes y_val\n # fold,\n # num_folds\n # )\n # if model_architecture=='dnn':\n # history, model = build_dnn(\n # dataset_row_num,\n # summary,\n # X_trn,\n # y_trn,\n # batch_size,\n # epochs,\n # X_val,#becomes X_val\n # y_val,#becomes y_val\n # fold,\n # num_folds\n # )\n # if model_architecture=='rnn':\n # history, model = build_rnn(\n # dataset_row_num,\n # summary,\n # X_trn,\n # y_trn,\n # batch_size,\n # epochs,\n # X_val,#becomes X_val\n # y_val,#becomes y_val\n # fold,\n # num_folds\n # )\n # # model.predict(X_trn)\n # val_fold_accs.append(history.history['val_accuracy'])\n # val_fold_losses.append(history.history['val_loss'])\n # trn_fold_accs.append(history.history['accuracy'])\n # trn_fold_losses.append(history.history['loss'])\n # fold += 1\n # else:\n # # set up submodel datasets\n # cnn_X_trn, cnn_y_trn = cnn_X_train[train], cnn_y_train[train]\n # cnn_X_val, cnn_y_val = cnn_X_train[test], cnn_y_train[test]\n # rd_X_trn, rd_y_trn = X_train[train], y_train[train]\n # rd_X_val, rd_y_val = X_train[test], y_train[test]\n # # build each submodel\n # hist01, submodel_01 = build_cnn(\n # dataset_row_num,\n # summary,\n # cnn_X_trn,\n # cnn_y_trn,\n # batch_size,\n # epochs,\n # cnn_X_val,\n # cnn_y_val,\n # fold,\n # num_folds\n # )\n # hist02, submodel_02 = build_dnn(\n # dataset_row_num,\n # summary,\n # rd_X_trn,\n # rd_y_trn,\n # batch_size,\n # epochs,\n # rd_X_val,\n # rd_y_val,\n # fold,\n # num_folds\n # )\n # # hist03, submodel_03 = build_rnn(\n # # dataset_row_num,\n # # summary,\n # # rd_X_trn,\n # # rd_y_trn,\n # # batch_size,\n # # epochs,\n # # rd_X_val,\n # # rd_y_val,\n # # fold,\n # # num_folds\n # # )\n # models = [submodel_01, submodel_02]#, submodel_03]\n # trn_scores, val_scores = EnsembleSplice.build(\n # models,\n # batch_size,\n # cnn_X_trn,\n # cnn_y_trn,\n # cnn_X_val,\n # cnn_y_val,\n # rd_X_trn,\n # rd_y_trn,\n # rd_X_val,\n # rd_y_val,\n # )\n # # get final epoch accuracy\n # trn_fold_accs.append(trn_scores)\n # val_fold_accs.append(val_scores)\n # # rnn_va.append(hist03.history['val_accuracy'])\n # # rnn_vl.append(hist03.history['val_loss'])\n # # rnn_ta.append(hist03.history['accuracy'])\n # # rnn_tl.append(hist03.history['loss'])\n # # cnn_vl.append(hist01.history['val_loss'])\n # # cnn_va.append(hist01.history['val_accuracy'])\n # # cnn_tl.append(hist01.history['loss'])\n # # cnn_ta.append(hist01.history['accuracy'])\n # # dnn_vl.append(hist02.history['val_loss'])\n # # dnn_va.append(hist02.history['val_accuracy'])\n # # dnn_tl.append(hist02.history['loss'])\n # # dnn_ta.append(hist02.history['accuracy'])\n #\n # # rnn_va.append(hist03.history['val_accuracy'][-1])\n # # rnn_vl.append(hist03.history['val_loss'][-1])\n # # rnn_ta.append(hist03.history['accuracy'][-1])\n # # rnn_tl.append(hist03.history['loss'][-1])\n # cnn_vl.append(hist01.history['val_loss'][-1])\n # cnn_va.append(hist01.history['val_accuracy'][-1])\n # cnn_tl.append(hist01.history['loss'][-1])\n # cnn_ta.append(hist01.history['accuracy'][-1])\n # dnn_vl.append(hist02.history['val_loss'][-1])\n # dnn_va.append(hist02.history['val_accuracy'][-1])\n # dnn_tl.append(hist02.history['loss'][-1])\n # dnn_ta.append(hist02.history['accuracy'][-1])\n #\n # fold += 1\n #\n # # do something with predicted values and real values to get AUC-ROC scores\n # # sklearn.metrics.roc_auc_score\n # # also get f-score and other scores here\n # # maybe connect tune_rnn and build_rnn -> get tuned parameters and plug them\n # # in automatically to RNN\n #\n # if model_architecture != 'esplice':\n #\n # val_acc_by_epoch = np.apply_along_axis(lambda row: np.mean(row), 1, np.asarray(val_fold_accs).T)\n # val_loss_by_epoch = np.apply_along_axis(lambda row: np.mean(row), 1, np.asarray(val_fold_losses).T)\n # trn_acc_by_epoch = np.apply_along_axis(lambda row: np.mean(row), 1, np.asarray(trn_fold_accs).T)\n # trn_loss_by_epoch = np.apply_along_axis(lambda row: np.mean(row), 1, np.asarray(trn_fold_losses).T)\n #\n # std_val_acc = np.apply_along_axis(lambda row: np.std(row), 1, np.asarray(val_fold_accs).T)\n # std_val_loss = np.apply_along_axis(lambda row: np.std(row), 1, np.asarray(val_fold_losses).T)\n # std_trn_acc = np.apply_along_axis(lambda row: np.std(row), 1, np.asarray(trn_fold_accs).T)\n # std_trn_loss = np.apply_along_axis(lambda row: np.std(row), 1, np.asarray(trn_fold_losses).T)\n #\n # values = [\n # val_acc_by_epoch,\n # std_val_acc,\n # trn_acc_by_epoch,\n # std_trn_acc,\n # val_loss_by_epoch,\n # std_val_loss,\n # trn_loss_by_epoch,\n # std_trn_loss\n # ]\n #\n # if model_architecture == 'esplice':\n #\n # # make a DICTIONARY AREY\n # # ES_Val_ACc: (vacc, std_va)\n # mean_good = lambda seq: np.apply_along_axis(lambda row: np.mean(row), 1, np.asarray(seq).T)\n # std_good = lambda seq: np.apply_along_axis(lambda row: np.std(row), 1, np.asarray(seq).T)\n # vacc = val_fold_accs\n # tacc = trn_fold_accs\n # # std_va = val_fold_accs\n # # std_ta = trn_fold_accs\n #\n # values = [\n # val_fold_accs,\n # trn_fold_accs,\n # #rnn_va,\n # # rnn_vl,\n # #rnn_ta,\n # # rnn_tl,\n # # cnn_vl,\n # cnn_va,\n # # cnn_tl,\n # cnn_ta,\n # # dnn_vl,\n # dnn_va,\n # # dnn_tl,\n # dnn_ta\n # ]\n #\n # # cnn_mva = mean_good(cnn_va)\n # # cnn_mvl = mean_good(cnn_vl)\n # # cnn_mta = mean_good(cnn_ta)\n # # cnn_mtl = mean_good(cnn_tl)\n # # cnn_sva = std_good(cnn_va)\n # # cnn_svl = std_good(cnn_vl)\n # # cnn_sta = std_good(cnn_ta)\n # # cnn_stl = std_good(cnn_tl)\n # #\n # # dnn_mva = mean_good(dnn_va)\n # # dnn_mvl = mean_good(dnn_vl)\n # # dnn_mta = mean_good(dnn_ta)\n # # dnn_mtl = mean_good(dnn_tl)\n # # dnn_sva = std_good(dnn_va)\n # # dnn_svl = std_good(dnn_vl)\n # # dnn_sta = std_good(dnn_ta)\n # # dnn_stl = std_good(dnn_tl)\n # #\n # # rnn_mva = mean_good(rnn_va)\n # # rnn_mvl = mean_good(rnn_vl)\n # # rnn_mta = mean_good(rnn_ta)\n # # rnn_mtl = mean_good(rnn_tl)\n # # rnn_sva = std_good(rnn_va)\n # # rnn_svl = std_good(rnn_vl)\n # # rnn_sta = std_good(rnn_ta)\n # # rnn_stl = std_good(rnn_tl)\n #\n # # values = [\n # # vacc,\n # # # std_va,\n # # tacc,\n # # # std_ta,\n # # cnn_mva,\n # # cnn_sva,\n # # cnn_mvl,\n # # cnn_svl,\n # # cnn_mta,\n # # cnn_sta,\n # # cnn_mtl,\n # # cnn_stl,\n # # dnn_mva,\n # # dnn_sva,\n # # dnn_mvl,\n # # dnn_svl,\n # # dnn_mta,\n # # dnn_sta,\n # # dnn_mtl,\n # # dnn_stl,\n # # rnn_mva,\n # # rnn_sva,\n # # rnn_mvl,\n # # rnn_svl,\n # # rnn_mta,\n # # rnn_sta,\n # # rnn_mtl,\n # # rnn_stl,\n # # ]\n\n # if config:\n # print(model.get_config())\n # if save_model:\n # name = input('What would you like to name this model?: ')\n # model.save(f'{name}')\n # tf.keras.utils.plot_model(model, f'{name}.png', show_shapes=True)\n # if visualize:\n # loss_acc_esplice(\n # values,\n # model_architecture,\n # dataset,\n # splice_site_type,\n # num_folds,\n # epochs,\n # bal,\n # )\n" ]
[ [ "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Conv1D", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.Sequential", "tensorflow.keras.layers.InputLayer", "tensorflow.keras.layers.MaxPooling1D", "tensorflow.keras.regularizers.l2", "tensorflow.keras.layers.LSTM", "tensorflow.keras.layers.Dropout", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.Flatten" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.2" ] } ]
ebartrum/NovelViewSynthesis-TensorFlow
[ "a5e236f3c564bf287c8a09d855fd2134ba86b299" ]
[ "ssim.py" ]
[ "import tensorflow as tf\nimport numpy as np\n\n\ndef _tf_fspecial_gauss(size, sigma, ch=1):\n \"\"\"Function to mimic the 'fspecial' gaussian MATLAB function\n \"\"\"\n x_data, y_data = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]\n\n x_data = np.expand_dims(x_data, axis=-1)\n x_data = np.expand_dims(x_data, axis=-1)\n\n y_data = np.expand_dims(y_data, axis=-1)\n y_data = np.expand_dims(y_data, axis=-1)\n\n x = tf.constant(x_data, dtype=tf.float32)\n y = tf.constant(y_data, dtype=tf.float32)\n\n g = tf.exp(-((x**2 + y**2)/(2.0*sigma**2)))\n g = tf.tile(g, [1, 1, ch, 1])\n\n return g / tf.reduce_sum(g)\n\n\ndef tf_ssim(img1, img2, cs_map=False, mean_metric=True, size=11, sigma=0.5):\n img1 = tf.image.rgb_to_grayscale(img1)\n img2 = tf.image.rgb_to_grayscale(img2)\n window = _tf_fspecial_gauss(size, sigma,\n ch=img1.get_shape().as_list()[-1]) # window shape [size, size]\n K1 = 0.01\n K2 = 0.03\n L = 1 # depth of image (255 in case the image has a differnt scale)\n C1 = (K1*L)**2\n C2 = (K2*L)**2\n mu1 = tf.nn.conv2d(img1, window, strides=[1, 1, 1, 1], padding='VALID')\n mu2 = tf.nn.conv2d(img2, window, strides=[1, 1, 1, 1], padding='VALID')\n mu1_sq = mu1*mu1\n mu2_sq = mu2*mu2\n mu1_mu2 = mu1*mu2\n sigma1_sq = tf.nn.conv2d(img1*img1, window, strides=[1, 1, 1, 1],\n padding='VALID') - mu1_sq\n sigma2_sq = tf.nn.conv2d(img2*img2, window, strides=[1, 1, 1, 1],\n padding='VALID') - mu2_sq\n sigma12 = tf.nn.conv2d(img1*img2, window, strides=[1, 1, 1, 1],\n padding='VALID') - mu1_mu2\n if cs_map:\n value = (\n ((2*mu1_mu2 + C1) * (2*sigma12 + C2)) / (\n (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)\n ), (2.0*sigma12 + C2)/(sigma1_sq + sigma2_sq + C2)\n )\n else:\n value = ((2*mu1_mu2 + C1)*(2*sigma12 + C2)) / (\n (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))\n\n if mean_metric:\n value = tf.reduce_mean(value)\n return value\n\n\ndef tf_ms_ssim(img1, img2, mean_metric=True, level=5):\n weight = tf.constant([0.0448, 0.2856, 0.3001, 0.2363, 0.1333], dtype=tf.float32)\n mssim = []\n mcs = []\n for l in range(level):\n ssim_map, cs_map = tf_ssim(img1, img2, cs_map=True, mean_metric=False)\n mssim.append(tf.reduce_mean(ssim_map))\n mcs.append(tf.reduce_mean(cs_map))\n filtered_im1 = tf.nn.avg_pool(img1, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n filtered_im2 = tf.nn.avg_pool(img2, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n img1 = filtered_im1\n img2 = filtered_im2\n\n # list to tensor of dim D+1\n mssim = tf.pack(mssim, axis=0)\n mcs = tf.pack(mcs, axis=0)\n\n value = (tf.reduce_prod(\n mcs[0:level-1]**weight[0:level-1]) * (mssim[level-1]**weight[level-1]))\n\n if mean_metric:\n value = tf.reduce_mean(value)\n return value\n" ]
[ [ "numpy.expand_dims", "tensorflow.constant", "tensorflow.reduce_mean", "tensorflow.reduce_sum", "tensorflow.exp", "tensorflow.image.rgb_to_grayscale", "tensorflow.reduce_prod", "tensorflow.nn.avg_pool", "tensorflow.pack", "tensorflow.tile", "tensorflow.nn.conv2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
junyuchen245/ViT-V-Net_for_3D_Image_Registration_Pytorch
[ "f43bcdeef1d6712dfcaa3b4e18f69474e1eeaf73" ]
[ "ViT-V-Net/models.py" ]
[ "# coding=utf-8\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport copy\r\nimport logging\r\nimport math\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as nnf\r\nfrom torch.nn import Dropout, Softmax, Linear, Conv3d, LayerNorm\r\nfrom torch.nn.modules.utils import _pair, _triple\r\nimport configs as configs\r\nfrom torch.distributions.normal import Normal\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nATTENTION_Q = \"MultiHeadDotProductAttention_1/query\"\r\nATTENTION_K = \"MultiHeadDotProductAttention_1/key\"\r\nATTENTION_V = \"MultiHeadDotProductAttention_1/value\"\r\nATTENTION_OUT = \"MultiHeadDotProductAttention_1/out\"\r\nFC_0 = \"MlpBlock_3/Dense_0\"\r\nFC_1 = \"MlpBlock_3/Dense_1\"\r\nATTENTION_NORM = \"LayerNorm_0\"\r\nMLP_NORM = \"LayerNorm_2\"\r\n\r\n\r\ndef np2th(weights, conv=False):\r\n \"\"\"Possibly convert HWIO to OIHW.\"\"\"\r\n if conv:\r\n weights = weights.transpose([3, 2, 0, 1])\r\n return torch.from_numpy(weights)\r\n\r\n\r\ndef swish(x):\r\n return x * torch.sigmoid(x)\r\n\r\n\r\nACT2FN = {\"gelu\": torch.nn.functional.gelu, \"relu\": torch.nn.functional.relu, \"swish\": swish}\r\n\r\n\r\nclass Attention(nn.Module):\r\n def __init__(self, config, vis):\r\n super(Attention, self).__init__()\r\n self.vis = vis\r\n self.num_attention_heads = config.transformer[\"num_heads\"]\r\n self.attention_head_size = int(config.hidden_size / self.num_attention_heads)\r\n self.all_head_size = self.num_attention_heads * self.attention_head_size\r\n\r\n self.query = Linear(config.hidden_size, self.all_head_size)\r\n self.key = Linear(config.hidden_size, self.all_head_size)\r\n self.value = Linear(config.hidden_size, self.all_head_size)\r\n\r\n self.out = Linear(config.hidden_size, config.hidden_size)\r\n self.attn_dropout = Dropout(config.transformer[\"attention_dropout_rate\"])\r\n self.proj_dropout = Dropout(config.transformer[\"attention_dropout_rate\"])\r\n\r\n self.softmax = Softmax(dim=-1)\r\n\r\n def transpose_for_scores(self, x):\r\n new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)\r\n x = x.view(*new_x_shape)\r\n return x.permute(0, 2, 1, 3)\r\n\r\n def forward(self, hidden_states):\r\n mixed_query_layer = self.query(hidden_states)\r\n mixed_key_layer = self.key(hidden_states)\r\n mixed_value_layer = self.value(hidden_states)\r\n\r\n query_layer = self.transpose_for_scores(mixed_query_layer)\r\n key_layer = self.transpose_for_scores(mixed_key_layer)\r\n value_layer = self.transpose_for_scores(mixed_value_layer)\r\n\r\n attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))\r\n attention_scores = attention_scores / math.sqrt(self.attention_head_size)\r\n attention_probs = self.softmax(attention_scores)\r\n weights = attention_probs if self.vis else None\r\n attention_probs = self.attn_dropout(attention_probs)\r\n\r\n context_layer = torch.matmul(attention_probs, value_layer)\r\n context_layer = context_layer.permute(0, 2, 1, 3).contiguous()\r\n new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)\r\n context_layer = context_layer.view(*new_context_layer_shape)\r\n attention_output = self.out(context_layer)\r\n attention_output = self.proj_dropout(attention_output)\r\n return attention_output, weights\r\n\r\n\r\nclass Mlp(nn.Module):\r\n def __init__(self, config):\r\n super(Mlp, self).__init__()\r\n self.fc1 = Linear(config.hidden_size, config.transformer[\"mlp_dim\"])\r\n self.fc2 = Linear(config.transformer[\"mlp_dim\"], config.hidden_size)\r\n self.act_fn = ACT2FN[\"gelu\"]\r\n self.dropout = Dropout(config.transformer[\"dropout_rate\"])\r\n\r\n self._init_weights()\r\n\r\n def _init_weights(self):\r\n nn.init.xavier_uniform_(self.fc1.weight)\r\n nn.init.xavier_uniform_(self.fc2.weight)\r\n nn.init.normal_(self.fc1.bias, std=1e-6)\r\n nn.init.normal_(self.fc2.bias, std=1e-6)\r\n\r\n def forward(self, x):\r\n x = self.fc1(x)\r\n x = self.act_fn(x)\r\n x = self.dropout(x)\r\n x = self.fc2(x)\r\n x = self.dropout(x)\r\n return x\r\n\r\n\r\nclass Embeddings(nn.Module):\r\n \"\"\"Construct the embeddings from patch, position embeddings.\r\n \"\"\"\r\n def __init__(self, config, img_size):\r\n super(Embeddings, self).__init__()\r\n self.config = config\r\n down_factor = config.down_factor\r\n patch_size = _triple(config.patches[\"size\"])\r\n n_patches = int((img_size[0]/2**down_factor// patch_size[0]) * (img_size[1]/2**down_factor// patch_size[1]) * (img_size[2]/2**down_factor// patch_size[2]))\r\n self.hybrid_model = CNNEncoder(config, n_channels=2)\r\n in_channels = config['encoder_channels'][-1]\r\n self.patch_embeddings = Conv3d(in_channels=in_channels,\r\n out_channels=config.hidden_size,\r\n kernel_size=patch_size,\r\n stride=patch_size)\r\n self.position_embeddings = nn.Parameter(torch.zeros(1, n_patches, config.hidden_size))\r\n\r\n self.dropout = Dropout(config.transformer[\"dropout_rate\"])\r\n\r\n def forward(self, x):\r\n x, features = self.hybrid_model(x)\r\n x = self.patch_embeddings(x) # (B, hidden. n_patches^(1/2), n_patches^(1/2))\r\n x = x.flatten(2)\r\n x = x.transpose(-1, -2) # (B, n_patches, hidden)\r\n embeddings = x + self.position_embeddings\r\n embeddings = self.dropout(embeddings)\r\n return embeddings, features\r\n\r\n\r\nclass Block(nn.Module):\r\n def __init__(self, config, vis):\r\n super(Block, self).__init__()\r\n self.hidden_size = config.hidden_size\r\n self.attention_norm = LayerNorm(config.hidden_size, eps=1e-6)\r\n self.ffn_norm = LayerNorm(config.hidden_size, eps=1e-6)\r\n self.ffn = Mlp(config)\r\n self.attn = Attention(config, vis)\r\n\r\n def forward(self, x):\r\n h = x\r\n\r\n x = self.attention_norm(x)\r\n x, weights = self.attn(x)\r\n x = x + h\r\n\r\n h = x\r\n x = self.ffn_norm(x)\r\n x = self.ffn(x)\r\n x = x + h\r\n return x, weights\r\n\r\nclass Encoder(nn.Module):\r\n def __init__(self, config, vis):\r\n super(Encoder, self).__init__()\r\n self.vis = vis\r\n self.layer = nn.ModuleList()\r\n self.encoder_norm = LayerNorm(config.hidden_size, eps=1e-6)\r\n for _ in range(config.transformer[\"num_layers\"]):\r\n layer = Block(config, vis)\r\n self.layer.append(copy.deepcopy(layer))\r\n\r\n def forward(self, hidden_states):\r\n attn_weights = []\r\n for layer_block in self.layer:\r\n hidden_states, weights = layer_block(hidden_states)\r\n if self.vis:\r\n attn_weights.append(weights)\r\n encoded = self.encoder_norm(hidden_states)\r\n return encoded, attn_weights\r\n\r\n\r\nclass Transformer(nn.Module):\r\n def __init__(self, config, img_size, vis):\r\n super(Transformer, self).__init__()\r\n self.embeddings = Embeddings(config, img_size=img_size)\r\n self.encoder = Encoder(config, vis)\r\n\r\n def forward(self, input_ids):\r\n embedding_output, features = self.embeddings(input_ids)\r\n encoded, attn_weights = self.encoder(embedding_output) # (B, n_patch, hidden)\r\n return encoded, attn_weights, features\r\n\r\n\r\nclass Conv3dReLU(nn.Sequential):\r\n def __init__(\r\n self,\r\n in_channels,\r\n out_channels,\r\n kernel_size,\r\n padding=0,\r\n stride=1,\r\n use_batchnorm=True,\r\n ):\r\n conv = nn.Conv3d(\r\n in_channels,\r\n out_channels,\r\n kernel_size,\r\n stride=stride,\r\n padding=padding,\r\n bias=not (use_batchnorm),\r\n )\r\n relu = nn.ReLU(inplace=True)\r\n\r\n bn = nn.BatchNorm3d(out_channels)\r\n\r\n super(Conv3dReLU, self).__init__(conv, bn, relu)\r\n\r\n\r\nclass DecoderBlock(nn.Module):\r\n def __init__(\r\n self,\r\n in_channels,\r\n out_channels,\r\n skip_channels=0,\r\n use_batchnorm=True,\r\n ):\r\n super().__init__()\r\n self.conv1 = Conv3dReLU(\r\n in_channels + skip_channels,\r\n out_channels,\r\n kernel_size=3,\r\n padding=1,\r\n use_batchnorm=use_batchnorm,\r\n )\r\n self.conv2 = Conv3dReLU(\r\n out_channels,\r\n out_channels,\r\n kernel_size=3,\r\n padding=1,\r\n use_batchnorm=use_batchnorm,\r\n )\r\n self.up = nn.Upsample(scale_factor=2, mode='trilinear', align_corners=False)\r\n\r\n def forward(self, x, skip=None):\r\n x = self.up(x)\r\n if skip is not None:\r\n x = torch.cat([x, skip], dim=1)\r\n x = self.conv1(x)\r\n x = self.conv2(x)\r\n return x\r\n\r\nclass DecoderCup(nn.Module):\r\n def __init__(self, config, img_size):\r\n super().__init__()\r\n self.config = config\r\n self.down_factor = config.down_factor\r\n head_channels = config.conv_first_channel\r\n self.img_size = img_size\r\n self.conv_more = Conv3dReLU(\r\n config.hidden_size,\r\n head_channels,\r\n kernel_size=3,\r\n padding=1,\r\n use_batchnorm=True,\r\n )\r\n decoder_channels = config.decoder_channels\r\n in_channels = [head_channels] + list(decoder_channels[:-1])\r\n out_channels = decoder_channels\r\n self.patch_size = _triple(config.patches[\"size\"])\r\n skip_channels = self.config.skip_channels\r\n blocks = [\r\n DecoderBlock(in_ch, out_ch, sk_ch) for in_ch, out_ch, sk_ch in zip(in_channels, out_channels, skip_channels)\r\n ]\r\n self.blocks = nn.ModuleList(blocks)\r\n\r\n def forward(self, hidden_states, features=None):\r\n B, n_patch, hidden = hidden_states.size() # reshape from (B, n_patch, hidden) to (B, h, w, hidden)\r\n l, h, w = (self.img_size[0]//2**self.down_factor//self.patch_size[0]), (self.img_size[1]//2**self.down_factor//self.patch_size[1]), (self.img_size[2]//2**self.down_factor//self.patch_size[2])\r\n x = hidden_states.permute(0, 2, 1)\r\n x = x.contiguous().view(B, hidden, l, h, w)\r\n x = self.conv_more(x)\r\n for i, decoder_block in enumerate(self.blocks):\r\n if features is not None:\r\n skip = features[i] if (i < self.config.n_skip) else None\r\n #print(skip.shape)\r\n else:\r\n skip = None\r\n x = decoder_block(x, skip=skip)\r\n return x\r\n\r\nclass SpatialTransformer(nn.Module):\r\n \"\"\"\r\n N-D Spatial Transformer\r\n\r\n Obtained from https://github.com/voxelmorph/voxelmorph\r\n \"\"\"\r\n\r\n def __init__(self, size, mode='bilinear'):\r\n super().__init__()\r\n\r\n self.mode = mode\r\n\r\n # create sampling grid\r\n vectors = [torch.arange(0, s) for s in size]\r\n grids = torch.meshgrid(vectors)\r\n grid = torch.stack(grids)\r\n grid = torch.unsqueeze(grid, 0)\r\n grid = grid.type(torch.FloatTensor)\r\n\r\n # registering the grid as a buffer cleanly moves it to the GPU, but it also\r\n # adds it to the state dict. this is annoying since everything in the state dict\r\n # is included when saving weights to disk, so the model files are way bigger\r\n # than they need to be. so far, there does not appear to be an elegant solution.\r\n # see: https://discuss.pytorch.org/t/how-to-register-buffer-without-polluting-state-dict\r\n self.register_buffer('grid', grid)\r\n\r\n def forward(self, src, flow):\r\n # new locations\r\n new_locs = self.grid + flow\r\n shape = flow.shape[2:]\r\n\r\n # need to normalize grid values to [-1, 1] for resampler\r\n for i in range(len(shape)):\r\n new_locs[:, i, ...] = 2 * (new_locs[:, i, ...] / (shape[i] - 1) - 0.5)\r\n\r\n # move channels dim to last position\r\n # also not sure why, but the channels need to be reversed\r\n if len(shape) == 2:\r\n new_locs = new_locs.permute(0, 2, 3, 1)\r\n new_locs = new_locs[..., [1, 0]]\r\n elif len(shape) == 3:\r\n new_locs = new_locs.permute(0, 2, 3, 4, 1)\r\n new_locs = new_locs[..., [2, 1, 0]]\r\n\r\n return nnf.grid_sample(src, new_locs, align_corners=True, mode=self.mode)\r\n\r\nclass DoubleConv(nn.Module):\r\n \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\r\n\r\n def __init__(self, in_channels, out_channels, mid_channels=None):\r\n super().__init__()\r\n if not mid_channels:\r\n mid_channels = out_channels\r\n self.double_conv = nn.Sequential(\r\n nn.Conv3d(in_channels, mid_channels, kernel_size=3, padding=1),\r\n nn.ReLU(inplace=True),\r\n nn.Conv3d(mid_channels, out_channels, kernel_size=3, padding=1),\r\n nn.ReLU(inplace=True)\r\n )\r\n\r\n def forward(self, x):\r\n return self.double_conv(x)\r\n\r\n\r\nclass Down(nn.Module):\r\n \"\"\"Downscaling with maxpool then double conv\"\"\"\r\n\r\n def __init__(self, in_channels, out_channels):\r\n super().__init__()\r\n self.maxpool_conv = nn.Sequential(\r\n nn.MaxPool3d(2),\r\n DoubleConv(in_channels, out_channels)\r\n )\r\n\r\n def forward(self, x):\r\n return self.maxpool_conv(x)\r\n\r\nclass CNNEncoder(nn.Module):\r\n def __init__(self, config, n_channels=2):\r\n super(CNNEncoder, self).__init__()\r\n self.n_channels = n_channels\r\n decoder_channels = config.decoder_channels\r\n encoder_channels = config.encoder_channels\r\n self.down_num = config.down_num\r\n self.inc = DoubleConv(n_channels, encoder_channels[0])\r\n self.down1 = Down(encoder_channels[0], encoder_channels[1])\r\n self.down2 = Down(encoder_channels[1], encoder_channels[2])\r\n self.width = encoder_channels[-1]\r\n def forward(self, x):\r\n features = []\r\n x1 = self.inc(x)\r\n features.append(x1)\r\n x2 = self.down1(x1)\r\n features.append(x2)\r\n feats = self.down2(x2)\r\n features.append(feats)\r\n feats_down = feats\r\n for i in range(self.down_num):\r\n feats_down = nn.MaxPool3d(2)(feats_down)\r\n features.append(feats_down)\r\n return feats, features[::-1]\r\n\r\nclass RegistrationHead(nn.Sequential):\r\n def __init__(self, in_channels, out_channels, kernel_size=3, upsampling=1):\r\n conv3d = nn.Conv3d(in_channels, out_channels, kernel_size=kernel_size, padding=kernel_size // 2)\r\n conv3d.weight = nn.Parameter(Normal(0, 1e-5).sample(conv3d.weight.shape))\r\n conv3d.bias = nn.Parameter(torch.zeros(conv3d.bias.shape))\r\n super().__init__(conv3d)\r\n\r\nclass ViTVNet(nn.Module):\r\n def __init__(self, config, img_size=(64, 256, 256), int_steps=7, vis=False):\r\n super(ViTVNet, self).__init__()\r\n self.transformer = Transformer(config, img_size, vis)\r\n self.decoder = DecoderCup(config, img_size)\r\n self.reg_head = RegistrationHead(\r\n in_channels=config.decoder_channels[-1],\r\n out_channels=config['n_dims'],\r\n kernel_size=3,\r\n )\r\n self.spatial_trans = SpatialTransformer(img_size)\r\n self.config = config\r\n #self.integrate = VecInt(img_size, int_steps)\r\n def forward(self, x):\r\n\r\n source = x[:,0:1,:,:]\r\n\r\n x, attn_weights, features = self.transformer(x) # (B, n_patch, hidden)\r\n x = self.decoder(x, features)\r\n flow = self.reg_head(x)\r\n #flow = self.integrate(flow)\r\n out = self.spatial_trans(source, flow)\r\n return out, flow\r\n\r\nclass VecInt(nn.Module):\r\n \"\"\"\r\n Integrates a vector field via scaling and squaring.\r\n\r\n Obtained from https://github.com/voxelmorph/voxelmorph\r\n \"\"\"\r\n\r\n def __init__(self, inshape, nsteps):\r\n super().__init__()\r\n\r\n assert nsteps >= 0, 'nsteps should be >= 0, found: %d' % nsteps\r\n self.nsteps = nsteps\r\n self.scale = 1.0 / (2 ** self.nsteps)\r\n self.transformer = SpatialTransformer(inshape)\r\n\r\n def forward(self, vec):\r\n vec = vec * self.scale\r\n for _ in range(self.nsteps):\r\n vec = vec + self.transformer(vec, vec)\r\n return vec\r\n\r\nCONFIGS = {\r\n 'ViT-V-Net': configs.get_3DReg_config(),\r\n}\r\n" ]
[ [ "torch.nn.Softmax", "torch.zeros", "torch.cat", "torch.distributions.normal.Normal", "torch.nn.Dropout", "torch.from_numpy", "torch.arange", "torch.sigmoid", "torch.nn.ModuleList", "torch.unsqueeze", "torch.nn.Linear", "torch.nn.Conv3d", "torch.nn.init.normal_", "torch.stack", "torch.nn.modules.utils._triple", "torch.nn.LayerNorm", "torch.matmul", "torch.nn.MaxPool3d", "torch.nn.Upsample", "torch.nn.functional.grid_sample", "torch.nn.init.xavier_uniform_", "torch.nn.ReLU", "torch.meshgrid", "torch.nn.BatchNorm3d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Geson-anko/JARVIS3
[ "bc599a352401a7e135ebaabead4d8e6d8835747e", "bc599a352401a7e135ebaabead4d8e6d8835747e" ]
[ "_Sensation0/DeltaTime.py", "Sensation1/sensation_models.py" ]
[ "import os\nimport torch\nimport os\nimport random\nfrom torch.nn import(\n Module,Linear,LayerNorm\n)\nimport math\nfrom .AutoEncoder import Encoder\n\nclass DeltaT(Module):\n def __init__(self):\n super().__init__()\n self.reset_seed()\n self.elem = math.prod(Encoder().output_size)\n self.input_size = (1,self.elem)\n self.output_size = (1,1)\n\n ## Model layers\n self.dense1 = Linear(self.elem,512)\n self.norm1= LayerNorm(512)\n self.dense2 = Linear(512,256)\n self.norm2 = LayerNorm(256)\n self.dense3 = Linear(256,1)\n \n def forward(self,x1,x2):\n #x1,x2 = x1.unsqueeze(1),x2.unsqueeze(1)\n #x = torch.cat([x1,x2],dim=1)\n x = x1 - x2\n x = torch.relu(self.norm1(self.dense1(x)))\n x = x.view(x.size(0),-1)\n x = torch.relu(self.norm2(self.dense2(x)))\n x = torch.relu(self.dense3(x))\n return x\n\n def reset_seed(self,seed=0):\n os.environ['PYTHONHASHSEED'] = '0'\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n\nif __name__ == '__main__':\n from torchsummaryX import summary\n model = DeltaT()\n dummy = torch.randn(model.input_size)\n print(summary(model,dummy,dummy))", "import torch\nfrom torch.nn import (\n Conv2d,BatchNorm2d,MaxPool2d,#AvgPool2d,\n ConvTranspose2d,Upsample,\n Linear,LayerNorm,\n Module, \n)\nimport os\nimport random\nfrom .config import config\n\nfrom typing import Union,Tuple\n\nclass ResBlock2d(torch.nn.Module):\n def __init__(\n self,in_channels:int,out_channels:int,\n kernel_size_1st:Union[int,Tuple[int,int]],kernel_size_2nd:Union[int,Tuple[int,int]]) -> None:\n super().__init__()\n\n f_ch = int(out_channels//2)\n self.convf = Conv2d(in_channels,f_ch,kernel_size=kernel_size_1st)\n self.normf = BatchNorm2d(f_ch)\n self.pool = MaxPool2d(2)\n \n # fork1\n self.conv_ch = Conv2d(f_ch,out_channels,1)\n self.norm_ch = BatchNorm2d(out_channels)\n\n # fork2\n pad = torch.floor(torch.tensor(kernel_size_2nd)/2).type(torch.long)\n if pad.dim() == 0:\n pad = int(pad)\n else:\n pad = tuple(pad)\n s_ch = int(out_channels//4)\n self.conv_rc1 = Conv2d(f_ch,s_ch,1)\n self.norm_rc1 = BatchNorm2d(s_ch)\n self.conv_r = Conv2d(s_ch,s_ch,kernel_size_2nd,padding=pad)\n self.norm_r = BatchNorm2d(s_ch)\n self.conv_rc2 = Conv2d(s_ch,out_channels,1)\n self.norm_rc2 = BatchNorm2d(out_channels)\n\n self.norm = BatchNorm2d(out_channels)\n\n def forward(self,x):\n x = self.normf(self.convf(x))\n x = torch.relu(x)\n x = self.pool(x)\n\n # fork1\n x1 = self.norm_ch(self.conv_ch(x))\n\n # fork2\n x2 = self.norm_rc1(self.conv_rc1(x))\n x2 = torch.relu(x2)\n x2 = self.norm_r(self.conv_r(x2)) \n x2 = torch.relu(x2)\n x2 = self.norm_rc2(self.conv_rc2(x2))\n \n # merge\n x = self.norm(torch.add(x1,x2))\n x = torch.relu(x)\n\n return x\n\nclass InverseBlock2d(Module):\n def __init__(\n self,in_channels:int,out_channels:int,\n kernel_size_1st:Union[int,Tuple[int,int]],kernel_size_2nd:Union[int,Tuple[int,int]]) -> None:\n super().__init__()\n \n self.upsampler = Upsample(scale_factor=2)\n self.Dcon1 = ConvTranspose2d(in_channels,out_channels,kernel_size_1st)\n self.norm1 = BatchNorm2d(out_channels)\n self.Dcon2 = ConvTranspose2d(out_channels,out_channels,kernel_size_2nd)\n self.norm2 = BatchNorm2d(out_channels)\n \n def forward(self,x):\n x = torch.relu(self.norm1(self.Dcon1(x)))\n x = self.upsampler(x)\n x = self.norm2(self.Dcon2(x))\n return x \nclass Encoder(Module):\n input_size = (1,config.channels,config.width,config.height) # input size\n output_size = (1,256,7,3) # output size\n def __init__(self):\n super().__init__()\n self.reset_seed()\n\n # Model layers\n self.Conv1 = ResBlock2d(config.channels,8,9,5)\n self.Conv2 = ResBlock2d(8,16,7,3)\n self.Conv3 = ResBlock2d(16,32,3,3)\n self.Conv4 = ResBlock2d(32,64,3,3)\n self.Conv5 = ResBlock2d(64,128,3,3)\n self.Conv6 = ResBlock2d(128,256,3,3)\n self.outconv = Conv2d(256,256,1,1)\n\n def forward(self,x):\n x = x.view(-1,config.channels,config.width,config.height)\n #x = self.pool(x)\n x = self.Conv1(x)\n x = self.Conv2(x)\n x = self.Conv3(x)\n x = self.Conv4(x)\n x = self.Conv5(x)\n x = self.Conv6(x)\n x = torch.tanh(self.outconv(x))\n return x\n\n def reset_seed(self,seed=0):\n os.environ['PYTHONHASHSEED'] = '0'\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n \nclass Decoder(Module):\n input_size = Encoder.output_size\n output_size = Encoder.input_size\n insize = (-1,) + input_size[1:]\n def __init__(self):\n super().__init__()\n self.reset_seed()\n \n # Model layers\n self.Dcon1 = InverseBlock2d(256,128,(7,3),5)\n self.Dcon2 = InverseBlock2d(128,64,(6,5),3)\n self.Dcon3 = InverseBlock2d(64,32,3,3)\n self.Dcon4 = InverseBlock2d(32,16,3,(7,5))\n self.Dcon5 = InverseBlock2d(16,3,7,(9,5))\n\n def forward(self,x):\n x = x.view(self.insize)\n x = self.Dcon1(x)\n x = torch.relu(x)\n x = self.Dcon2(x)\n x = torch.relu(x)\n x = self.Dcon3(x)\n x = torch.relu(x)\n x = self.Dcon4(x)\n x = torch.relu(x)\n x = self.Dcon5(x)\n x = torch.sigmoid(x) \n\n return x\n\n\n def reset_seed(self,seed=0):\n os.environ['PYTHONHASHSEED'] = '0'\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n\nclass AutoEncoder(Module):\n def __init__(self):\n \"\"\"\n This class is used training only. \n How about using it like this?\n >>> model = AutoEncoder()\n >>> # -- Training Model Process --\n >>> torch.save(model.encoder.state_dict(),encoder_name)\n >>> torch.save(model.decoder.state_dict(),decoder_name)\n \"\"\"\n super().__init__()\n self.encoder = Encoder()\n self.decoder = Decoder()\n \n def forward(self,x):\n x = self.encoder(x)\n x = self.decoder(x)\n return x\n \nif __name__ == '__main__':\n from torchsummaryX import summary\n model = AutoEncoder()\n dummy = torch.randn(model.encoder.input_size)\n print(summary(model.encoder,dummy))\n\"\"\" Documentation\n\n\n\"\"\"" ]
[ [ "torch.cuda.manual_seed", "torch.randn", "torch.manual_seed", "torch.nn.LayerNorm", "torch.nn.Linear" ], [ "torch.sigmoid", "torch.add", "torch.nn.ConvTranspose2d", "torch.cuda.manual_seed", "torch.randn", "torch.manual_seed", "torch.nn.Conv2d", "torch.tensor", "torch.nn.MaxPool2d", "torch.relu", "torch.nn.Upsample", "torch.nn.BatchNorm2d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
soybase/DroneImageScripts
[ "c077325a868237569592bd3820b3d873eddb4f83", "c077325a868237569592bd3820b3d873eddb4f83" ]
[ "CNN/CNNProcessData.py", "CNN/MaskRCNNBoundingBoxPredict.py" ]
[ "# import the necessary packages\nimport sys\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.layers import BatchNormalization\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.layers import Conv2DTranspose\nfrom tensorflow.keras.layers import LeakyReLU\nfrom tensorflow.keras.layers import Activation\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.layers import Reshape\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import Input\nfrom tensorflow.keras import Model\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\n\nclass CNNProcessData:\n def __init__(self):\n pass\n\n def get_imagedatagenerator(self):\n datagen = ImageDataGenerator(\n featurewise_center=True,\n featurewise_std_normalization=True,\n #rotation_range=20,\n #width_shift_range=0.05,\n #height_shift_range=0.05,\n #horizontal_flip=True,\n # vertical_flip=True,\n #brightness_range=[0.8,1.2]\n )\n return datagen\n\n def generate_croppings(self, testX, testY, image_size, number):\n if number != 11:\n raise Exception(\"Only implemented for number = 11 right now\")\n\n augmented_testX_1 = []\n augmented_testX_2 = []\n augmented_testX_3 = []\n augmented_testX_4 = []\n augmented_testX_5 = []\n augmented_testX_6 = []\n augmented_testX_7 = []\n augmented_testX_8 = []\n augmented_testX_9 = []\n augmented_testX_10 = []\n augmented_testX_11 = []\n mid_image_size = int(round(image_size/2))\n for img in testX:\n height = img.shape[0]\n small_height = int(round(height*0.1))\n mid_height = int(round(height/2))\n width = img.shape[1]\n mid_width = int(round(width/2))\n crop_img1 = img[height-image_size:height, 0:image_size]\n crop_img2 = img[height-image_size:height, width-image_size:width]\n crop_img3 = img[0:image_size, width-image_size:width]\n crop_img4 = img[0:image_size, 0:image_size]\n crop_img5 = img[mid_height-mid_image_size:mid_height+mid_image_size, mid_width-mid_image_size:mid_width+mid_image_size]\n crop_img6 = img[mid_height-mid_image_size:mid_height+mid_image_size, 0:image_size]\n crop_img7 = img[mid_height-mid_image_size:mid_height+mid_image_size, width-image_size:width]\n crop_img8 = img[mid_height+small_height-mid_image_size:mid_height+small_height+mid_image_size, 0:image_size]\n crop_img9 = img[mid_height+small_height-mid_image_size:mid_height+small_height+mid_image_size, width-image_size:width]\n crop_img10 = img[mid_height-small_height-mid_image_size:mid_height-small_height+mid_image_size, 0:image_size]\n crop_img11 = img[mid_height-small_height-mid_image_size:mid_height-small_height+mid_image_size, width-image_size:width]\n augmented_testX_1.append(crop_img1)\n augmented_testX_2.append(crop_img2)\n augmented_testX_3.append(crop_img3)\n augmented_testX_4.append(crop_img4)\n augmented_testX_5.append(crop_img5)\n augmented_testX_6.append(crop_img6)\n augmented_testX_7.append(crop_img7)\n augmented_testX_8.append(crop_img8)\n augmented_testX_9.append(crop_img9)\n augmented_testX_10.append(crop_img10)\n augmented_testX_11.append(crop_img11)\n\n augmented_testX_1 = np.array(augmented_testX_1)\n augmented_testX_2 = np.array(augmented_testX_2)\n augmented_testX_3 = np.array(augmented_testX_3)\n augmented_testX_4 = np.array(augmented_testX_4)\n augmented_testX_5 = np.array(augmented_testX_5)\n augmented_testX_6 = np.array(augmented_testX_6)\n augmented_testX_7 = np.array(augmented_testX_7)\n augmented_testX_8 = np.array(augmented_testX_8)\n augmented_testX_9 = np.array(augmented_testX_9)\n augmented_testX_10 = np.array(augmented_testX_10)\n augmented_testX_11 = np.array(augmented_testX_11)\n testX = np.concatenate((augmented_testX_1, augmented_testX_2, augmented_testX_3, augmented_testX_4, augmented_testX_5, augmented_testX_6, augmented_testX_7, augmented_testX_8, augmented_testX_9, augmented_testX_10, augmented_testX_11))\n # testXflipped = []\n # for img in testX:\n # horizontal_flip = cv2.flip( img, 0 )\n # testXflipped.append(horizontal_flip)\n # testXflipped = np.array(testXflipped)\n # testX = np.concatenate((testX, testXflipped))\n testY = np.repeat(testY, number)\n return (testX, testY)\n\n def create_montages(self, images, montage_image_number, image_size, full_montage_image_size):\n output = []\n if montage_image_number == 4:\n data = images.reshape(int(len(images)/montage_image_number), montage_image_number, image_size, image_size, 3)\n\n for iter in range(len(data)):\n img_set = data[iter]\n outputImage = np.zeros((full_montage_image_size, full_montage_image_size, 3))\n outputImage[0:image_size, 0:image_size, :] = img_set[0]\n outputImage[0:image_size, image_size:2*image_size, :] = img_set[1]\n outputImage[image_size:2*image_size, 0:image_size, :] = img_set[2]\n outputImage[image_size:2*image_size, image_size:2*image_size, :] = img_set[3]\n\n # cv2.imshow(\"Result\", outputImage)\n # cv2.waitKey(0)\n # raise Exception('Exit')\n\n output.append(outputImage)\n else:\n raise Exception('Only implemented to montage 4 images into one image')\n\n return np.array(output)\n\n def process_cnn_data(self, images, aux_data, num_unique_stock_ids, num_unique_image_types, num_unique_time_days, image_size, keras_model_type, data_augmentation, data_augmentation_test, montage_image_number, full_montage_image_size, output_autoencoder_model_file_path, log_file_path):\n\n if log_file_path is not None:\n sys.stderr = open(log_file_path, 'a')\n\n def eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n trainX = []\n testX = []\n trainY = []\n testY = []\n\n datagen = self.get_imagedatagenerator()\n\n datagen.fit(images)\n images = datagen.standardize(images)\n\n aux_data[\"value\"] = aux_data[\"value\"].astype(float)\n output_image_file = aux_data[\"output_image_file\"].tolist()\n\n # LSTM models group images by time, but are still ties to a single label e.g. X, Y = [img_t1, img_t2, img_t3], y1.\n if keras_model_type == 'densenet121_lstm_imagenet':\n images = images.reshape(num_unique_stock_ids * num_unique_image_types, num_unique_time_days, input_image_size, input_image_size, 3)\n\n (train_aux_data, test_aux_data, train_images, test_images) = train_test_split(aux_data, images, test_size=0.2)\n trainX_length = len(train_images) \n testX_length = len(test_images)\n train_images = train_images.reshape(trainX_length * num_unique_time_days, input_image_size, input_image_size, 3)\n test_images = test_images.reshape(testX_length * num_unique_time_days, input_image_size, input_image_size, 3)\n trainX_length_flat = len(train_images)\n\n test_images = datagen.standardize(test_images)\n\n # (testX, testY) = self.generate_croppings(testX, testY, image_size, data_augmentation_test)\n testX_resized = []\n for img in test_images:\n testX_resized.append(cv2.resize(img, (image_size, image_size)))\n test_images = np.array(testX_resized)\n\n test_images = test_images.reshape(data_augmentation_test * testX_length, num_unique_time_days, image_size, image_size, 3)\n\n # trainX_aug = []\n # trainY_aug = []\n # augmented = datagen.flow(train_images, train_aux_data, batch_size=trainX_length_flat)\n # for i in range(0, data_augmentation):\n # X, y = augmented.next()\n # if len(trainX_aug) == 0:\n # trainX_aug = X\n # trainY_aug = y\n # else:\n # trainX_aug = np.concatenate((trainX_aug, X))\n # trainY_aug = np.concatenate((trainY_aug, y))\n # \n # trainX = trainX_aug\n # trainY = trainY_aug\n\n trainX_resized = []\n for img in train_images:\n trainX_resized.append(cv2.resize(img, (image_size, image_size)))\n train_images = np.array(trainX_resized)\n\n train_images = train_images.reshape(data_augmentation * trainX_length, num_unique_time_days, image_size, image_size, 3)\n else:\n images = self.create_montages(images, montage_image_number, image_size, full_montage_image_size)\n\n (encoder, decoder, autoencoder) = self.build_autoencoder(full_montage_image_size, full_montage_image_size, 3)\n opt = Adam(lr=1e-3)\n autoencoder.compile(loss=\"mse\", optimizer=opt)\n\n (train_aux_data, test_aux_data, train_images, test_images) = train_test_split(aux_data, images, test_size=0.2)\n\n checkpoint = ModelCheckpoint(filepath=output_autoencoder_model_file_path, monitor='loss', verbose=1, save_best_only=True, mode='min', save_frequency=1, save_weights_only=False)\n callbacks_list = [checkpoint]\n\n # train the convolutional autoencoder\n H = autoencoder.fit(\n train_images, train_images,\n validation_data=(test_images, test_images),\n epochs=25,\n batch_size=32,\n callbacks=callbacks_list\n )\n decoded = autoencoder.predict(images)\n\n output_image_counter = 0\n for image in decoded:\n cv2.imwrite(output_image_file[output_image_counter], image*255)\n output_image_counter += 1\n\n (train_aux_data, test_aux_data, train_images, test_images) = train_test_split(aux_data, decoded, test_size=0.2)\n # testY_length = len(testY)\n\n # (testX, testY) = self.generate_croppings(testX, testY, image_size, data_augmentation_test)\n # testY = testY.reshape(data_augmentation_test * testY_length, 1)\n\n # augmented = datagen.flow(trainX, trainY, batch_size=len(trainX))\n # for i in range(0, data_augmentation):\n # X, y = augmented.next()\n\n stock_id_binarizer = LabelBinarizer().fit(aux_data[\"stock_id\"])\n train_stock_id_categorical = stock_id_binarizer.transform(train_aux_data[\"stock_id\"])\n test_stock_id_categorical = stock_id_binarizer.transform(test_aux_data[\"stock_id\"])\n\n accession_id_binarizer = LabelBinarizer().fit(aux_data[\"accession_id\"])\n train_accession_id_categorical = accession_id_binarizer.transform(train_aux_data[\"accession_id\"])\n test_accession_id_categorical = accession_id_binarizer.transform(test_aux_data[\"accession_id\"])\n\n female_id_binarizer = LabelBinarizer().fit(aux_data[\"female_id\"])\n train_female_id_categorical = female_id_binarizer.transform(train_aux_data[\"female_id\"])\n test_female_id_categorical = female_id_binarizer.transform(test_aux_data[\"female_id\"])\n\n male_id_binarizer = LabelBinarizer().fit(aux_data[\"male_id\"])\n train_male_id_categorical = male_id_binarizer.transform(train_aux_data[\"male_id\"])\n test_male_id_categorical = male_id_binarizer.transform(test_aux_data[\"male_id\"])\n\n continuous = [col for col in aux_data.columns if 'aux_trait_' in col]\n cs = MinMaxScaler()\n if len(continuous) > 0:\n trainContinuous = cs.fit_transform(train_aux_data[continuous])\n testContinuous = cs.transform(test_aux_data[continuous])\n\n #trainX = np.hstack((train_stock_id_categorical, train_accession_id_categorical, train_female_id_categorical, train_male_id_categorical, trainContinuous))\n #testX = np.hstack((test_stock_id_categorical, test_accession_id_categorical, test_female_id_categorical, test_male_id_categorical, testContinuous))\n trainX = trainContinuous\n testX = testContinuous\n else:\n trainX = []\n testX = []\n trainx = np.array(trainX)\n testx = np.array(testX)\n\n max_label = aux_data[\"value\"].max()\n trainY = train_aux_data[\"value\"]/max_label\n testY = test_aux_data[\"value\"]/max_label\n\n train_genotype_files = train_aux_data[\"genotype_file\"].tolist()\n test_genotype_files = test_aux_data[\"genotype_file\"].tolist()\n train_genotype_data = []\n for f in train_genotype_files:\n if log_file_path is not None:\n eprint(f)\n else:\n print(f)\n if pd.isna(f) is False:\n geno_data = pd.read_csv(f, sep=\"\\t\", header=None, na_values=\"NA\")\n train_genotype_data.append(np.array(geno_data.iloc[:,0]))\n test_genotype_data = []\n for f in test_genotype_files:\n if log_file_path is not None:\n eprint(f)\n else:\n print(f)\n if pd.isna(f) is False:\n geno_data = pd.read_csv(f, sep=\"\\t\", header=None, na_values=\"NA\")\n test_genotype_data.append(np.array(geno_data.iloc[:,0]))\n\n train_genotype_data = np.array(train_genotype_data)\n test_genotype_data = np.array(test_genotype_data)\n eprint(train_genotype_data)\n eprint(testX)\n eprint(trainX)\n\n return (test_images, np.array(testX), testY.to_numpy(), test_genotype_data, train_images, np.array(trainX), trainY.to_numpy(), train_genotype_data)\n\n def process_cnn_data_predictions(self, data, aux_data, num_unique_stock_ids, num_unique_image_types, num_unique_time_days, image_size, keras_model_type, input_autoencoder_model_file_path, training_data, data_augmentation_test, montage_image_number, full_montage_image_size):\n trainX = []\n testX = []\n trainY = []\n testY = []\n\n datagen = self.get_imagedatagenerator()\n datagen.fit(training_data)\n data = datagen.standardize(data)\n\n output_image_file = aux_data[\"output_image_file\"].tolist()\n\n data = self.create_montages(data, montage_image_number, image_size, full_montage_image_size)\n\n autoencoder_model = load_model(input_autoencoder_model_file_path)\n data = autoencoder_model.predict(data)\n\n #ret = self.generate_croppings(data, None, image_size, data_augmentation_test)\n #augmented_data = ret[0]\n\n # LSTM models group images by time, but are still ties to a single label e.g. X, Y = [img_t1, img_t2, img_t3], y1.\n if keras_model_type == 'KerasCNNLSTMDenseNet121ImageNetWeights':\n data = data.reshape(data_augmentation_test * num_unique_stock_ids * num_unique_image_types, num_unique_time_days, image_size, image_size, 3)\n\n output_image_counter = 0\n for image in data:\n cv2.imwrite(output_image_file[output_image_counter], image*255)\n output_image_counter += 1\n\n stock_id_binarizer = LabelBinarizer().fit(aux_data[\"stock_id\"])\n stock_id_categorical = stock_id_binarizer.transform(aux_data[\"stock_id\"])\n\n accession_id_binarizer = LabelBinarizer().fit(aux_data[\"accession_id\"])\n accession_id_categorical = accession_id_binarizer.transform(aux_data[\"accession_id\"])\n\n female_id_binarizer = LabelBinarizer().fit(aux_data[\"female_id\"])\n female_id_categorical = female_id_binarizer.transform(aux_data[\"female_id\"])\n\n male_id_binarizer = LabelBinarizer().fit(aux_data[\"male_id\"])\n male_id_categorical = male_id_binarizer.transform(aux_data[\"male_id\"])\n\n continuous = [col for col in aux_data.columns if 'aux_trait_' in col]\n cs = MinMaxScaler()\n if len(continuous) > 0:\n fitContinuous = cs.fit_transform(aux_data[continuous])\n\n # fitX = np.hstack([stock_id_categorical, accession_id_categorical, female_id_categorical, male_id_categorical, fitContinuous])\n fitX = fitContinuous\n else:\n # fitX = np.hstack([stock_id_categorical, accession_id_categorical, female_id_categorical, male_id_categorical])\n fitX = []\n fitX = np.array(fitX)\n\n max_label = aux_data[\"value\"].max()\n fitY = aux_data[\"value\"]/max_label\n\n genotype_files = aux_data[\"genotype_file\"].tolist()\n genotype_data = []\n for f in genotype_files:\n if pd.isna(f) is False:\n geno_data = pd.read_csv(f, sep=\"\\t\", header=None, na_values=\"NA\")\n genotype_data.append(np.array(geno_data.iloc[:,0]))\n\n genotype_data = np.array(genotype_data)\n\n return (data, fitX, genotype_data, fitY.to_numpy())\n\n def build_autoencoder(self, width, height, depth, filters=(32, 64), latentDim=16):\n inputShape = (height, width, depth)\n chanDim = -1\n\n # define the input to the encoder\n inputs = Input(shape=inputShape)\n x = inputs\n\n # loop over the number of filters\n for f in filters:\n # apply a CONV => RELU => BN operation\n x = Conv2D(f, (3, 3), strides=2, padding=\"same\")(x)\n x = LeakyReLU(alpha=0.2)(x)\n x = BatchNormalization(axis=chanDim)(x)\n\n # flatten the network and then construct our latent vector\n volumeSize = K.int_shape(x)\n x = Flatten()(x)\n latent = Dense(latentDim)(x)\n\n # build the encoder model\n encoder = Model(inputs, latent, name=\"encoder\")\n\n # start building the decoder model which will accept the\n # output of the encoder as its inputs\n latentInputs = Input(shape=(latentDim,))\n x = Dense(np.prod(volumeSize[1:]))(latentInputs)\n x = Reshape((volumeSize[1], volumeSize[2], volumeSize[3]))(x)\n\n # loop over our number of filters again, but this time in\n # reverse order\n for f in filters[::-1]:\n # apply a CONV_TRANSPOSE => RELU => BN operation\n x = Conv2DTranspose(f, (3, 3), strides=2, padding=\"same\")(x)\n x = LeakyReLU(alpha=0.2)(x)\n x = BatchNormalization(axis=chanDim)(x)\n\n # apply a single CONV_TRANSPOSE layer used to recover the\n # original depth of the image\n x = Conv2DTranspose(depth, (3, 3), padding=\"same\")(x)\n outputs = Activation(\"sigmoid\")(x)\n\n # build the decoder model\n decoder = Model(latentInputs, outputs, name=\"decoder\")\n\n # our autoencoder is the encoder + decoder\n autoencoder = Model(inputs, decoder(encoder(inputs)), name=\"autoencoder\")\n\n # return a 3-tuple of the encoder, decoder, and autoencoder\n return (encoder, decoder, autoencoder)\n", "\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\nimport sys\nimport argparse\nimport cv2\nimport csv\nfrom os import listdir\nfrom xml.etree import ElementTree\nfrom numpy import zeros\nfrom numpy import asarray\nfrom numpy import expand_dims\nfrom matplotlib import pyplot\nfrom matplotlib.patches import Rectangle\nfrom mrcnn.config import Config\nfrom mrcnn.model import MaskRCNN\nfrom mrcnn.model import mold_image\nfrom mrcnn.utils import Dataset\nimport matplotlib.backends.backend_pdf\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-l\", \"--log_file_path\", required=False, help=\"file path to write log to. useful for using from the web interface\")\nap.add_argument(\"-i\", \"--input_annotations_dir\", required=True, help=\"file directory holding all annotation xml files\")\nap.add_argument(\"-p\", \"--model_dir\", required=True, help=\"dir where to save checkpoints\")\nap.add_argument(\"-o\", \"--model_path\", required=True, help=\"file where to save trained model\")\nap.add_argument(\"-e\", \"--outfile_annotated\", required=True, help=\"file path where the annotated image pdf saved\")\nap.add_argument(\"-a\", \"--results_outfile\", required=True, help=\"file path where the boxes are saved\")\n\nargs = vars(ap.parse_args())\n\nlog_file_path = args[\"log_file_path\"]\ninput_annotations_dir = args[\"input_annotations_dir\"]\nmodel_dir = args[\"model_dir\"]\nmodel_path = args[\"model_path\"]\noutfile_annotated = args[\"outfile_annotated\"]\nresults_outfile = args[\"results_outfile\"]\n\nif sys.version_info[0] < 3:\n raise Exception(\"Must use Python3. Use python3 in your command line.\")\n\nif log_file_path is not None:\n sys.stderr = open(log_file_path, 'a')\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\nclass PlotImageDataset(Dataset):\n # load the dataset definitions\n def load_dataset(self, annotations_dir, is_train=True):\n # define one class\n self.add_class(\"dataset\", 1, \"plotimage\")\n # define data locations\n # images_dir = dataset_dir + '/images/'\n # annotations_dir = dataset_dir + '/annots/'\n # find all images\n counter = 0\n annotations = listdir(annotations_dir)\n for filename in annotations:\n ann_path = annotations_dir + '/' + filename\n eprint(ann_path)\n tree = ElementTree.parse(ann_path)\n root = tree.getroot()\n image_id = int(root.find('image_id').text)\n # extract image id\n # image_id = filename[:-4]\n # skip bad images\n # if image_id in ['00090']:\n # continue\n # skip all images after 150 if we are building the train set\n if is_train and counter >= round(len(annotations)/5):\n counter += 1\n continue\n # skip all images before 150 if we are building the test/val set\n if not is_train and counter < round(len(annotations)/5):\n counter += 1\n continue\n #img_path = images_dir + filename\n img_path = root.find('image_path').text\n #ann_path = annotations_dir + image_id + '.xml'\n # add to dataset\n self.add_image('dataset', image_id=image_id, path=img_path, annotation=ann_path)\n counter += 1\n\n # extract bounding boxes from an annotation file\n def extract_boxes(self, filename):\n # load and parse the file\n tree = ElementTree.parse(filename)\n # get the root of the document\n root = tree.getroot()\n # extract each bounding box\n boxes = list()\n for box in root.findall('.//bndbox'):\n xmin = int(box.find('xmin').text)\n ymin = int(box.find('ymin').text)\n xmax = int(box.find('xmax').text)\n ymax = int(box.find('ymax').text)\n coors = [xmin, ymin, xmax, ymax]\n boxes.append(coors)\n # extract image dimensions\n width = int(root.find('.//size/width').text)\n height = int(root.find('.//size/height').text)\n return boxes, width, height\n\n # load the masks for an image\n def load_mask(self, image_id):\n # get details of image\n info = self.image_info[image_id]\n # define box file location\n path = info['annotation']\n # load XML\n boxes, w, h = self.extract_boxes(path)\n # create one array for all masks, each on a different channel\n masks = zeros([h, w, len(boxes)], dtype='uint8')\n # create masks\n class_ids = list()\n for i in range(len(boxes)):\n box = boxes[i]\n row_s, row_e = box[1], box[3]\n col_s, col_e = box[0], box[2]\n masks[row_s:row_e, col_s:col_e, i] = 1\n class_ids.append(self.class_names.index('plotimage'))\n return masks, asarray(class_ids, dtype='int32')\n\n # load an image reference\n def image_reference(self, image_id):\n info = self.image_info[image_id]\n return info['path']\n\n# define the prediction configuration\nclass PredictionConfig(Config):\n # define the name of the configuration\n NAME = \"plotimage_cfg\"\n # number of classes (background + plot image)\n NUM_CLASSES = 1 + 1\n # simplify GPU config\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n\n# plot a number of photos with ground truth and predictions\ndef plot_actual_vs_predicted(dataset, model, cfg, n_images=5):\n # load image and mask\n for i in range(n_images):\n # load the image and mask\n image = dataset.load_image(i)\n mask, _ = dataset.load_mask(i)\n # convert pixel values (e.g. center)\n scaled_image = mold_image(image, cfg)\n # convert image into one sample\n sample = expand_dims(scaled_image, 0)\n # make prediction\n yhat = model.detect(sample, verbose=0)[0]\n # define subplot\n pyplot.subplot(n_images, 2, i*2+1)\n # plot raw pixel data\n pyplot.imshow(image)\n pyplot.title('Actual')\n # plot masks\n for j in range(mask.shape[2]):\n pyplot.imshow(mask[:, :, j], cmap='gray', alpha=0.3)\n # get the context for drawing boxes\n pyplot.subplot(n_images, 2, i*2+2)\n # plot raw pixel data\n pyplot.imshow(image)\n pyplot.title('Predicted')\n ax = pyplot.gca()\n # plot each box\n for box in yhat['rois']:\n # get coordinates\n y1, x1, y2, x2 = box\n # calculate width and height of the box\n width, height = x2 - x1, y2 - y1\n # create the shape\n rect = Rectangle((x1, y1), width, height, fill=False, color='red')\n # draw the box\n ax.add_patch(rect)\n # show the figure\n pyplot.show()\n\ntest_set = PlotImageDataset()\ntest_set.load_dataset(input_annotations_dir, is_train=False)\ntest_set.prepare()\nprint('Test: %d' % len(test_set.image_ids))\n# create config\ncfg = PredictionConfig()\n# define the model\nmodel = MaskRCNN(mode='inference', model_dir=model_dir, config=cfg)\n# load model weights\nmodel.load_weights(model_path, by_name=True)\n# plot predictions for test dataset\n# plot_actual_vs_predicted(test_set, model, cfg)\n\nout_figures = []\n\ni = 0\nimage = test_set.load_image(i)\n# mask, _ = test_set.load_mask(i)\n# convert pixel values (e.g. center)\nscaled_image = mold_image(image, cfg)\n# convert image into one sample\nsample = expand_dims(scaled_image, 0)\n# make prediction\nyhat = model.detect(sample, verbose=0)[0]\nprint(yhat)\n\nfor box in yhat['rois']:\n y1, x1, y2, x2 = box\n width, height = x2 - x1, y2 - y1\n image = cv2.rectangle(image, (x1, y1), (x2, y2), (255,0,0), 2)\n\npyplot.figure()\npyplot.imshow(image)\npyplot.title('Predicted')\nfig = pyplot.gcf()\n\n# show the figure\nout_figures.append(fig)\n\npdf = matplotlib.backends.backend_pdf.PdfPages(outfile_annotated)\nfor fig in out_figures:\n pdf.savefig(fig)\npdf.close()\n\nwith open(results_outfile, 'w') as writeFile:\n writer = csv.writer(writeFile)\n writer.writerows(yhat['rois'])\nwriteFile.close()\n" ]
[ [ "tensorflow.keras.models.load_model", "tensorflow.keras.layers.Conv2DTranspose", "numpy.concatenate", "pandas.isna", "sklearn.preprocessing.MinMaxScaler", "pandas.read_csv", "tensorflow.keras.layers.LeakyReLU", "tensorflow.keras.preprocessing.image.ImageDataGenerator", "tensorflow.keras.Input", "tensorflow.keras.backend.int_shape", "tensorflow.keras.layers.Conv2D", "sklearn.preprocessing.LabelBinarizer", "numpy.repeat", "numpy.zeros", "tensorflow.keras.layers.Flatten", "tensorflow.keras.callbacks.ModelCheckpoint", "tensorflow.keras.layers.Dense", "sklearn.model_selection.train_test_split", "tensorflow.keras.Model", "tensorflow.keras.layers.Reshape", "numpy.array", "tensorflow.keras.layers.Activation", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.layers.BatchNormalization", "numpy.prod" ], [ "matplotlib.pyplot.gca", "matplotlib.pyplot.imshow", "numpy.expand_dims", "matplotlib.pyplot.title", "numpy.asarray", "matplotlib.patches.Rectangle", "matplotlib.pyplot.gcf", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Li-fAngyU/Paddle
[ "e548f65f96697830035a28f9070b40829408ccdb", "e548f65f96697830035a28f9070b40829408ccdb", "e548f65f96697830035a28f9070b40829408ccdb" ]
[ "python/paddle/fluid/tests/unittests/ipu/op_test_ipu.py", "python/paddle/fluid/contrib/sparsity/asp.py", "python/paddle/fluid/tests/unittests/test_imperative_reinforcement.py" ]
[ "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport random\nimport unittest\nimport numpy as np\nfrom enum import Enum\n\nimport paddle\nimport paddle.static\n\nmap_np_dtype_to_fluid_dtype = {\n 'bool': \"bool\",\n 'int8': \"int8\",\n 'uint8': \"uint8\",\n \"int32\": \"int32\",\n \"int64\": \"int64\",\n \"float16\": \"float16\",\n \"float32\": \"float32\",\n \"float64\": \"float64\",\n}\n\n\nclass ExecutionMode(Enum):\n CPU_FP32 = 1\n IPU_FP32 = 2\n # enable_fp16 through ipu_strategy.enable_fp16\n IPU_POPART_FP16 = 3\n\n def __lt__(self, other):\n return self.value < other.value\n\n def __gt__(self, other):\n return self.value > other.value\n\n\ndef np_dtype_to_fluid_str(dtype: np.dtype) -> str:\n return map_np_dtype_to_fluid_dtype[dtype.name]\n\n\nclass IPUOpTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n # Get random seeds\n cls._np_rand_state = np.random.get_state()\n cls._py_rand_state = random.getstate()\n\n cls.SEED = 2021\n np.random.seed(cls.SEED)\n random.seed(cls.SEED)\n\n # Enable paddle static graph mode\n paddle.enable_static()\n\n @classmethod\n def tearDownClass(cls):\n \"\"\"Restore random seeds\"\"\"\n np.random.set_state(cls._np_rand_state)\n random.setstate(cls._py_rand_state)\n\n @classmethod\n def use_ipumodel(cls):\n if 'POPLAR_IPUMODEL' not in os.environ:\n return False\n else:\n flag = os.environ['POPLAR_IPUMODEL']\n if flag.upper() in ['1', \"TRUE\"]:\n return True\n\n def set_atol(self):\n self.atol = 1e-10\n self.rtol = 1e-6\n self.atol_fp16 = 1e-3\n self.rtol_fp16 = 1e-3\n\n def set_training(self):\n self.is_training = False\n self.epoch = 1\n\n def check(self, outputs, check_shape=False):\n cpu_fp32 = outputs[ExecutionMode.CPU_FP32]\n ipu_fp32 = outputs[ExecutionMode.IPU_FP32]\n max_diff = np.abs(cpu_fp32 - ipu_fp32).max()\n fp32_flag = np.allclose(\n cpu_fp32, ipu_fp32, rtol=self.rtol, atol=self.atol)\n self.assertTrue(fp32_flag, \"max diff is %f\" % (max_diff))\n\n if check_shape:\n self.assertTrue(cpu_fp32.shape == ipu_fp32.shape)\n\n ipu_popart_fp16 = None\n if ExecutionMode.IPU_POPART_FP16 in outputs.keys():\n ipu_popart_fp16 = outputs[ExecutionMode.IPU_POPART_FP16]\n max_diff = np.abs(ipu_popart_fp16.astype(np.float32) -\n cpu_fp32).max()\n fp16_flag = np.allclose(\n ipu_popart_fp16.astype(np.float32),\n cpu_fp32,\n rtol=self.rtol_fp16,\n atol=self.atol_fp16)\n self.assertTrue(fp16_flag, \"max diff is %f\" % (max_diff))\n\n if check_shape:\n self.assertTrue(ipu_popart_fp16.shape == cpu_fp32.shape)\n", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n# Copyright (c) 2021 NVIDIA Corporation. All rights reserved.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nFunctions for Auto SParsity (ASP) training and inference.\n\"\"\"\n\nimport os\nimport copy\nimport numpy as np\nimport paddle\nfrom paddle.fluid import global_scope, program_guard, layers\nfrom paddle.fluid.initializer import ConstantInitializer\nfrom paddle.fluid.contrib import sparsity\nfrom paddle.fluid import core\n\nOpRole = core.op_proto_and_checker_maker.OpRole\nOP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName()\n\n__all__ = [\n 'decorate', 'prune_model', 'set_excluded_layers', 'reset_excluded_layers'\n]\n\n\ndef set_excluded_layers(main_program, param_names):\n r\"\"\"\n Set parameter name of layers which would not be pruned as sparse weights.\n\n Args:\n main_program (Program, optional): Program with model definition and its parameters.\n param_names (list): A list contains names of parameters.\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.static import sparsity\n\n paddle.enable_static()\n\n main_program = paddle.static.Program()\n startup_program = paddle.static.Program()\n\n with paddle.static.program_guard(main_program, startup_program):\n input_data = paddle.static.data(name='data', shape=[None, 128])\n label = paddle.static.data(name='label', shape=[None, 10])\n hidden = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None, name=\"need_sparse_fc\")\n hidden = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=32, activation=None, name=\"need_dense_fc\")\n prob = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=10, activation=None)\n loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label))\n\n # Setup exluded layers out from ASP workflow.\n # Please note, excluded_layers must be set before calling `optimizer.minimize()`.\n sparsity.set_excluded_layers(main_program, [\"need_dense_fc\"])\n\n optimizer = paddle.optimizer.SGD(learning_rate=0.1)\n optimizer = paddle.static.amp.decorate(optimizer )\n # Calling sparsity.decorate() to wrap minimize() in optimizer, which \n # will insert necessary masking operations for ASP workflow.\n optimizer = sparsity.decorate(optimizer)\n optimizer.minimize(loss, startup_program)\n \"\"\"\n ASPHelper.set_excluded_layers(\n main_program=main_program, param_names=param_names)\n\n\ndef reset_excluded_layers(main_program=None):\n r\"\"\"\n Reset exculded layers setting corresponding to :attr:`main_program`. If :attr:`main_program` \n is None, then all configurations of excluded_layers would be cleaned.\n\n Args:\n main_program (Program, optional): Program with model definition and its parameters.\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.static import sparsity\n\n paddle.enable_static()\n\n main_program = paddle.static.Program()\n startup_program = paddle.static.Program()\n\n with paddle.static.program_guard(main_program, startup_program):\n input_data = paddle.static.data(name='data', shape=[None, 128])\n label = paddle.static.data(name='label', shape=[None, 10])\n hidden = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None, name=\"my_first_fc\")\n hidden = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=32, activation=None, name=\"my_second_fc\")\n prob = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=10, activation=None)\n loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label))\n\n # Setup exluded layers out from ASP workflow.\n # Please note, excluded_layers must be set before calling `optimizer.minimize()`.\n sparsity.set_excluded_layers(main_program, [\"my_second_fc\"])\n # Now the weights of \"my_second_fc\" would not be included in Automatic SParsity's workflow.\n\n # Reset excluded_layers, all FC layers would be included into Automatic SParsity's workflow.\n # Please note, reset_excluded_layers also must be called before calling `optimizer.minimize()`.\n sparsity.reset_excluded_layers(main_program)\n \"\"\"\n ASPHelper.reset_excluded_layers(main_program=main_program)\n\n\ndef decorate(optimizer):\n r\"\"\"\n Wrap the given optimizer as a OptimizerWithSparsityGuarantee, \n which would insert necessary ops for ASP workflows when calling minimize()\n\n Args:\n optimizer (Optimizer): A Optimizer used for training.\n Returns:\n OptimizerWithSparsityGuarantee: A wrapper for ASP to decorate `minimize` function of the given optimizer.\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.static import sparsity\n\n main_program = paddle.static.Program()\n startup_program = paddle.static.Program()\n\n paddle.enable_static()\n\n with paddle.static.program_guard(main_program, startup_program):\n input_data = paddle.static.data(name='data', shape=[None, 128])\n label = paddle.static.data(name='label', shape=[None, 10])\n hidden = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None)\n prob = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=10, activation=None)\n loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label))\n\n optimizer = paddle.optimizer.SGD(learning_rate=0.1)\n optimizer = sparsity.decorate(optimizer)\n # if do sparse training with Fleet, please replace above decorate with:\n # strategy = paddle.distributed.fleet.DistributedStrategy()\n # strategy.asp = True\n # optimizer = fleet.distributed_optimizer(optimizer, strategy=strategy)\n\n optimizer.minimize(loss, startup_program)\n \"\"\"\n return ASPHelper.decorate(optimizer)\n\n\ndef prune_model(main_program=None,\n n=2,\n m=4,\n mask_algo='mask_1d',\n with_mask=True):\n r\"\"\"\n Pruning parameters of supported layers in :attr:`main_program` via \n specified mask generation function given by :attr:`mask_algo`. This \n function supports both training and inference controlled by :attr:`with_mask`.\n If :attr:`with_mask` is True, it would also prune parameter related ASP mask Variables,\n else only prunes parameters.\n\n *Note*: If parameters are supported and in FP16, please set :attr:`n`=2, :attr:`m`=4, \n if they in FP32, then :attr:`n`=1, :attr:`m`=2` to further enable Sparse Tensor Core acceleration.\n\n *Note*: If calling this function with :attr:`with_mask`, it should call `OptimizerWithSparsityGuarantee.minimize` \n and initialization (`exe.run(startup_program`)) before (For successfully obtain mask Variable). \n Typically set `with_mask` as true for training (have called `OptimizerWithSparsityGuarantee.minimize`) and false for \n inference only. To obtain OptimizerWithSparsityGuarantee, please see `sparsity.decoreate()`.\n\n Args:\n main_program (Program, optional): Program with model definition and its parameters. Default is `paddle.static.default_main_program()\n n (int): n of `n:m` sparse pattern.\n m (int): m of `n:m` sparse pattern.\n mask_algo (string, optional): The function name to generate spase mask. Default is `mask_1d`.\n The vaild inputs should be one of 'mask_1d', 'mask_2d_greedy' and 'mask_2d_best'.\n with_mask (bool, optional): To prune mask Variables related to parameters or not. Ture is purning also, False is not. Defalut is True.\n Returns:\n dictionary: A dictionary with key: `parameter name` (string) and value: its corresponding mask Variable.\n Examples:\n .. code-block:: python\n\n import paddle\n from paddle.static import sparsity\n\n paddle.enable_static()\n\n main_program = paddle.static.Program()\n startup_program = paddle.static.Program()\n\n with paddle.static.program_guard(main_program, startup_program):\n input_data = paddle.static.data(name='data', shape=[None, 128])\n label = paddle.static.data(name='label', shape=[None, 10])\n hidden = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None, name=\"need_sparse_fc\")\n hidden = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=32, activation=None, name=\"need_dense_fc\")\n prob = paddle.static.nn.fc(x=hidden, num_flatten_dims=-1, size=10, activation=None)\n loss = paddle.mean(paddle.nn.functional.square_error_cost(prob, label))\n\n # Setup exluded layers out from ASP workflow.\n # Please note, excluded_layers must be set before calling `optimizer.minimize()`.\n sparsity.set_excluded_layers(main_program, [\"need_dense_fc\"])\n\n optimizer = paddle.optimizer.SGD(learning_rate=0.1)\n optimizer = paddle.static.amp.decorate(optimizer )\n # Calling sparsity.decorate() to wrap minimize() in optimizer, which \n # will insert necessary masking operations for ASP workflow.\n optimizer = sparsity.decorate(optimizer)\n optimizer.minimize(loss, startup_program)\n\n device = paddle.device.get_device()\n place = paddle.set_device(device)\n\n exe = paddle.static.Executor(place)\n exe.run(startup_program)\n\n # Must call `exe.run(startup_program)` first before calling `sparsity.prune_model`\n sparsity.prune_model(main_program, mask_algo='mask_2d_best')\n \"\"\"\n if main_program is not None and hasattr(\n main_program,\n \"distributed_info_\") and main_program.distributed_info_[\n \"sharding_degree\"] > 1 and paddle.fluid.is_compiled_with_cuda():\n gpu_id = int(os.environ.get('FLAGS_selected_gpus', 0))\n place = paddle.CUDAPlace(gpu_id)\n else:\n device = paddle.device.get_device()\n place = paddle.set_device(device)\n\n MaskAlgo_mapping = {\n 'mask_1d': sparsity.MaskAlgo.MASK_1D,\n 'mask_2d_greedy': sparsity.MaskAlgo.MASK_2D_GREEDY,\n 'mask_2d_best': sparsity.MaskAlgo.MASK_2D_BEST\n }\n assert (mask_algo in MaskAlgo_mapping), \\\n 'The \"mask_algo\" should be one of [\"mask_1d\", \"mask_2d_greedy\", \"mask_2d_best\"]'\n\n return ASPHelper.prune_model(\n place=place,\n main_program=main_program,\n n=n,\n m=m,\n mask_algo=MaskAlgo_mapping[mask_algo],\n with_mask=with_mask)\n\n\nclass ProgramASPInfo(object):\n r\"\"\"\n ProgramASPInfo is a container to keep ASP relevant information of Pragrom. It contains three inner-variables:\n 1. __mask_vars (Dictionary): Key is parameter's name and vaule is its corresponding sparse mask Variable object, which is created by `ASPHelper.create_mask_variables`.\n 2. __masks (Dictionary): Key is parameter's name and vaule is its corressponding sparse mask Numpy array, which is created by `ASPHelper.prune_model`.\n 3. __excluded_layers (List): It stores name of layers which should not involve into ASP workflow.\n \"\"\"\n\n def __init__(self):\n self.__mask_vars = {}\n self.__masks = {}\n self.__excluded_layers = []\n\n def update_mask_vars(self, param_name, var):\n self.__mask_vars[param_name] = var\n\n def update_masks(self, param_name, var):\n self.__masks[param_name] = var\n\n def update_excluded_layers(self, param_names):\n self.__excluded_layers.extend(copy.deepcopy(param_names))\n\n def reset_excluded_layers(self):\n self.__excluded_layers = []\n\n @property\n def mask_vars(self):\n return self.__mask_vars\n\n @property\n def masks(self):\n return self.__masks\n\n @property\n def excluded_layers(self):\n return self.__excluded_layers\n\n\nclass ASPHelper(object):\n r\"\"\"\n ASPHelper is a collection of Auto SParsity (ASP) functions to enable \n\n 1. training models with weights in 2:4 sparse pattern on FP16 or 1:2 sparse pattern on FP32 from scratch.\n 2. pruning well-trained models into 2:4 sparse pattern on FP16 or 1:2 sparse pattern on FP32 for fine-tuning.\n \"\"\"\n\n MASK_APPENDDED_NAME = '_asp_mask'\n SUPPORTED_LAYERS = {'fc': 'w_0', 'linear': 'w_0', 'conv2d': 'w_0'}\n\n __asp_info = {}\n\n @classmethod\n def set_excluded_layers(cls, main_program, param_names):\n r\"\"\"\n This is the implementation of `sparsity.set_excluded_layers`, for details please see explanation in `sparsity.set_excluded_layers`.\n \"\"\"\n asp_info = cls._get_program_asp_info(main_program)\n asp_info.update_excluded_layers(param_names)\n\n @classmethod\n def reset_excluded_layers(cls, main_program=None):\n r\"\"\"\n This is the implementation of `sparsity.reset_excluded_layers`, for details please see explanation in `sparsity.reset_excluded_layers`.\n \"\"\"\n if main_program is None:\n for asp_info in cls.__asp_info:\n asp_info.reset_excluded_layers()\n else:\n cls._get_program_asp_info(main_program).reset_excluded_layers()\n\n @staticmethod\n def decorate(optimizer):\n r\"\"\"\n This is the implementation of `sparsity.decorate`, for details please see explanation in `sparsity.decorate`.\n \"\"\"\n return OptimizerWithSparsityGuarantee(optimizer)\n\n @classmethod\n def prune_model(cls,\n place,\n main_program=None,\n n=2,\n m=4,\n mask_algo=sparsity.MaskAlgo.MASK_1D,\n with_mask=True):\n r\"\"\"\n This is the implementation of `sparsity.prune_model`, for details please see explanation in `sparsity.prune_model`.\n \"\"\"\n checked_func_name = sparsity.CheckMethod.get_checking_method(mask_algo)\n\n if main_program is None:\n main_program = paddle.static.default_main_program()\n\n asp_info = cls._get_program_asp_info(main_program)\n for param in main_program.global_block().all_parameters():\n if ASPHelper._is_supported_layer(main_program, param.name):\n weight_tensor = global_scope().find_var(param.name).get_tensor()\n weight_nparray = np.array(weight_tensor)\n\n # The double transpose ops here make sure pruning direction consistent with cuSparseLt.\n # SPMMA in cuSparseLt: D = (AxB) + C, where matrix A (mxk) is sparse matrix.\n # cuSparseLt would prune matrix A along k dimension.\n # In sparse training, layer weight matriices is viewed sparse matrix A, so\n # the math fomula should be 'Act(WX + b)'. However, default fomula in PaddlePaddle\n # is 'Act(XW + b)'. For enabling SPMMA, weights and inputs should be transposed \n # for computing, Act( (W^T X^T)^T + b). Therefore, we have to prune alog k dimension \n # of W^T, which is m dimension of W. Moreove, all mask generating functions in \n # sparsity/utils is row-major pruning. That is the reason we have to transpose weight \n # matrices beforce invoking create_mask. Then we transpose the result maks to make \n # sure its shape to be the same as the input weight.\n weight_sparse_mask = sparsity.create_mask(\n weight_nparray.T, func_name=mask_algo, n=n, m=m).T\n weight_pruned_nparray = np.multiply(weight_nparray,\n weight_sparse_mask)\n weight_tensor.set(weight_pruned_nparray, place)\n assert sparsity.check_sparsity(weight_pruned_nparray.T, n=n, m=m, func_name=checked_func_name), \\\n 'Pruning {} weight matrix failure!!!'.format(param.name)\n if with_mask:\n weight_mask_param = global_scope().find_var(\n ASPHelper._get_mask_name(param.name))\n assert weight_mask_param is not None, \\\n 'Cannot find {} variable, please call ASPHelper.minimize' \\\n ' and initialization (exe.run(startup_program)) first!'.format(ASPHelper._get_mask_name(param.name))\n weight_mask_tensor = weight_mask_param.get_tensor()\n weight_mask_tensor.set(weight_sparse_mask, place)\n asp_info.update_masks(param.name, weight_sparse_mask)\n return asp_info.masks.copy()\n\n @staticmethod\n def _get_mask_name(param_name):\n r\"\"\"\n Return mask name by given parameter name :attr:`param_name`.\n\n Args:\n param_name (string): The name of parameter.\n Returns:\n string: The mask name of :attr:`param_name`.\n \"\"\"\n return param_name + ASPHelper.MASK_APPENDDED_NAME\n\n @staticmethod\n def _get_not_ASP_relevant_vars(main_program):\n r\"\"\"\n Get all parameters's Variables in :attr:`main_program` but excluded ASP mask Variables.\n\n Args:\n main_program (Program): Program with model definition and its parameters.\n Returns:\n list: A list of parameter Variables in :attr:`main_program` (excluded ASP mask Variables).\n \"\"\"\n var_list = []\n for param in main_program.global_block().all_parameters():\n if ASPHelper.MASK_APPENDDED_NAME not in param.name:\n var_list.append(param)\n return var_list\n\n @classmethod\n def _get_program_asp_info(cls, main_program):\n if not main_program in cls.__asp_info:\n cls.__asp_info[main_program] = ProgramASPInfo()\n return cls.__asp_info[main_program]\n\n @classmethod\n def _is_supported_layer(cls, main_program, param_name):\n r\"\"\"\n Verify if given :attr:`param_name` is supported by ASP.\n\n Args:\n param_name (string): The name of parameter.\n Returns:\n bool: True if it is supported, else False.\n Examples:\n .. code-block:: python\n\n from paddle.static.sparsity.asp import ASPHelper\n\n main_program = paddle.static.Program()\n startup_program = paddle.static.Program()\n\n with paddle.static.program_guard(main_program, startup_program):\n input_data = paddle.static.data(name='data', shape=[None, 128])\n fc = paddle.static.nn.fc(x=input_data, num_flatten_dims=-1, size=32, activation=None)\n\n for param in main_program.global_block().all_parameters():\n ASPHelper._is_supported_layer(main_program, param.name)\n # fc_0.w_0 -> True\n # fc_0.b_0 -> False\n \"\"\"\n if ASPHelper.MASK_APPENDDED_NAME in param_name:\n return False\n\n for layer in cls._get_program_asp_info(main_program).excluded_layers:\n if layer in param_name:\n return False\n\n for name in ASPHelper.SUPPORTED_LAYERS:\n if name in param_name and \\\n ASPHelper.SUPPORTED_LAYERS[name] in param_name:\n return True\n return False\n\n @classmethod\n def _minimize(cls,\n optimizer,\n loss,\n main_program=None,\n startup_program=None,\n parameter_list=None,\n no_grad_set=None):\n r\"\"\"\n This function is a decorator of `minimize` function in `Optimizer`.\n There are three steps:\n\n 1. Call :attr:`optimizer`.minimize(:attr:`loss`)\n 2. Create sparse mask Tensors according to supported layers in :attr:`main_program`.\n 3. Insert masking ops in the end of parameters update.\n\n *Note*: Please use `ASP.decorate` instead when applying distributed training with `Fleet`. \n (Due to there is a invisiable graphs optimization in `Fleet.minimize()` which make training graph \n cannot be modified anymore.)\n\n Args:\n optimizer (Optimizer): A Optimizer used for training.\n loss (Variable): A Variable containing the value to minimize.\n main_program (Program, optional): Program with model definition and its parameters. Default is `loss.block.program`.\n startup_program (Program, optional): Program for initializing parameters in `parameter_list`. Default is `paddle.static.default_startup_program()`.\n parameter_list (Iterable, optional): Iterable of `Variable` or `Variable.name` to update to minimize `loss`. The default value is None, at this time all parameters will be updated.\n no_grad_set (set, optional): Set of `Variable or `Variable.name` that don't need to be updated. The default value is None.\n Returns:\n list: operators from :attr:`optimizer`.minimize(:attr:`loss`).\n list: pairs of parameters and their gradients.\n \"\"\"\n if main_program is None:\n main_program = loss.block.program\n\n if startup_program is None:\n startup_program = paddle.static.default_startup_program()\n\n optimizer_ops, params_and_grads = optimizer.minimize(\n loss, startup_program, parameter_list, no_grad_set=no_grad_set)\n cls._create_mask_variables(main_program, startup_program,\n params_and_grads)\n cls._insert_sparse_mask_ops(main_program, params_and_grads)\n return optimizer_ops, params_and_grads\n\n @classmethod\n def _create_mask_variables(cls, main_program, startup_program,\n params_and_grads):\n r\"\"\"\n Create sparse mask Tensors according to supported layers in :attr:`main_program`.\n This function is called in second step of `ASPHelper._minimize`\n\n Args:\n main_program (Program): Program with model definition and its parameters.\n startup_program (Program): Program for initializing parameters.\n params_and_grads (list): Variable pairs of parameters and their gradients.\n \"\"\"\n asp_info = cls._get_program_asp_info(main_program)\n with program_guard(main_program, startup_program):\n for param_and_grad in params_and_grads:\n if ASPHelper._is_supported_layer(main_program,\n param_and_grad[0].name):\n mask_param = layers.create_parameter(\n name=param_and_grad[0].name +\n ASPHelper.MASK_APPENDDED_NAME,\n shape=param_and_grad[0].shape,\n dtype=param_and_grad[0].dtype,\n default_initializer=ConstantInitializer(value=1.0))\n mask_param.stop_gradient = True\n mask_param.trainable = False\n asp_info.update_mask_vars(param_and_grad[0].name,\n mask_param)\n\n @classmethod\n def _insert_sparse_mask_ops(cls, main_program, param_grads):\n r\"\"\"\n Insert masking ops in the end of parameters update.\n This function is called in third step of `ASPHelper._minimize`\n\n Args:\n main_program (Program): Program with model definition and its parameters.\n params_and_grads (list): Variable pairs of parameters and their gradients.\n \"\"\"\n block = main_program.global_block()\n asp_info = cls._get_program_asp_info(main_program)\n for param_grad in param_grads:\n if param_grad[0].name in asp_info.mask_vars:\n block.append_op(\n type='elementwise_mul',\n inputs={\n \"X\": param_grad[0],\n 'Y': asp_info.mask_vars[param_grad[0].name]\n },\n outputs={'Out': param_grad[0]},\n attrs={\n 'axis': -1,\n 'use_mkldnn': False,\n OP_ROLE_KEY: OpRole.Optimize\n })\n\n\nclass OptimizerWithSparsityGuarantee(object):\n r\"\"\"\n OptimizerWithSparsityGuarantee is a wrapper to decorate `minimize` function of given optimizer by `_minimize` of ASPHelper.\n The decorated `minimize` function would do three things (exactly same as `ASPHelper._minimize`):\n 1. Call `minimize` function of given optimizer.\n 2. Call `ASPHelper._create_mask_variables` to create mask Variables.\n 3. Call `ASPHelper._insert_sparse_mask_ops` to insert weight masking ops in the end of `loss`'s Program.\n \"\"\"\n\n def __init__(self, optimizer):\n self._optimizer = optimizer\n self._learning_rate = optimizer._learning_rate\n self._learning_rate_map = optimizer._learning_rate_map\n\n def minimize(self,\n loss,\n startup_program=None,\n parameter_list=None,\n no_grad_set=None):\n r\"\"\"\n This function is to call `ASPHelper.minimize()` and return its return\n\n Args:\n loss (Variable): A Variable containing the value to minimize.\n startup_program (Program, optional): Program for initializing parameters in `parameter_list`. Default is `paddle.static.default_startup_program()`.\n parameter_list (Iterable, optional): Iterable of `Variable` or `Variable.name` to update to minimize `loss`. The default value is None, at this time all parameters will be updated.\n no_grad_set (set, optional): Set of `Variable or `Variable.name` that don't need to be updated. The default value is None.\n Returns:\n list: operators from :attr:`optimizer`.minimize(:attr:`loss`).\n list: pairs of parameters and their gradients.\n \"\"\"\n return ASPHelper._minimize(\n self._optimizer,\n loss,\n startup_program=startup_program,\n parameter_list=parameter_list,\n no_grad_set=no_grad_set)\n", "# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\n\nimport contextlib\nimport unittest\nimport numpy as np\nimport six\n\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid import core\nfrom paddle.fluid.optimizer import SGDOptimizer\nfrom paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear\nimport paddle.fluid.dygraph.nn as nn\nfrom paddle.fluid.dygraph.base import to_variable\nfrom test_imperative_base import new_program_scope\nfrom paddle.fluid.framework import _test_eager_guard\n\n\nclass Policy(fluid.dygraph.Layer):\n def __init__(self, input_size):\n super(Policy, self).__init__()\n\n self.affine1 = nn.Linear(input_size, 128)\n self.affine2 = nn.Linear(128, 2)\n self.dropout_ratio = 0.6\n\n self.saved_log_probs = []\n self.rewards = []\n\n def forward(self, inputs):\n x = fluid.layers.reshape(inputs, shape=[-1, 4])\n x = self.affine1(x)\n x = fluid.layers.dropout(x, self.dropout_ratio)\n x = fluid.layers.relu(x)\n action_scores = self.affine2(x)\n return fluid.layers.softmax(action_scores, axis=1)\n\n\nclass TestImperativeMnist(unittest.TestCase):\n def test_mnist_float32(self):\n seed = 90\n epoch_num = 1\n\n state = np.random.normal(size=4).astype(\"float32\")\n state_list = state.tolist()\n reward = np.random.random(size=[1, 1]).astype(\"float32\")\n reward_list = reward.tolist()\n action_list = [1]\n action = np.array(action_list).astype(\"float32\")\n mask_list = [[0, 1]]\n mask = np.array(mask_list).astype(\"float32\")\n\n def run_dygraph():\n paddle.seed(seed)\n paddle.framework.random._manual_program_seed(seed)\n\n policy = Policy(input_size=4)\n\n dy_state = fluid.dygraph.base.to_variable(state)\n dy_state.stop_gradient = True\n loss_probs = policy(dy_state)\n\n dy_mask = fluid.dygraph.base.to_variable(mask)\n dy_mask.stop_gradient = True\n\n loss_probs = fluid.layers.log(loss_probs)\n loss_probs = fluid.layers.elementwise_mul(loss_probs, dy_mask)\n loss_probs = fluid.layers.reduce_sum(loss_probs, dim=-1)\n\n dy_reward = fluid.dygraph.base.to_variable(reward)\n dy_reward.stop_gradient = True\n\n loss_probs = fluid.layers.elementwise_mul(dy_reward, loss_probs)\n loss = fluid.layers.reduce_sum(loss_probs)\n\n sgd = SGDOptimizer(\n learning_rate=1e-3, parameter_list=policy.parameters())\n\n dy_param_init_value = {}\n\n dy_out = loss.numpy()\n\n for param in policy.parameters():\n dy_param_init_value[param.name] = param.numpy()\n\n loss.backward()\n sgd.minimize(loss)\n policy.clear_gradients()\n\n dy_param_value = {}\n for param in policy.parameters():\n dy_param_value[param.name] = param.numpy()\n\n return dy_out, dy_param_init_value, dy_param_value\n\n with fluid.dygraph.guard():\n dy_out, dy_param_init_value, dy_param_value = run_dygraph()\n\n with fluid.dygraph.guard():\n with _test_eager_guard():\n eager_out, eager_param_init_value, eager_param_value = run_dygraph(\n )\n\n with new_program_scope():\n paddle.seed(seed)\n paddle.framework.random._manual_program_seed(seed)\n\n exe = fluid.Executor(fluid.CPUPlace(\n ) if not core.is_compiled_with_cuda() else fluid.CUDAPlace(0))\n\n policy = Policy(input_size=4)\n\n st_sgd = SGDOptimizer(learning_rate=1e-3)\n\n st_state = fluid.layers.data(\n name='st_state', shape=[4], dtype='float32')\n st_reward = fluid.layers.data(\n name='st_reward', shape=[1], dtype='float32')\n st_mask = fluid.layers.data(\n name='st_mask', shape=[2], dtype='float32')\n\n st_loss_probs = policy(st_state)\n\n st_loss_probs = fluid.layers.log(st_loss_probs)\n st_loss_probs = fluid.layers.elementwise_mul(st_loss_probs, st_mask)\n st_loss_probs = fluid.layers.reduce_sum(st_loss_probs, dim=-1)\n\n st_loss_probs = fluid.layers.elementwise_mul(st_reward,\n st_loss_probs)\n st_loss = fluid.layers.reduce_sum(st_loss_probs)\n\n st_sgd.minimize(st_loss)\n\n # initialize params and fetch them\n static_param_init_value = {}\n static_param_name_list = []\n for param in policy.parameters():\n static_param_name_list.append(param.name)\n\n out = exe.run(fluid.default_startup_program(),\n fetch_list=static_param_name_list)\n\n for i in range(len(static_param_name_list)):\n static_param_init_value[static_param_name_list[i]] = out[i]\n\n fetch_list = [st_loss.name]\n fetch_list.extend(static_param_name_list)\n\n out = exe.run(\n fluid.default_main_program(),\n feed={\"st_state\": state,\n \"st_reward\": reward,\n \"st_mask\": mask},\n fetch_list=fetch_list)\n\n static_param_value = {}\n static_out = out[0]\n for i in range(1, len(out)):\n static_param_value[static_param_name_list[i - 1]] = out[i]\n\n #self.assertTrue(np.allclose(dy_x_data.all(), static_x_data.all()))\n\n for key, value in six.iteritems(static_param_init_value):\n self.assertTrue(np.equal(value, dy_param_init_value[key]).all())\n\n self.assertTrue(np.equal(static_out, dy_out).all())\n\n for key, value in six.iteritems(static_param_value):\n self.assertTrue(np.equal(value, dy_param_value[key]).all())\n\n # check eager\n for key, value in six.iteritems(static_param_init_value):\n self.assertTrue(np.equal(value, eager_param_init_value[key]).all())\n\n self.assertTrue(np.equal(static_out, eager_out).all())\n\n for key, value in six.iteritems(static_param_value):\n self.assertTrue(np.equal(value, eager_param_value[key]).all())\n\n\nif __name__ == '__main__':\n paddle.enable_static()\n unittest.main()\n" ]
[ [ "numpy.random.get_state", "numpy.allclose", "numpy.random.seed", "numpy.abs", "numpy.random.set_state" ], [ "numpy.array", "numpy.multiply" ], [ "numpy.random.normal", "numpy.array", "numpy.random.random", "numpy.equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
alxfmpl/swarmlib
[ "625645d466223ebef35fa1492d47e1a252cfd863" ]
[ "swarmlib/cuckoosearch/cuckoo_problem.py" ]
[ "# ------------------------------------------------------------------------------------------------------\n# Copyright (c) Leo Hanisch. All rights reserved.\n# Licensed under the BSD 3-Clause License. See LICENSE.txt in the project root for license information.\n# ------------------------------------------------------------------------------------------------------\n\n# pylint: disable=too-many-instance-attributes\n\nfrom copy import deepcopy\nimport logging\n\nimport numpy as np\n\nfrom .nest import Nest\nfrom ..util import levy_flight as cuckoo\nfrom .visualizer import Visualizer\nLOGGER = logging.getLogger(__name__)\n\n\nclass CuckooProblem:\n def __init__(self, **kwargs):\n \"\"\"\n Initialize a new cuckoo search problem.\n \"\"\"\n\n self.__upper_boundary = kwargs.get('upper_boundary', 4.)\n self.__lower_boundary = kwargs.get('lower_boundary', 0.)\n self.__alpha = kwargs.pop('alpha', 1)\n self.__max_generations = kwargs.pop('max_generations', 10)\n self.__lambda = kwargs.pop('lambda', 1.5)\n self.__p_a = kwargs.pop('p_a', .1)\n\n self.__function = kwargs['function']\n self.__nests = [\n Nest(lower_boundary=self.__lower_boundary, upper_boundary=self.__upper_boundary, function=self.__function)\n for _ in range(kwargs['nests'])\n ]\n\n # Initialize visualizer for plotting\n kwargs['iteration_number'] = self.__max_generations\n self.__visualizer = Visualizer(**kwargs)\n\n def solve(self) -> Nest:\n nest_indices = np.array(range(len(self.__nests)))\n best_nest = deepcopy(min(self.__nests, key=lambda nest: nest.value))\n\n positions, abandoned = zip(*[(nest.position, nest.abandoned) for nest in self.__nests])\n self.__visualizer.add_data(positions=positions, best_position=best_nest.position, abandoned=abandoned)\n\n LOGGER.info('Iteration 0 best solution=\"%s\" at position=\"%s\"', best_nest.value, best_nest.position)\n\n for iteration in range(self.__max_generations):\n\n # Perform levy flights to get cuckoo's new position\n new_cuckoo_pos = [\n np.clip(cuckoo.levy_flight(nest.position, self.__alpha, self.__lambda), a_min=self.__lower_boundary, a_max=self.__upper_boundary)\n for nest in self.__nests\n ]\n\n # Randomly select nests to be updated\n np.random.shuffle(nest_indices)\n\n # Update nests\n for index, pos in zip(nest_indices, new_cuckoo_pos):\n self.__nests[index].update_pos(pos)\n\n # Abandon nests randomly considering p_a\n for nest in self.__nests:\n if np.random.random_sample() < self.__p_a:\n nest.abandon()\n\n # Update best nest\n current_best = min(self.__nests, key=lambda nest: nest.value)\n if current_best.value < best_nest.value:\n best_nest = deepcopy(current_best)\n LOGGER.info('Iteration %i Found new best solution=\"%s\" at position=\"%s\"', iteration+1, best_nest.value, best_nest.position)\n\n # Add data for plot\n positions, abandoned = zip(*[(nest.position, nest.abandoned) for nest in self.__nests])\n self.__visualizer.add_data(positions=positions, best_position=current_best.position, abandoned=abandoned)\n\n LOGGER.info('Last best solution=\"%s\" at position=\"%s\"', best_nest.value, best_nest.position)\n return best_nest\n\n def replay(self):\n \"\"\"\n Start the problems visualization.\n \"\"\"\n self.__visualizer.replay()\n" ]
[ [ "numpy.random.random_sample", "numpy.random.shuffle" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
olga-turkovska/land-cover-patterns
[ "67bbf0d01b7bb5ec5b1376a9fbc1da59addf2e31" ]
[ "scripts/2-aggregate-land-cover.py" ]
[ "import os\nimport numpy as np\nimport rasterio\n\n\naggregate_forest = np.vectorize(lambda x: np.where(0 < x < 6, 1, x))\naggregate_agriculture = np.vectorize(lambda x: np.where(11 < x < 21, 21, x))\n\n\nfor dirs, subdirs, files in os.walk('../output/ceara/'):\n for file in files:\n wp_raster = rasterio.open('../output/ceara/' + file)\n\n file_name = file.replace('id_', '')\n wp_id = int(file_name.replace('.tif', ''))\n\n out_raster_temp = aggregate_forest(wp_raster.read(range(1, 34)))\n out_raster = aggregate_agriculture(out_raster_temp)\n out_raster = out_raster.astype('uint8')\n out_meta = wp_raster.meta\n\n with rasterio.open('../output/ceara_agg_v2/' + 'agg_v2_id_' + str(wp_id) + '.tif', 'w', **out_meta) as raster:\n raster.write(out_raster)\n" ]
[ [ "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Dref360/fairlearn
[ "8f087fbb0b27740d10b31d95706bb175a4b4581c", "3cbd144b824d7454d04b813c2cb093fae5b9b256" ]
[ "test/unit/reductions/exponentiated_gradient/simple_learners.py", "fairlearn/reductions/_exponentiated_gradient/_lagrangian.py" ]
[ "# Copyright (c) Microsoft Corporation and contributors.\n# Licensed under the MIT License.\n\nimport numpy as np\nimport pandas as pd\n\n\nclass LeastSquaresBinaryClassifierLearner:\n def __init__(self):\n self.weights = None\n\n def fit(self, X, Y, sample_weight):\n sqrtW = np.sqrt(sample_weight)\n matX = np.array(X) * sqrtW[:, np.newaxis]\n vecY = Y * sqrtW\n self.lsqinfo = np.linalg.lstsq(matX, vecY, rcond=-1)\n self.weights = pd.Series(self.lsqinfo[0], index=list(X))\n\n def predict(self, X):\n pred = X.dot(np.asarray(self.weights))\n return 1 * (pred > 0.5)\n\n\nclass LeastSquaresRegressor:\n def __init__(self):\n self.weights = None\n\n def fit(self, X, Y, sample_weight):\n sqrtW = np.sqrt(sample_weight)\n matX = np.array(X) * sqrtW[:, np.newaxis]\n vecY = Y * sqrtW\n self.lsqinfo = np.linalg.lstsq(matX, vecY, rcond=-1)\n self.weights = pd.Series(self.lsqinfo[0], index=list(X))\n\n def predict(self, X):\n return X.dot(self.weights)\n", "# Copyright (c) Microsoft Corporation and contributors.\n# Licensed under the MIT License.\n\nimport logging\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport scipy.optimize as opt\nfrom sklearn.dummy import DummyClassifier\nfrom time import time\n\nfrom ._constants import _PRECISION, _INDENTATION, _LINE\n\nfrom fairlearn.reductions._moments import ClassificationMoment\n\nlogger = logging.getLogger(__name__)\n\n\nclass _Lagrangian:\n \"\"\"Operations related to the Lagrangian.\n\n Parameters\n ----------\n X : {numpy.ndarray, pandas.DataFrame}\n the training features\n sensitive_features : {numpy.ndarray, pandas.Series, pandas.DataFrame, list}\n the sensitive features to use for constraints\n y : {numpy.ndarray, pandas.Series, pandas.DataFrame, list}\n the training labels\n estimator :\n the estimator to fit in every iteration of :meth:`best_h` using a\n :meth:`fit` method with arguments `X`, `y`, and `sample_weight`\n constraints : fairlearn.reductions.Moment\n Object describing the parity constraints. This provides the reweighting\n and relabelling.\n B : float\n bound on the L1-norm of the lambda vector\n opt_lambda : bool\n indicates whether to optimize lambda during the calculation of the\n Lagrangian; optional with default value True\n \"\"\"\n\n def __init__(self, X, sensitive_features, y, estimator, constraints, B, opt_lambda=True):\n self.X = X\n self.n = self.X.shape[0]\n self.y = y\n self.constraints = constraints\n self.constraints.load_data(X, y, sensitive_features=sensitive_features)\n self.obj = self.constraints.default_objective()\n self.obj.load_data(X, y, sensitive_features=sensitive_features)\n self.pickled_estimator = pickle.dumps(estimator)\n self.B = B\n self.opt_lambda = opt_lambda\n self.hs = pd.Series(dtype=\"float64\")\n self.predictors = pd.Series(dtype=\"float64\")\n self.errors = pd.Series(dtype=\"float64\")\n self.gammas = pd.DataFrame()\n self.lambdas = pd.DataFrame()\n self.n_oracle_calls = 0\n self.oracle_execution_times = []\n self.n_oracle_calls_dummy_returned = 0\n self.last_linprog_n_hs = 0\n self.last_linprog_result = None\n\n def _eval(self, Q, lambda_vec):\n \"\"\"Return the value of the Lagrangian.\n\n Parameters\n ----------\n Q : {pandas.Series, callable}\n `Q` is either a series of weights summing up to 1 that indicate\n the weight of each `h` in contributing to the randomized\n predictor, or a callable corresponding to a deterministic\n `predict` function.\n lambda_vec : pandas.Series\n lambda vector\n\n Returns\n -------\n tuple\n tuple `(L, L_high, gamma, error)` where `L` is the value of the\n Lagrangian, `L_high` is the value of the Lagrangian under the best\n response of the lambda player, `gamma` is the vector of constraint\n violations, and `error` is the empirical error\n \"\"\"\n if callable(Q):\n error = self.obj.gamma(Q)[0]\n gamma = self.constraints.gamma(Q)\n else:\n error = self.errors[Q.index].dot(Q)\n gamma = self.gammas[Q.index].dot(Q)\n\n if self.opt_lambda:\n lambda_projected = self.constraints.project_lambda(lambda_vec)\n L = error + np.sum(lambda_projected * (gamma - self.constraints.bound()))\n else:\n L = error + np.sum(lambda_vec * (gamma - self.constraints.bound()))\n\n max_constraint = (gamma - self.constraints.bound()).max()\n if max_constraint <= 0:\n L_high = error\n else:\n L_high = error + self.B * max_constraint\n return L, L_high, gamma, error\n\n def eval_gap(self, Q, lambda_hat, nu):\n r\"\"\"Return the duality gap object for the given :math:`Q` and :math:`\\hat{\\lambda}`.\"\"\"\n L, L_high, gamma, error = self._eval(Q, lambda_hat)\n result = _GapResult(L, L, L_high, gamma, error)\n for mul in [1.0, 2.0, 5.0, 10.0]:\n h_hat, h_hat_idx = self.best_h(mul * lambda_hat)\n logger.debug(\"%smul=%.0f\", _INDENTATION, mul)\n L_low_mul, _, _, _ = self._eval(pd.Series({h_hat_idx: 1.0}), lambda_hat)\n if L_low_mul < result.L_low:\n result.L_low = L_low_mul\n if result.gap() > nu + _PRECISION:\n break\n return result\n\n def solve_linprog(self, nu):\n n_hs = len(self.hs)\n n_constraints = len(self.constraints.index)\n if self.last_linprog_n_hs == n_hs:\n return self.last_linprog_result\n c = np.concatenate((self.errors, [self.B]))\n A_ub = np.concatenate((self.gammas.sub(self.constraints.bound(), axis=0),\n -np.ones((n_constraints, 1))), axis=1)\n b_ub = np.zeros(n_constraints)\n A_eq = np.concatenate((np.ones((1, n_hs)), np.zeros((1, 1))), axis=1)\n b_eq = np.ones(1)\n result = opt.linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, method='simplex')\n Q = pd.Series(result.x[:-1], self.hs.index)\n dual_c = np.concatenate((b_ub, -b_eq))\n dual_A_ub = np.concatenate((-A_ub.transpose(), A_eq.transpose()), axis=1)\n dual_b_ub = c\n dual_bounds = [(None, None) if i == n_constraints else (0, None) for i in range(n_constraints + 1)] # noqa: E501\n result_dual = opt.linprog(dual_c,\n A_ub=dual_A_ub,\n b_ub=dual_b_ub,\n bounds=dual_bounds,\n method='simplex')\n lambda_vec = pd.Series(result_dual.x[:-1], self.constraints.index)\n self.last_linprog_n_hs = n_hs\n self.last_linprog_result = (Q, lambda_vec, self.eval_gap(Q, lambda_vec, nu))\n return self.last_linprog_result\n\n def _call_oracle(self, lambda_vec):\n signed_weights = self.obj.signed_weights() + self.constraints.signed_weights(lambda_vec)\n if isinstance(self.constraints, ClassificationMoment):\n redY = 1 * (signed_weights > 0)\n else:\n redY = self.y\n redW = signed_weights.abs()\n redW = self.n * redW / redW.sum()\n\n redY_unique = np.unique(redY)\n\n classifier = None\n if len(redY_unique) == 1:\n logger.debug(\"redY had single value. Using DummyClassifier\")\n classifier = DummyClassifier(strategy='constant',\n constant=redY_unique[0])\n self.n_oracle_calls_dummy_returned += 1\n else:\n classifier = pickle.loads(self.pickled_estimator)\n\n oracle_call_start_time = time()\n classifier.fit(self.X, redY, sample_weight=redW)\n self.oracle_execution_times.append(time() - oracle_call_start_time)\n self.n_oracle_calls += 1\n\n return classifier\n\n def best_h(self, lambda_vec):\n \"\"\"Solve the best-response problem.\n\n Returns the classifier that solves the best-response problem for\n the vector of Lagrange multipliers `lambda_vec`.\n \"\"\"\n classifier = self._call_oracle(lambda_vec)\n def h(X): return classifier.predict(X)\n h_error = self.obj.gamma(h)[0]\n h_gamma = self.constraints.gamma(h)\n h_value = h_error + h_gamma.dot(lambda_vec)\n\n if not self.hs.empty:\n values = self.errors + self.gammas.transpose().dot(lambda_vec)\n best_idx = values.idxmin()\n best_value = values[best_idx]\n else:\n best_idx = -1\n best_value = np.PINF\n\n if h_value < best_value - _PRECISION:\n logger.debug(\"%sbest_h: val improvement %f\", _LINE, best_value - h_value)\n h_idx = len(self.hs)\n self.hs.at[h_idx] = h\n self.predictors.at[h_idx] = classifier\n self.errors.at[h_idx] = h_error\n self.gammas[h_idx] = h_gamma\n self.lambdas[h_idx] = lambda_vec.copy()\n best_idx = h_idx\n\n return self.hs[best_idx], best_idx\n\n\nclass _GapResult:\n \"\"\"The result of a duality gap computation.\"\"\"\n\n def __init__(self, L, L_low, L_high, gamma, error):\n self.L = L\n self.L_low = L_low\n self.L_high = L_high\n self.gamma = gamma\n self.error = error\n\n def gap(self):\n return max(self.L - self.L_low, self.L_high - self.L)\n" ]
[ [ "numpy.asarray", "numpy.linalg.lstsq", "numpy.array", "numpy.sqrt" ], [ "pandas.Series", "sklearn.dummy.DummyClassifier", "numpy.unique", "pandas.DataFrame", "numpy.ones", "numpy.concatenate", "scipy.optimize.linprog", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [ "1.6", "1.10", "0.15", "1.4", "0.16", "1.9", "0.19", "1.5", "0.18", "1.2", "1.7", "1.0", "0.17", "1.3", "1.8" ], "tensorflow": [] } ]
MaxGosselin/portfolio_optimizer
[ "a137d5b029aff0b584adb9df0ba8bf1831731882" ]
[ "portfolio_functions.py" ]
[ "''' \n \n A collection of functions to perform portfolio analysis. \n\n Max Gosselin, 2019\n \n'''\nimport numpy as np\nimport pandas as pd\nfrom scipy import optimize\n\n\ndef portfolio_metrics(weights, avg_xs_returns, covariance_matrix):\n ''' Compute basic portfolio metrics: return, stdv, sharpe ratio '''\n\n portfolio_return = np.sum(weights * avg_xs_returns)\n portfolio_stdv = np.sqrt(np.dot(weights.T, np.dot(weights, covariance_matrix)))\n \n portfolio_sharpe = portfolio_return / portfolio_stdv\n\n tickers = covariance_matrix.columns\n\n metrics = {\n 'return': portfolio_return,\n 'stdv': portfolio_stdv,\n 'sharpe': portfolio_sharpe,\n 'weights': weights\n }\n metrics.update(dict([(ticker, weight) for ticker, weight in zip(tickers, weights)]).items())\n\n return metrics\n\ndef simulate_portfolios(iters, xs_stats, covariance_matrix):\n ''' What we want here is to randomly generate portfolios that will sit \n inside the efficiency frontier for illustrative purposes '''\n\n # Set up an empty array to store our generated portfolios\n simulations = []\n \n while iters > 1:\n \n weights = np.random.random(len(xs_stats.columns))\n weights /= np.sum(weights)\n \n simulations.append(portfolio_metrics(weights, xs_stats.loc['Avg'], covariance_matrix))\n \n iters -= 1\n\n return simulations\n\ndef solve_minvar(xs_avg, covariance_matrix):\n ''' Solve for the weights of the minimum variance portfolio \n\n Constraints:\n sum of weights = 1,\n weights bound by [0, 0.2],\n\n Returns the weights and the jacobian used to generate the solution.\n \n '''\n\n def __minvar(weights, xs_avg, covariance_matrix):\n ''' Anonymous function to compute stdv '''\n return np.sqrt(np.dot(weights.T, np.dot(weights, covariance_matrix)))\n\n p_size = len(xs_avg)\n args = (xs_avg, covariance_matrix) \n constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}]\n bounds = [(0, 0.2)] * p_size\n\n\n minimized_weights = optimize.minimize(__minvar, np.zeros(p_size), args=args,\n method='SLSQP', bounds=bounds, constraints=constraints, options={'maxiter':1000})\n\n return minimized_weights\n\ndef solve_maxsharpe(xs_avg, covariance_matrix):\n ''' Solve for the weights of the maximum Sharpe ratio portfolio \n\n Constraints:\n sum of weights = 1,\n weights bound by [0, 0.2],\n\n Returns the weights and the jacobian used to generate the solution.\n \n '''\n def __max_by_min_sharpe(weights, xs_avg, covariance_matrix):\n ''' Anonymous function to compute sharpe ratio, note that since scipy only minimizes we go negative. '''\n pm = portfolio_metrics(weights, xs_avg, covariance_matrix) \n return -pm['return'] / pm['stdv']\n\n p_size = len(xs_avg)\n args = (xs_avg, covariance_matrix) \n constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}]\n bounds = [(0, 0.2)] * p_size\n\n \n minimized_weights = optimize.minimize(__max_by_min_sharpe, ((1/p_size) * np.ones(p_size)), args=args,\n method='SLSQP', bounds=bounds, constraints=constraints, options={'maxiter':1000})\n\n return minimized_weights\n\ndef solve_for_target_return(xs_avg, covariance_matrix, target):\n ''' Solve for the weights of the minimum variance portfolio which has\n a specific targeted return.\n\n Constraints:\n sum of weights = 1,\n weights bound by [0, 0.2],\n portfolio return = target return,\n\n Returns the weights and the jacobian used to generate the solution.\n \n '''\n\n def __minvar(weights, xs_avg, covariance_matrix):\n ''' Anonymous function to compute stdv '''\n return np.sqrt(np.dot(weights.T, np.dot(weights, covariance_matrix)))\n \n def __match_target(weights):\n ''' Anonymous function to check equality with the target return '''\n return np.sum(weights * xs_avg)\n\n p_size = len(xs_avg)\n args = (xs_avg, covariance_matrix)\n constraints = [\n {'type': 'eq', 'fun': lambda x: np.sum(x) - 1},\n {'type': 'eq', 'fun': lambda x: __match_target(x) - target},\n ]\n bounds = [(0, 0.2)] * p_size\n\n minimized_weights = optimize.minimize(__minvar, ((1/p_size) * np.ones(p_size)), args=args,\n method='SLSQP', bounds=bounds, constraints=constraints, options={'maxiter':1000})\n\n return minimized_weights\n\ndef generate_efficient_frontier(targets, xs_avg, covariance_matrix):\n\n portfolios = []\n\n for target in targets:\n\n p_weights = solve_for_target_return(xs_avg, covariance_matrix, target)\n portfolios.append(portfolio_metrics(p_weights['x'], xs_avg, covariance_matrix))\n\n return portfolios\n\n" ]
[ [ "numpy.dot", "numpy.zeros", "numpy.sum", "numpy.ones" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
matroshenko/SPLERGE_via_TF
[ "1768485985b00fd7dabd726d8d24cbdb947dd143", "1768485985b00fd7dabd726d8d24cbdb947dd143" ]
[ "merge/evaluation.py", "tests/test_projection_layer.py" ]
[ "import os\nimport tensorflow as tf\n\nfrom merge.model import Model\n\n\ndef run_model_on_random_input(model):\n batch_size = 1\n height = 100\n width = 200\n inputs = {\n 'image': tf.random.uniform(shape=(batch_size, height, width, 3), minval=0, maxval=256, dtype='int32'),\n 'horz_split_points_probs': tf.random.uniform(shape=(batch_size, height), dtype='float32'),\n 'vert_split_points_probs': tf.random.uniform(shape=(batch_size, width), dtype='float32'),\n 'horz_split_points_binary': tf.random.uniform(shape=(batch_size, height), minval=0, maxval=2, dtype='int32'),\n 'vert_split_points_binary': tf.random.uniform(shape=(batch_size, width), minval=0, maxval=2, dtype='int32')\n }\n model(inputs)\n\ndef load_model(model_file_path, compute_metric):\n assert os.path.exists(model_file_path)\n model = Model(compute_metric)\n run_model_on_random_input(model)\n model.load_weights(model_file_path)\n\n # Metric can't be calculated in graph mode.\n run_eagerly = True if compute_metric else False\n model.compile(run_eagerly=run_eagerly)\n return model\n\ndef convert_ds_element_to_tuple(element):\n input_keys = [\n 'image', \n 'horz_split_points_probs', \n 'vert_split_points_probs',\n 'horz_split_points_binary',\n 'vert_split_points_binary'\n ]\n return (\n {key: element[key] for key in input_keys},\n {\n 'markup_table': element['markup_table'] \n }\n )", "from unittest import TestCase, main\n\nimport tensorflow as tf\n\nimport context\nfrom split.projection_layer import ProjectionDirection, ProjectionLayer\n\n\nclass ProjectionLayerTestCase(TestCase):\n def setUp(self):\n self.input = tf.constant([[\n [[1, 2], [3, 4], [5, 6]],\n [[7, 8], [9, 10], [11, 12]],\n ]], dtype = 'float32')\n\n def test_project_on_height_no_broadcast(self):\n expected_output = tf.constant([[\n [[3, 4]],\n [[9, 10]]\n ]], dtype = 'float32')\n layer = ProjectionLayer(ProjectionDirection.Height, False)\n output = layer(self.input)\n self.assertTrue(tf.reduce_all(expected_output == output))\n\n def test_project_on_height_broadcast(self):\n expected_output = tf.constant([[\n [[3, 4], [3, 4], [3, 4]],\n [[9, 10], [9, 10], [9, 10]]\n ]], dtype = 'float32')\n layer = ProjectionLayer(ProjectionDirection.Height, True)\n output = layer(self.input)\n self.assertTrue(tf.reduce_all(expected_output == output))\n\n def test_project_on_width_no_broadcast(self):\n expected_output = tf.constant([[\n [[4, 5], [6, 7], [8, 9]]\n ]], dtype = 'float32')\n layer = ProjectionLayer(ProjectionDirection.Width, False)\n output = layer(self.input)\n self.assertTrue(tf.reduce_all(expected_output == output))\n\n def test_project_on_width_broadcast(self):\n expected_output = tf.constant([[\n [[4, 5], [6, 7], [8, 9]],\n [[4, 5], [6, 7], [8, 9]]\n ]], dtype = 'float32')\n layer = ProjectionLayer(ProjectionDirection.Width, True)\n output = layer(self.input)\n self.assertTrue(tf.reduce_all(expected_output == output))\n\nif __name__ == '__main__':\n main()" ]
[ [ "tensorflow.random.uniform" ], [ "tensorflow.reduce_all", "tensorflow.constant" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.8", "1.10", "1.12", "2.7", "2.6", "1.4", "2.3", "2.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.2", "1.2", "2.10" ] } ]
egonw/pyamiimage
[ "8e436bae06a0c13a4265a186832e0e679512b7b9" ]
[ "pyimage/contour.py" ]
[ "from skimage.measure import find_contours\nfrom skimage import io\nfrom skimage.color import rgb2gray\nfrom matplotlib import pyplot as plt\n\nimage = io.imread('contour_finding_test.png')\n# image = io.imread('FlowchartDiagram.png')\nimage = rgb2gray(image)\nout = find_contours(image)\nprint(len(out))\n\n# Find contours at a constant value of 0.8\n# contours = find_contours(image, 0.8)\ncontours = find_contours(image, )\n\n# Display the image and plot all contours found\nfig, ax = plt.subplots()\nax.imshow(image, cmap=plt.cm.gray)\n\nfor contour in contours:\n ax.plot(contour[:, 1], contour[:, 0], linewidth=2)\n\nax.axis('image')\nax.set_xticks([])\nax.set_yticks([])\nplt.show()\n# io.imshow(image)\n# io.show()\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.subplots" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dengemann/engemann-2020-multimodal-brain-age
[ "ceffb1e01658e31d19dfc4dc0be7aff1d6d21af5", "ceffb1e01658e31d19dfc4dc0be7aff1d6d21af5" ]
[ "camcan/utils/file_parsing.py", "camcan/utils/notebook.py" ]
[ "\"\"\"Utility functions for parcinging Freesurfer output files.\"\"\"\nfrom os.path import join\n\nimport nibabel as nb\nimport numpy as np\n\n\ndef _vectorize_fs_surf(file_path):\n \"\"\"\n Read surface information from a file and turn it into a vector.\n\n Parameters\n ----------\n file_path : str\n The path to a file with surface data.\n\n Returns\n -------\n vectorized_data : numpy.ndarray\n Extracted data.\n\n \"\"\"\n img = nb.load(file_path)\n in_data = img.get_fdata().squeeze()\n\n return in_data\n\n\ndef get_area(subject_dir, n_points):\n \"\"\"\n Read area information for the given subject and turn it into a vector.\n\n Data for left and right hemispheres are concatenated.\n\n Parameters\n ----------\n subject_dir : str\n The directory to files with surface data.\n n_points : int\n Defines how many points to take from cortex surface.\n\n Returns\n -------\n : numpy.ndarray\n Extracted data.\n\n \"\"\"\n AREA_FILES = ('lh.area.mgh', 'rh.area.mgh')\n\n lh_data = _vectorize_fs_surf(join(subject_dir, AREA_FILES[0]))\n rh_data = _vectorize_fs_surf(join(subject_dir, AREA_FILES[1]))\n\n n_points = n_points // 2\n\n return np.concatenate((lh_data[:n_points], rh_data[:n_points]), 0)\n\n\ndef get_thickness(subject_dir, n_points):\n \"\"\"\n Read thickness information for the given subject and turn it into a vector.\n\n Data for left and right hemispheres are concatenated.\n\n Parameters\n ----------\n subject_dir : str\n The directory to files with surface data.\n n_points : int\n Defines how many points to take from cortex surface.\n\n Returns\n -------\n : numpy.ndarray\n Extracted data.\n\n \"\"\"\n THICKNESS_FILES = ('rh.thickness.mgh', 'lh.thickness.mgh')\n\n lh_data = _vectorize_fs_surf(join(subject_dir, THICKNESS_FILES[0]))\n rh_data = _vectorize_fs_surf(join(subject_dir, THICKNESS_FILES[1]))\n\n n_points = n_points // 2\n\n return np.concatenate((lh_data[:n_points], rh_data[:n_points]), 0)\n", "\"\"\"Utilities for Jupyter Notebook reports.\"\"\"\nfrom itertools import combinations\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\n\n\ndef plot_pred(y, y_pred, mae, title='Prediction vs Measured'):\n \"\"\"Plot predicted values vs real values.\"\"\"\n plt.figure()\n plt.title(title)\n plt.scatter(y, y_pred, edgecolor='black')\n plt.plot([y.min(), y.max()], [y.min(), y.max()], '-', lw=3, color='green')\n plt.plot([y.min(), y.max()], [y.min() - mae, y.max() - mae], 'k--', lw=3,\n color='red')\n plt.plot([y.min(), y.max()], [y.min() + mae, y.max() + mae], 'k--', lw=3,\n color='red')\n plt.xlabel('Chronological Age')\n plt.ylabel('Predicted Age')\n plt.grid()\n plt.show()\n\n\n# https://scikit-learn.org/stable/auto_examples/model_selection/\n# plot_learning_curve.html\ndef plot_learning_curve(train_sizes, train_scores, test_scores,\n title='Learning Curves', ylim=None):\n \"\"\"\n Generate a simple plot of the test and training learning curve.\n\n Parameters\n ----------\n train_sizes : array-like, shape (n_ticks,), dtype float or int\n Numbers of training examples that has been used to generate\n the learning curve.\n\n train_scores : array, shape (n_ticks, n_cv_folds)\n Scores on training sets.\n\n test_scores : array, shape (n_ticks, n_cv_folds)\n Scores on test set.\n\n title : string\n Title for the chart.\n\n ylim : tuple, shape (ymin, ymax), optional\n Defines minimum and maximum yvalues plotted.\n\n \"\"\"\n plt.figure()\n plt.title(title)\n\n if ylim is not None:\n plt.ylim(*ylim)\n\n plt.xlabel('Training examples')\n plt.ylabel('Score')\n\n train_scores = -train_scores\n test_scores = -test_scores\n\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid()\n\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color='r')\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color='g')\n plt.plot(train_sizes, train_scores_mean, 'o-', color='r',\n label='Training score')\n plt.plot(train_sizes, test_scores_mean, 'o-', color='g',\n label='Cross-validation score')\n\n plt.legend(loc='best')\n plt.show()\n\n\ndef plot_barchart(mae_std,\n title='Age Prediction Performance of Different Modalities',\n bar_text_indent=2):\n \"\"\"Plot bar chart.\n\n Parameters\n ----------\n mae_std : dict(str, (number, number))\n Dictionary with labels and corresponding mae and std.\n title : str\n Bar chart title.\n bar_text_indent : number\n Indent from the bar top for labels displaying mae and std,\n measured in years.\n\n \"\"\"\n objects = tuple(reversed(sorted(mae_std.keys())))\n y_pos = np.arange(len(objects))\n mae = tuple(mae_std[k][0] for k in objects)\n std = tuple(mae_std[k][1] for k in objects)\n\n fig, axs = plt.subplots()\n axs.barh(y_pos, mae, align='center', xerr=std)\n\n # remove frame around the plot\n axs.spines['top'].set_visible(False)\n axs.spines['bottom'].set_visible(False)\n axs.spines['right'].set_visible(False)\n axs.spines['left'].set_visible(False)\n\n for i, v in enumerate(mae):\n axs.text(v + bar_text_indent, i - 0.05,\n f'{round(v, 2)} ({round(std[i], 2)})',\n color='blue', bbox=dict(facecolor='white'))\n\n plt.yticks(y_pos, objects)\n plt.xlabel('Absolute Prediction Error (Years)')\n plt.title(title)\n plt.show()\n\n\ndef plot_boxplot(data, title='Age Prediction Performance'):\n \"\"\"Plot box plot.\n\n Parameters\n ----------\n data : dict(str, numpy.ndarray)\n Dictionary with labels and corresponding data.\n title : str\n Bar chart title.\n\n \"\"\"\n data_pd = pd.DataFrame(data)\n sns.set_style('darkgrid')\n plt.figure()\n ax = sns.boxplot(data=data_pd, showmeans=True, orient='h')\n ax.set_title(title)\n ax.set(xlabel='Absolute Prediction Error (Years)')\n plt.show()\n\n\ndef plot_error_scatters(data, title='AE Scatter', xlim=None, ylim=None):\n \"\"\"Plot prediction errors of different modalities versus each other.\"\"\"\n data = data.dropna()\n age = data.age.values\n color_map = plt.cm.viridis((age - min(age)) / max(age))\n keys = data.columns\n # remove column with the original age\n keys = keys[1:]\n for key1, key2 in combinations(keys, r=2):\n fig, ax = plt.subplots()\n x_values = np.abs(data[key1].values - age)\n y_values = np.abs(data[key2].values - age)\n plt.scatter(x_values, y_values, edgecolors='black', color=color_map)\n plt.title(title)\n plt.xlabel(key1)\n plt.ylabel(key2)\n\n if xlim is not None:\n xlim_ = (xlim[0] - 1, xlim[1] + 1)\n else:\n xlim_ = (data[key1].min() - 1, data[key1].max() + 1)\n\n if ylim is not None:\n ylim_ = (ylim[0] - 1, ylim[1] + 1)\n else:\n ylim_ = (data[key2].min() - 1, data[key2].max() + 1)\n\n ax.set(xlim=xlim_, ylim=ylim_)\n ax.plot(ax.get_xlim(), ax.get_ylim(), ls='--', c='.3')\n plt.grid()\n\n\ndef plot_error_age(data, title='AE vs Age', xlim=None, ylim=None):\n \"\"\"Plot prediction errors of different modalities versus subject's age.\"\"\"\n keys = data.columns\n # remove column with the original age\n keys = keys[1:]\n for key1 in keys:\n data_slice = data[key1].dropna()\n age = data.loc[data_slice.index, 'age'].values\n abs_errors = np.abs(data_slice.values - age)\n plt.figure()\n plt.scatter(age, abs_errors, edgecolors='black')\n plt.title(title)\n plt.xlabel('Age (Years)')\n plt.ylabel(key1)\n plt.grid()\n\n if xlim is not None:\n plt.xlim(xlim)\n if ylim is not None:\n plt.ylim(ylim)\n\n\ndef plot_error_segments(data, segment_len=10, title=None, figsize=None,\n xlim=(0, 55)):\n \"\"\"Plot prediction errors for different age groups.\"\"\"\n keys = data.columns\n # remove column with the original age\n keys = keys[1:]\n age = data.age.values\n for key in keys:\n n_segments = int((age.max() - age.min()) / segment_len)\n segments_dict = {}\n plt_title = 'AE per Segment, %s' % key if title is None else title\n age_pred = data[key]\n\n for i in range(0, n_segments):\n bound_low = age.min() + i * segment_len\n bound_high = age.min() + (i + 1) * segment_len\n\n if i == n_segments - 1:\n indices = age >= bound_low\n else:\n indices = (age >= bound_low) * (age < bound_high)\n\n segments_dict[f'{bound_low}-{bound_high}'] =\\\n np.abs(age[indices] - age_pred[indices])\n\n df = pd.DataFrame.from_dict(segments_dict, orient='index').transpose()\n\n sns.set_style('darkgrid')\n fig, ax = plt.subplots(figsize=figsize)\n sns.boxplot(data=df, showmeans=True, orient='h')\n ax.set_title(plt_title)\n ax.set(xlim=xlim, xlabel='Absolute Prediction Error (Years)',\n ylabel='Age Ranges')\n plt.show()\n" ]
[ [ "numpy.concatenate" ], [ "matplotlib.pyplot.legend", "pandas.DataFrame", "matplotlib.pyplot.plot", "numpy.mean", "numpy.std", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "matplotlib.pyplot.ylim", "matplotlib.pyplot.fill_between", "pandas.DataFrame.from_dict", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.abs", "matplotlib.pyplot.scatter", "matplotlib.pyplot.subplots", "matplotlib.pyplot.xlim", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.yticks" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
dbatten5/dagster
[ "d76e50295054ffe5a72f9b292ef57febae499528", "d76e50295054ffe5a72f9b292ef57febae499528" ]
[ "examples/hacker_news/hacker_news/resources/dbt_asset_resource.py", "python_modules/libraries/dagster-pandas/dagster_pandas/validation.py" ]
[ "from typing import Any, Dict, List\n\nimport pandas\nfrom dagster import AssetKey, AssetMaterialization, EventMetadataEntry\nfrom dagster_dbt import DbtOutput\n\nfrom .snowflake_io_manager import connect_snowflake\n\n\nclass DbtAssetResource:\n \"\"\"\n This class defines a resource that is capable of producing a list of AssetMaterializations from\n a DbtOutput. It has one public function, get_asset_materializations(), which finds all the\n generated models in the dbt output and produces corresponding asset materializations.\n\n Putting this logic in a resource makes it easier to swap out between modes. You probably want\n your local testing / development pipelines to produce different assets than your production\n pipelines, as they will ideally be writing to different tables (with different dbt profiles).\n \"\"\"\n\n def __init__(self, asset_key_prefix: List[str]):\n self._asset_key_prefix = asset_key_prefix\n\n def _get_metadata(self, result: Dict[str, Any]) -> List[EventMetadataEntry]:\n return [\n EventMetadataEntry.float(\n value=result[\"execution_time\"], label=\"Execution Time (seconds)\"\n )\n ]\n\n def get_asset_materializations(self, dbt_output: DbtOutput) -> List[AssetMaterialization]:\n ret = []\n\n # dbt_output.result contains the parsed contents of the results.json file\n # Note that the json schema can change from version to version. This is written for\n # https://schemas.getdbt.com/dbt/run-results/v2.json (also will work with v1.json)\n for result in dbt_output.result[\"results\"]:\n if result[\"status\"] != \"success\":\n continue\n unique_id = result[\"unique_id\"]\n\n # Here, we choose a naming scheme for our asset keys that will look something like\n # <asset prefix> / model / <dbt project> / <model name>, but this is pretty arbitrary\n asset_key = AssetKey(self._asset_key_prefix + unique_id.split(\".\"))\n\n # create an AssetMaterialization with our key and metadata\n ret.append(\n AssetMaterialization(\n description=f\"dbt node: {unique_id}\",\n metadata_entries=self._get_metadata(result),\n asset_key=asset_key,\n )\n )\n\n return ret\n\n\nclass SnowflakeQueryDbtAssetResource(DbtAssetResource):\n \"\"\"\n This resource allows us to add in some extra information to these AssetMaterialization events.\n Because the relevant dbt project is configured for a Snowflake cluster, we can query the output\n models to get some additional information that we might want Dagster to track over time.\n\n Of course, this is completely optional.\n \"\"\"\n\n def __init__(self, snowflake_config: Dict[str, str], dbt_schema: str):\n self._snowflake_config = snowflake_config\n self._dbt_schema = dbt_schema\n super().__init__(asset_key_prefix=[\"snowflake\", dbt_schema])\n\n def _get_metadata(self, result: Dict[str, Any]) -> List[EventMetadataEntry]:\n \"\"\"\n Here, we run queries against our output Snowflake database tables to add additional context\n to our asset materializations.\n \"\"\"\n\n table_name = result[\"unique_id\"].split(\".\")[-1]\n with connect_snowflake(config=self._snowflake_config, schema=self._dbt_schema) as con:\n n_rows = pandas.read_sql_query(f\"SELECT COUNT(*) FROM {table_name}\", con)\n sample_rows = pandas.read_sql_query(\n f\"SELECT * FROM {table_name} SAMPLE ROW (10 rows)\", con\n )\n return super()._get_metadata(result) + [\n EventMetadataEntry.int(int(n_rows.iloc[0][0]), \"dbt Model Number of Rows\"),\n EventMetadataEntry.md(sample_rows.astype(\"str\").to_markdown(), \"dbt Model Sample Rows\"),\n ]\n", "from dagster import DagsterInvariantViolationError, check\nfrom dagster_pandas.constraints import (\n CategoricalColumnConstraint,\n ColumnDTypeFnConstraint,\n ColumnDTypeInSetConstraint,\n Constraint,\n ConstraintViolationException,\n DataFrameConstraint,\n InRangeColumnConstraint,\n NonNullableColumnConstraint,\n UniqueColumnConstraint,\n)\nfrom pandas import DataFrame, Timestamp\nfrom pandas.core.dtypes.common import (\n is_bool_dtype,\n is_float_dtype,\n is_integer_dtype,\n is_numeric_dtype,\n is_string_dtype,\n)\n\nPANDAS_NUMERIC_TYPES = {\"int64\", \"float\"}\n\n\ndef _construct_keyword_constraints(non_nullable, unique, ignore_missing_vals):\n non_nullable = check.bool_param(non_nullable, \"exists\")\n unique = check.bool_param(unique, \"unique\")\n ignore_missing_vals = check.bool_param(ignore_missing_vals, \"ignore_missing_vals\")\n if non_nullable and ignore_missing_vals:\n raise DagsterInvariantViolationError(\n \"PandasColumn cannot have a non-null constraint while also ignore missing values\"\n )\n constraints = []\n if non_nullable:\n constraints.append(NonNullableColumnConstraint())\n if unique:\n constraints.append(UniqueColumnConstraint(ignore_missing_vals=ignore_missing_vals))\n return constraints\n\n\nclass PandasColumn:\n \"\"\"\n The main API for expressing column level schemas and constraints for your custom dataframe\n types.\n\n Args:\n name (str): Name of the column. This must match up with the column name in the dataframe you\n expect to receive.\n is_required (Optional[bool]): Flag indicating the optional/required presence of the column.\n If th column exists, the validate function will validate the column. Defaults to True.\n constraints (Optional[List[Constraint]]): List of constraint objects that indicate the\n validation rules for the pandas column.\n \"\"\"\n\n def __init__(self, name, constraints=None, is_required=None):\n self.name = check.str_param(name, \"name\")\n self.is_required = check.opt_bool_param(is_required, \"is_required\", default=True)\n self.constraints = check.opt_list_param(constraints, \"constraints\", of_type=Constraint)\n\n def validate(self, dataframe):\n if self.name not in dataframe.columns:\n # Ignore validation if column is missing from dataframe and is not required\n if self.is_required:\n raise ConstraintViolationException(\n \"Required column {column_name} not in dataframe with columns {dataframe_columns}\".format(\n column_name=self.name, dataframe_columns=dataframe.columns\n )\n )\n else:\n for constraint in self.constraints:\n constraint.validate(dataframe, self.name)\n\n @staticmethod\n def exists(name, non_nullable=False, unique=False, ignore_missing_vals=False, is_required=None):\n \"\"\"\n Simple constructor for PandasColumns that expresses existence constraints.\n\n Args:\n name (str): Name of the column. This must match up with the column name in the dataframe you\n expect to receive.\n non_nullable (Optional[bool]): If true, this column will enforce a constraint that all values in the column\n ought to be non null values.\n unique (Optional[bool]): If true, this column will enforce a uniqueness constraint on the column values.\n ignore_missing_vals (Optional[bool]): A flag that is passed into most constraints. If true, the constraint will\n only evaluate non-null data. Ignore_missing_vals and non_nullable cannot both be True.\n is_required (Optional[bool]): Flag indicating the optional/required presence of the column.\n If the column exists the validate function will validate the column. Default to True.\n \"\"\"\n return PandasColumn(\n name=check.str_param(name, \"name\"),\n constraints=_construct_keyword_constraints(\n non_nullable=non_nullable, unique=unique, ignore_missing_vals=ignore_missing_vals\n ),\n is_required=is_required,\n )\n\n @staticmethod\n def boolean_column(\n name, non_nullable=False, unique=False, ignore_missing_vals=False, is_required=None\n ):\n \"\"\"\n Simple constructor for PandasColumns that expresses boolean constraints on boolean dtypes.\n\n Args:\n name (str): Name of the column. This must match up with the column name in the dataframe you\n expect to receive.\n non_nullable (Optional[bool]): If true, this column will enforce a constraint that all values in the column\n ought to be non null values.\n unique (Optional[bool]): If true, this column will enforce a uniqueness constraint on the column values.\n ignore_missing_vals (Optional[bool]): A flag that is passed into most constraints. If true, the constraint will\n only evaluate non-null data. Ignore_missing_vals and non_nullable cannot both be True.\n is_required (Optional[bool]): Flag indicating the optional/required presence of the column.\n If the column exists the validate function will validate the column. Default to True.\n \"\"\"\n return PandasColumn(\n name=check.str_param(name, \"name\"),\n constraints=[ColumnDTypeFnConstraint(is_bool_dtype)]\n + _construct_keyword_constraints(\n non_nullable=non_nullable, unique=unique, ignore_missing_vals=ignore_missing_vals\n ),\n is_required=is_required,\n )\n\n @staticmethod\n def numeric_column(\n name,\n min_value=-float(\"inf\"),\n max_value=float(\"inf\"),\n non_nullable=False,\n unique=False,\n ignore_missing_vals=False,\n is_required=None,\n ):\n \"\"\"\n Simple constructor for PandasColumns that expresses numeric constraints numeric dtypes.\n\n Args:\n name (str): Name of the column. This must match up with the column name in the dataframe you\n expect to receive.\n min_value (Optional[Union[int,float]]): The lower bound for values you expect in this column. Defaults to -float('inf')\n max_value (Optional[Union[int,float]]): The upper bound for values you expect in this column. Defaults to float('inf')\n non_nullable (Optional[bool]): If true, this column will enforce a constraint that all values in the column\n ought to be non null values.\n unique (Optional[bool]): If true, this column will enforce a uniqueness constraint on the column values.\n ignore_missing_vals (Optional[bool]): A flag that is passed into most constraints. If true, the constraint will\n only evaluate non-null data. Ignore_missing_vals and non_nullable cannot both be True.\n is_required (Optional[bool]): Flag indicating the optional/required presence of the column.\n If the column exists the validate function will validate the column. Default to True.\n \"\"\"\n return PandasColumn(\n name=check.str_param(name, \"name\"),\n constraints=[\n ColumnDTypeFnConstraint(is_numeric_dtype),\n InRangeColumnConstraint(\n check.numeric_param(min_value, \"min_value\"),\n check.numeric_param(max_value, \"max_value\"),\n ignore_missing_vals=ignore_missing_vals,\n ),\n ]\n + _construct_keyword_constraints(\n non_nullable=non_nullable, unique=unique, ignore_missing_vals=ignore_missing_vals\n ),\n is_required=is_required,\n )\n\n @staticmethod\n def integer_column(\n name,\n min_value=-float(\"inf\"),\n max_value=float(\"inf\"),\n non_nullable=False,\n unique=False,\n ignore_missing_vals=False,\n is_required=None,\n ):\n \"\"\"\n Simple constructor for PandasColumns that expresses numeric constraints on integer dtypes.\n\n Args:\n name (str): Name of the column. This must match up with the column name in the dataframe you\n expect to receive.\n min_value (Optional[Union[int,float]]): The lower bound for values you expect in this column. Defaults to -float('inf')\n max_value (Optional[Union[int,float]]): The upper bound for values you expect in this column. Defaults to float('inf')\n non_nullable (Optional[bool]): If true, this column will enforce a constraint that all values in the column\n ought to be non null values.\n unique (Optional[bool]): If true, this column will enforce a uniqueness constraint on the column values.\n ignore_missing_vals (Optional[bool]): A flag that is passed into most constraints. If true, the constraint will\n only evaluate non-null data. Ignore_missing_vals and non_nullable cannot both be True.\n is_required (Optional[bool]): Flag indicating the optional/required presence of the column.\n If the column exists the validate function will validate the column. Default to True.\n \"\"\"\n return PandasColumn(\n name=check.str_param(name, \"name\"),\n constraints=[\n ColumnDTypeFnConstraint(is_integer_dtype),\n InRangeColumnConstraint(\n check.numeric_param(min_value, \"min_value\"),\n check.numeric_param(max_value, \"max_value\"),\n ignore_missing_vals=ignore_missing_vals,\n ),\n ]\n + _construct_keyword_constraints(\n non_nullable=non_nullable, unique=unique, ignore_missing_vals=ignore_missing_vals\n ),\n is_required=is_required,\n )\n\n @staticmethod\n def float_column(\n name,\n min_value=-float(\"inf\"),\n max_value=float(\"inf\"),\n non_nullable=False,\n unique=False,\n ignore_missing_vals=False,\n is_required=None,\n ):\n \"\"\"\n Simple constructor for PandasColumns that expresses numeric constraints on float dtypes.\n\n Args:\n name (str): Name of the column. This must match up with the column name in the dataframe you\n expect to receive.\n min_value (Optional[Union[int,float]]): The lower bound for values you expect in this column. Defaults to -float('inf')\n max_value (Optional[Union[int,float]]): The upper bound for values you expect in this column. Defaults to float('inf')\n non_nullable (Optional[bool]): If true, this column will enforce a constraint that all values in the column\n ought to be non null values.\n unique (Optional[bool]): If true, this column will enforce a uniqueness constraint on the column values.\n ignore_missing_vals (Optional[bool]): A flag that is passed into most constraints. If true, the constraint will\n only evaluate non-null data. Ignore_missing_vals and non_nullable cannot both be True.\n is_required (Optional[bool]): Flag indicating the optional/required presence of the column.\n If the column exists the validate function will validate the column. Default to True.\n \"\"\"\n return PandasColumn(\n name=check.str_param(name, \"name\"),\n constraints=[\n ColumnDTypeFnConstraint(is_float_dtype),\n InRangeColumnConstraint(\n check.numeric_param(min_value, \"min_value\"),\n check.numeric_param(max_value, \"max_value\"),\n ignore_missing_vals=ignore_missing_vals,\n ),\n ]\n + _construct_keyword_constraints(\n non_nullable=non_nullable, unique=unique, ignore_missing_vals=ignore_missing_vals\n ),\n is_required=is_required,\n )\n\n @staticmethod\n def datetime_column(\n name,\n min_datetime=Timestamp.min,\n max_datetime=Timestamp.max,\n non_nullable=False,\n unique=False,\n ignore_missing_vals=False,\n is_required=None,\n tz=None,\n ):\n \"\"\"\n Simple constructor for PandasColumns that expresses datetime constraints on 'datetime64[ns]' dtypes.\n\n Args:\n name (str): Name of the column. This must match up with the column name in the dataframe you\n expect to receive.\n min_datetime (Optional[Union[int,float]]): The lower bound for values you expect in this column.\n Defaults to pandas.Timestamp.min.\n max_datetime (Optional[Union[int,float]]): The upper bound for values you expect in this column.\n Defaults to pandas.Timestamp.max.\n non_nullable (Optional[bool]): If true, this column will enforce a constraint that all values in the column\n ought to be non null values.\n unique (Optional[bool]): If true, this column will enforce a uniqueness constraint on the column values.\n ignore_missing_vals (Optional[bool]): A flag that is passed into most constraints. If true, the constraint will\n only evaluate non-null data. Ignore_missing_vals and non_nullable cannot both be True.\n is_required (Optional[bool]): Flag indicating the optional/required presence of the column.\n If the column exists the validate function will validate the column. Default to True.\n tz (Optional[str]): Required timezone for values eg: tz='UTC', tz='Europe/Dublin', tz='US/Eastern'.\n Defaults to None, meaning naive datetime values.\n \"\"\"\n if tz is None:\n datetime_constraint = ColumnDTypeInSetConstraint({\"datetime64[ns]\"})\n else:\n datetime_constraint = ColumnDTypeInSetConstraint({f\"datetime64[ns, {tz}]\"})\n # One day more/less than absolute min/max to prevent OutOfBoundsDatetime errors when converting min/max to be tz aware\n if min_datetime.tz_localize(None) == Timestamp.min:\n min_datetime = Timestamp(\"1677-09-22 00:12:43.145225Z\")\n if max_datetime.tz_localize(None) == Timestamp.max:\n max_datetime = Timestamp(\"2262-04-10 23:47:16.854775807Z\")\n # Convert bounds to same tz\n if Timestamp(min_datetime).tz is None:\n min_datetime = Timestamp(min_datetime).tz_localize(tz)\n if Timestamp(max_datetime).tz is None:\n max_datetime = Timestamp(max_datetime).tz_localize(tz)\n\n return PandasColumn(\n name=check.str_param(name, \"name\"),\n constraints=[\n datetime_constraint,\n InRangeColumnConstraint(\n min_datetime, max_datetime, ignore_missing_vals=ignore_missing_vals\n ),\n ]\n + _construct_keyword_constraints(\n non_nullable=non_nullable, unique=unique, ignore_missing_vals=ignore_missing_vals\n ),\n is_required=is_required,\n )\n\n @staticmethod\n def string_column(\n name, non_nullable=False, unique=False, ignore_missing_vals=False, is_required=None\n ):\n \"\"\"\n Simple constructor for PandasColumns that expresses constraints on string dtypes.\n\n Args:\n name (str): Name of the column. This must match up with the column name in the dataframe you\n expect to receive.\n non_nullable (Optional[bool]): If true, this column will enforce a constraint that all values in the column\n ought to be non null values.\n unique (Optional[bool]): If true, this column will enforce a uniqueness constraint on the column values.\n ignore_missing_vals (Optional[bool]): A flag that is passed into most constraints. If true, the constraint will\n only evaluate non-null data. Ignore_missing_vals and non_nullable cannot both be True.\n is_required (Optional[bool]): Flag indicating the optional/required presence of the column.\n If the column exists the validate function will validate the column. Default to True.\n \"\"\"\n return PandasColumn(\n name=check.str_param(name, \"name\"),\n constraints=[ColumnDTypeFnConstraint(is_string_dtype)]\n + _construct_keyword_constraints(\n non_nullable=non_nullable, unique=unique, ignore_missing_vals=ignore_missing_vals\n ),\n is_required=is_required,\n )\n\n @staticmethod\n def categorical_column(\n name,\n categories,\n of_types=\"object\",\n non_nullable=False,\n unique=False,\n ignore_missing_vals=False,\n is_required=None,\n ):\n \"\"\"\n Simple constructor for PandasColumns that expresses categorical constraints on specified dtypes.\n\n Args:\n name (str): Name of the column. This must match up with the column name in the dataframe you\n expect to receive.\n categories (List[Any]): The valid set of buckets that all values in the column must match.\n of_types (Optional[Union[str, Set[str]]]): The expected dtype[s] that your categories and values must\n abide by.\n non_nullable (Optional[bool]): If true, this column will enforce a constraint that all values in\n the column ought to be non null values.\n unique (Optional[bool]): If true, this column will enforce a uniqueness constraint on the column values.\n ignore_missing_vals (Optional[bool]): A flag that is passed into most constraints. If true, the\n constraint will only evaluate non-null data. Ignore_missing_vals and non_nullable cannot both be True.\n is_required (Optional[bool]): Flag indicating the optional/required presence of the column.\n If the column exists the validate function will validate the column. Default to True.\n \"\"\"\n of_types = {of_types} if isinstance(of_types, str) else of_types\n return PandasColumn(\n name=check.str_param(name, \"name\"),\n constraints=[\n ColumnDTypeInSetConstraint(of_types),\n CategoricalColumnConstraint(categories, ignore_missing_vals=ignore_missing_vals),\n ]\n + _construct_keyword_constraints(\n non_nullable=non_nullable, unique=unique, ignore_missing_vals=ignore_missing_vals\n ),\n is_required=is_required,\n )\n\n\ndef validate_constraints(dataframe, pandas_columns=None, dataframe_constraints=None):\n dataframe = check.inst_param(dataframe, \"dataframe\", DataFrame)\n pandas_columns = check.opt_list_param(\n pandas_columns, \"column_constraints\", of_type=PandasColumn\n )\n dataframe_constraints = check.opt_list_param(\n dataframe_constraints, \"dataframe_constraints\", of_type=DataFrameConstraint\n )\n\n if pandas_columns:\n for column in pandas_columns:\n column.validate(dataframe)\n\n if dataframe_constraints:\n for dataframe_constraint in dataframe_constraints:\n dataframe_constraint.validate(dataframe)\n" ]
[ [ "pandas.read_sql_query" ], [ "pandas.Timestamp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
kct22aws/transformers
[ "28e091430eea9e0d40839e56fd0d57aec262f5f9", "28e091430eea9e0d40839e56fd0d57aec262f5f9", "04cddaf402591e9f5bdb5f116a111d829a0ce4f4", "28e091430eea9e0d40839e56fd0d57aec262f5f9" ]
[ "src/transformers/models/convbert/modeling_tf_convbert.py", "src/transformers/models/hubert/modeling_tf_hubert.py", "src/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py", "src/transformers/feature_extraction_sequence_utils.py" ]
[ "# coding=utf-8\n# Copyright 2021 The HuggingFace Inc. team. 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\"\"\" TF 2.0 ConvBERT model.\"\"\"\n\n\nimport tensorflow as tf\n\nfrom ...activations_tf import get_tf_activation\nfrom ...file_utils import (\n MULTIPLE_CHOICE_DUMMY_INPUTS,\n add_code_sample_docstrings,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n)\nfrom ...modeling_tf_outputs import (\n TFBaseModelOutput,\n TFMaskedLMOutput,\n TFMultipleChoiceModelOutput,\n TFQuestionAnsweringModelOutput,\n TFSequenceClassifierOutput,\n TFTokenClassifierOutput,\n)\nfrom ...modeling_tf_utils import (\n TFMaskedLanguageModelingLoss,\n TFMultipleChoiceLoss,\n TFPreTrainedModel,\n TFQuestionAnsweringLoss,\n TFSequenceClassificationLoss,\n TFSequenceSummary,\n TFTokenClassificationLoss,\n get_initializer,\n input_processing,\n keras_serializable,\n shape_list,\n)\nfrom ...utils import logging\nfrom .configuration_convbert import ConvBertConfig\n\n\nlogger = logging.get_logger(__name__)\n\n_CHECKPOINT_FOR_DOC = \"YituTech/conv-bert-base\"\n_CONFIG_FOR_DOC = \"ConvBertConfig\"\n_TOKENIZER_FOR_DOC = \"ConvBertTokenizer\"\n\nTF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"YituTech/conv-bert-base\",\n \"YituTech/conv-bert-medium-small\",\n \"YituTech/conv-bert-small\",\n # See all ConvBERT models at https://huggingface.co/models?filter=convbert\n]\n\n\n# Copied from transformers.models.albert.modeling_tf_albert.TFAlbertEmbeddings with Albert->ConvBert\nclass TFConvBertEmbeddings(tf.keras.layers.Layer):\n \"\"\"Construct the embeddings from word, position and token_type embeddings.\"\"\"\n\n def __init__(self, config: ConvBertConfig, **kwargs):\n super().__init__(**kwargs)\n\n self.vocab_size = config.vocab_size\n self.type_vocab_size = config.type_vocab_size\n self.embedding_size = config.embedding_size\n self.max_position_embeddings = config.max_position_embeddings\n self.initializer_range = config.initializer_range\n self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=\"LayerNorm\")\n self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)\n\n def build(self, input_shape: tf.TensorShape):\n with tf.name_scope(\"word_embeddings\"):\n self.weight = self.add_weight(\n name=\"weight\",\n shape=[self.vocab_size, self.embedding_size],\n initializer=get_initializer(self.initializer_range),\n )\n\n with tf.name_scope(\"token_type_embeddings\"):\n self.token_type_embeddings = self.add_weight(\n name=\"embeddings\",\n shape=[self.type_vocab_size, self.embedding_size],\n initializer=get_initializer(self.initializer_range),\n )\n\n with tf.name_scope(\"position_embeddings\"):\n self.position_embeddings = self.add_weight(\n name=\"embeddings\",\n shape=[self.max_position_embeddings, self.embedding_size],\n initializer=get_initializer(self.initializer_range),\n )\n\n super().build(input_shape)\n\n # Copied from transformers.models.bert.modeling_tf_bert.TFBertEmbeddings.call\n def call(\n self,\n input_ids: tf.Tensor = None,\n position_ids: tf.Tensor = None,\n token_type_ids: tf.Tensor = None,\n inputs_embeds: tf.Tensor = None,\n past_key_values_length=0,\n training: bool = False,\n ) -> tf.Tensor:\n \"\"\"\n Applies embedding based on inputs tensor.\n\n Returns:\n final_embeddings (`tf.Tensor`): output embedding tensor.\n \"\"\"\n if input_ids is None and inputs_embeds is None:\n raise ValueError(\"Need to provide either `input_ids` or `input_embeds`.\")\n\n if input_ids is not None:\n inputs_embeds = tf.gather(params=self.weight, indices=input_ids)\n\n input_shape = shape_list(inputs_embeds)[:-1]\n\n if token_type_ids is None:\n token_type_ids = tf.fill(dims=input_shape, value=0)\n\n if position_ids is None:\n position_ids = tf.expand_dims(\n tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0\n )\n\n position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)\n token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)\n final_embeddings = inputs_embeds + position_embeds + token_type_embeds\n final_embeddings = self.LayerNorm(inputs=final_embeddings)\n final_embeddings = self.dropout(inputs=final_embeddings, training=training)\n\n return final_embeddings\n\n\nclass TFConvBertSelfAttention(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n f\"The hidden size ({config.hidden_size}) is not a multiple of the number of attention \"\n f\"heads ({config.num_attention_heads})\"\n )\n\n new_num_attention_heads = int(config.num_attention_heads / config.head_ratio)\n if new_num_attention_heads < 1:\n self.head_ratio = config.num_attention_heads\n num_attention_heads = 1\n else:\n num_attention_heads = new_num_attention_heads\n self.head_ratio = config.head_ratio\n\n self.num_attention_heads = num_attention_heads\n self.conv_kernel_size = config.conv_kernel_size\n\n assert (\n config.hidden_size % self.num_attention_heads == 0\n ), \"hidden_size should be divisible by num_attention_heads\"\n\n self.attention_head_size = config.hidden_size // config.num_attention_heads\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n self.query = tf.keras.layers.Dense(\n self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name=\"query\"\n )\n self.key = tf.keras.layers.Dense(\n self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name=\"key\"\n )\n self.value = tf.keras.layers.Dense(\n self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name=\"value\"\n )\n\n self.key_conv_attn_layer = tf.keras.layers.SeparableConv1D(\n self.all_head_size,\n self.conv_kernel_size,\n padding=\"same\",\n activation=None,\n depthwise_initializer=get_initializer(1 / self.conv_kernel_size),\n pointwise_initializer=get_initializer(config.initializer_range),\n name=\"key_conv_attn_layer\",\n )\n\n self.conv_kernel_layer = tf.keras.layers.Dense(\n self.num_attention_heads * self.conv_kernel_size,\n activation=None,\n name=\"conv_kernel_layer\",\n kernel_initializer=get_initializer(config.initializer_range),\n )\n\n self.conv_out_layer = tf.keras.layers.Dense(\n self.all_head_size,\n activation=None,\n name=\"conv_out_layer\",\n kernel_initializer=get_initializer(config.initializer_range),\n )\n\n self.dropout = tf.keras.layers.Dropout(config.attention_probs_dropout_prob)\n\n def transpose_for_scores(self, x, batch_size):\n # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]\n x = tf.reshape(x, (batch_size, -1, self.num_attention_heads, self.attention_head_size))\n return tf.transpose(x, perm=[0, 2, 1, 3])\n\n def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):\n batch_size = shape_list(hidden_states)[0]\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 mixed_key_conv_attn_layer = self.key_conv_attn_layer(hidden_states)\n\n query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)\n key_layer = self.transpose_for_scores(mixed_key_layer, batch_size)\n conv_attn_layer = tf.multiply(mixed_key_conv_attn_layer, mixed_query_layer)\n\n conv_kernel_layer = self.conv_kernel_layer(conv_attn_layer)\n conv_kernel_layer = tf.reshape(conv_kernel_layer, [-1, self.conv_kernel_size, 1])\n conv_kernel_layer = tf.nn.softmax(conv_kernel_layer, axis=1)\n\n paddings = tf.constant(\n [\n [\n 0,\n 0,\n ],\n [int((self.conv_kernel_size - 1) / 2), int((self.conv_kernel_size - 1) / 2)],\n [0, 0],\n ]\n )\n\n conv_out_layer = self.conv_out_layer(hidden_states)\n conv_out_layer = tf.reshape(conv_out_layer, [batch_size, -1, self.all_head_size])\n conv_out_layer = tf.pad(conv_out_layer, paddings, \"CONSTANT\")\n\n unfold_conv_out_layer = tf.stack(\n [\n tf.slice(conv_out_layer, [0, i, 0], [batch_size, shape_list(mixed_query_layer)[1], self.all_head_size])\n for i in range(self.conv_kernel_size)\n ],\n axis=-1,\n )\n\n conv_out_layer = tf.reshape(unfold_conv_out_layer, [-1, self.attention_head_size, self.conv_kernel_size])\n\n conv_out_layer = tf.matmul(conv_out_layer, conv_kernel_layer)\n conv_out_layer = tf.reshape(conv_out_layer, [-1, self.all_head_size])\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = tf.matmul(\n query_layer, key_layer, transpose_b=True\n ) # (batch size, num_heads, seq_len_q, seq_len_k)\n dk = tf.cast(shape_list(key_layer)[-1], attention_scores.dtype) # scale attention_scores\n attention_scores = attention_scores / tf.math.sqrt(dk)\n\n if attention_mask is not None:\n # Apply the attention mask is (precomputed for all layers in TFBertModel call() function)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = tf.nn.softmax(attention_scores, axis=-1)\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, training=training)\n\n # Mask heads if we want to\n if head_mask is not None:\n attention_probs = attention_probs * head_mask\n\n value_layer = tf.reshape(\n mixed_value_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size]\n )\n value_layer = tf.transpose(value_layer, [0, 2, 1, 3])\n\n context_layer = tf.matmul(attention_probs, value_layer)\n context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])\n\n conv_out = tf.reshape(conv_out_layer, [batch_size, -1, self.num_attention_heads, self.attention_head_size])\n context_layer = tf.concat([context_layer, conv_out], 2)\n context_layer = tf.reshape(\n context_layer, (batch_size, -1, self.head_ratio * self.all_head_size)\n ) # (batch_size, seq_len_q, all_head_size)\n outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)\n\n return outputs\n\n\nclass TFConvBertSelfOutput(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n self.dense = tf.keras.layers.Dense(\n config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name=\"dense\"\n )\n self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=\"LayerNorm\")\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)\n\n def call(self, hidden_states, input_tensor, training=False):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states, training=training)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n\n return hidden_states\n\n\nclass TFConvBertAttention(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n self.self_attention = TFConvBertSelfAttention(config, name=\"self\")\n self.dense_output = TFConvBertSelfOutput(config, name=\"output\")\n\n def prune_heads(self, heads):\n raise NotImplementedError\n\n def call(self, input_tensor, attention_mask, head_mask, output_attentions, training=False):\n self_outputs = self.self_attention(\n input_tensor, attention_mask, head_mask, output_attentions, training=training\n )\n attention_output = self.dense_output(self_outputs[0], input_tensor, training=training)\n outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them\n\n return outputs\n\n\nclass GroupedLinearLayer(tf.keras.layers.Layer):\n def __init__(self, input_size, output_size, num_groups, kernel_initializer, **kwargs):\n super().__init__(**kwargs)\n self.input_size = input_size\n self.output_size = output_size\n self.num_groups = num_groups\n self.kernel_initializer = kernel_initializer\n self.group_in_dim = self.input_size // self.num_groups\n self.group_out_dim = self.output_size // self.num_groups\n\n def build(self, input_shape):\n self.kernel = self.add_weight(\n \"kernel\",\n shape=[self.group_out_dim, self.group_in_dim, self.num_groups],\n initializer=self.kernel_initializer,\n trainable=True,\n )\n\n self.bias = self.add_weight(\n \"bias\", shape=[self.output_size], initializer=self.kernel_initializer, dtype=self.dtype, trainable=True\n )\n\n def call(self, hidden_states):\n batch_size = shape_list(hidden_states)[0]\n x = tf.transpose(tf.reshape(hidden_states, [-1, self.num_groups, self.group_in_dim]), [1, 0, 2])\n x = tf.matmul(x, tf.transpose(self.kernel, [2, 1, 0]))\n x = tf.transpose(x, [1, 0, 2])\n x = tf.reshape(x, [batch_size, -1, self.output_size])\n x = tf.nn.bias_add(value=x, bias=self.bias)\n return x\n\n\nclass TFConvBertIntermediate(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n if config.num_groups == 1:\n self.dense = tf.keras.layers.Dense(\n config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name=\"dense\"\n )\n else:\n self.dense = GroupedLinearLayer(\n config.hidden_size,\n config.intermediate_size,\n num_groups=config.num_groups,\n kernel_initializer=get_initializer(config.initializer_range),\n name=\"dense\",\n )\n\n if isinstance(config.hidden_act, str):\n self.intermediate_act_fn = get_tf_activation(config.hidden_act)\n else:\n self.intermediate_act_fn = config.hidden_act\n\n def call(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n\n return hidden_states\n\n\nclass TFConvBertOutput(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n if config.num_groups == 1:\n self.dense = tf.keras.layers.Dense(\n config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name=\"dense\"\n )\n else:\n self.dense = GroupedLinearLayer(\n config.intermediate_size,\n config.hidden_size,\n num_groups=config.num_groups,\n kernel_initializer=get_initializer(config.initializer_range),\n name=\"dense\",\n )\n self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=\"LayerNorm\")\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout_prob)\n\n def call(self, hidden_states, input_tensor, training=False):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states, training=training)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n\n return hidden_states\n\n\nclass TFConvBertLayer(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n self.attention = TFConvBertAttention(config, name=\"attention\")\n self.intermediate = TFConvBertIntermediate(config, name=\"intermediate\")\n self.bert_output = TFConvBertOutput(config, name=\"output\")\n\n def call(self, hidden_states, attention_mask, head_mask, output_attentions, training=False):\n attention_outputs = self.attention(\n hidden_states, attention_mask, head_mask, output_attentions, training=training\n )\n attention_output = attention_outputs[0]\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.bert_output(intermediate_output, attention_output, training=training)\n outputs = (layer_output,) + attention_outputs[1:] # add attentions if we output them\n\n return outputs\n\n\nclass TFConvBertEncoder(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n self.layer = [TFConvBertLayer(config, name=f\"layer_._{i}\") for i in range(config.num_hidden_layers)]\n\n def call(\n self,\n hidden_states,\n attention_mask,\n head_mask,\n output_attentions,\n output_hidden_states,\n return_dict,\n training=False,\n ):\n all_hidden_states = () if output_hidden_states else None\n all_attentions = () if output_attentions else None\n\n for i, layer_module in enumerate(self.layer):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n layer_outputs = layer_module(\n hidden_states, attention_mask, head_mask[i], output_attentions, training=training\n )\n hidden_states = layer_outputs[0]\n\n if output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n\n # Add last layer\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)\n\n return TFBaseModelOutput(\n last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions\n )\n\n\nclass TFConvBertPredictionHeadTransform(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n self.dense = tf.keras.layers.Dense(\n config.embedding_size, kernel_initializer=get_initializer(config.initializer_range), name=\"dense\"\n )\n\n if isinstance(config.hidden_act, str):\n self.transform_act_fn = get_tf_activation(config.hidden_act)\n else:\n self.transform_act_fn = config.hidden_act\n\n self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=\"LayerNorm\")\n\n def call(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\n return hidden_states\n\n\n@keras_serializable\nclass TFConvBertMainLayer(tf.keras.layers.Layer):\n config_class = ConvBertConfig\n\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n self.embeddings = TFConvBertEmbeddings(config, name=\"embeddings\")\n\n if config.embedding_size != config.hidden_size:\n self.embeddings_project = tf.keras.layers.Dense(config.hidden_size, name=\"embeddings_project\")\n\n self.encoder = TFConvBertEncoder(config, name=\"encoder\")\n self.config = config\n\n def get_input_embeddings(self):\n return self.embeddings\n\n def set_input_embeddings(self, value):\n self.embeddings.weight = value\n self.embeddings.vocab_size = value.shape[0]\n\n def _prune_heads(self, heads_to_prune):\n \"\"\"\n Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base\n class PreTrainedModel\n \"\"\"\n raise NotImplementedError\n\n def get_extended_attention_mask(self, attention_mask, input_shape, dtype):\n if attention_mask is None:\n attention_mask = tf.fill(input_shape, 1)\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 = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # 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 = tf.cast(extended_attention_mask, dtype)\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n\n return extended_attention_mask\n\n def get_head_mask(self, head_mask):\n if head_mask is not None:\n raise NotImplementedError\n else:\n head_mask = [None] * self.config.num_hidden_layers\n\n return head_mask\n\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n training=False,\n **kwargs,\n ):\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n kwargs_call=kwargs,\n )\n\n if inputs[\"input_ids\"] is not None and inputs[\"inputs_embeds\"] is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif inputs[\"input_ids\"] is not None:\n input_shape = shape_list(inputs[\"input_ids\"])\n elif inputs[\"inputs_embeds\"] is not None:\n input_shape = shape_list(inputs[\"inputs_embeds\"])[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n if inputs[\"attention_mask\"] is None:\n inputs[\"attention_mask\"] = tf.fill(input_shape, 1)\n\n if inputs[\"token_type_ids\"] is None:\n inputs[\"token_type_ids\"] = tf.fill(input_shape, 0)\n\n hidden_states = self.embeddings(\n inputs[\"input_ids\"],\n inputs[\"position_ids\"],\n inputs[\"token_type_ids\"],\n inputs[\"inputs_embeds\"],\n training=inputs[\"training\"],\n )\n extended_attention_mask = self.get_extended_attention_mask(\n inputs[\"attention_mask\"], input_shape, hidden_states.dtype\n )\n inputs[\"head_mask\"] = self.get_head_mask(inputs[\"head_mask\"])\n\n if hasattr(self, \"embeddings_project\"):\n hidden_states = self.embeddings_project(hidden_states, training=inputs[\"training\"])\n\n hidden_states = self.encoder(\n hidden_states,\n extended_attention_mask,\n inputs[\"head_mask\"],\n inputs[\"output_attentions\"],\n inputs[\"output_hidden_states\"],\n inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n\n return hidden_states\n\n\nclass TFConvBertPreTrainedModel(TFPreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = ConvBertConfig\n base_model_prefix = \"convbert\"\n\n\nCONVBERT_START_DOCSTRING = r\"\"\"\n\n This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the\n library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n etc.)\n\n This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it\n as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and\n behavior.\n\n <Tip>\n\n TF 2.0 models accepts two formats as inputs:\n\n - having all inputs as keyword arguments (like PyTorch models), or\n - having all inputs as a list, tuple or dict in the first positional arguments.\n\n This second option is useful when using [`tf.keras.Model.fit`] method which currently requires having all the\n tensors in the first argument of the model call function: `model(inputs)`.\n\n If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the\n first positional argument :\n\n - a single Tensor with `input_ids` only and nothing else: `model(inputs_ids)`\n - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:\n `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`\n - a dictionary with one or several input Tensors associated to the input names given in the docstring:\n `model({\"input_ids\": input_ids, \"token_type_ids\": token_type_ids})`\n\n </Tip>\n\n Args:\n config ([`ConvBertConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n\"\"\"\n\nCONVBERT_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`ConvBertTokenizer`]. See [`PreTrainedTokenizer.__call__`] and\n [`PreTrainedTokenizer.encode`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):\n Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,\n 1]`:\n\n - 0 corresponds to a *sentence A* token,\n - 1 corresponds to a *sentence B* token.\n\n [What are token type IDs?](../glossary#token-type-ids)\n position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n config.max_position_embeddings - 1]`.\n\n [What are position IDs?](../glossary#position-ids)\n head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):\n Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):\n Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n model's internal embedding lookup matrix.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the\n config will be used instead.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail. This argument can be used only in eager mode, in graph mode the value in the config will be\n used instead.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. This argument can be used\n in eager mode, in graph mode the value will always be set to True.\n training (`bool`, *optional*, defaults to `False`):\n Whether or not to use the model in training mode (some modules like dropout modules have different\n behaviors between training and evaluation).\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top.\",\n CONVBERT_START_DOCSTRING,\n)\nclass TFConvBertModel(TFConvBertPreTrainedModel):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n\n self.convbert = TFConvBertMainLayer(config, name=\"convbert\")\n\n @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFBaseModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n training=False,\n **kwargs,\n ):\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.convbert(\n input_ids=inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n\n return outputs\n\n def serving_output(self, output):\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFBaseModelOutput(last_hidden_state=output.last_hidden_state, hidden_states=hs, attentions=attns)\n\n\nclass TFConvBertMaskedLMHead(tf.keras.layers.Layer):\n def __init__(self, config, input_embeddings, **kwargs):\n super().__init__(**kwargs)\n\n self.vocab_size = config.vocab_size\n self.embedding_size = config.embedding_size\n self.input_embeddings = input_embeddings\n\n def build(self, input_shape):\n self.bias = self.add_weight(shape=(self.vocab_size,), initializer=\"zeros\", trainable=True, name=\"bias\")\n\n super().build(input_shape)\n\n def get_output_embeddings(self):\n return self.input_embeddings\n\n def set_output_embeddings(self, value):\n self.input_embeddings.weight = value\n self.input_embeddings.vocab_size = shape_list(value)[0]\n\n def get_bias(self):\n return {\"bias\": self.bias}\n\n def set_bias(self, value):\n self.bias = value[\"bias\"]\n self.vocab_size = shape_list(value[\"bias\"])[0]\n\n def call(self, hidden_states):\n seq_length = shape_list(tensor=hidden_states)[1]\n hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.embedding_size])\n hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)\n hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.vocab_size])\n hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)\n\n return hidden_states\n\n\nclass TFConvBertGeneratorPredictions(tf.keras.layers.Layer):\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=\"LayerNorm\")\n self.dense = tf.keras.layers.Dense(config.embedding_size, name=\"dense\")\n\n def call(self, generator_hidden_states, training=False):\n hidden_states = self.dense(generator_hidden_states)\n hidden_states = get_tf_activation(\"gelu\")(hidden_states)\n hidden_states = self.LayerNorm(hidden_states)\n\n return hidden_states\n\n\n@add_start_docstrings(\"\"\"ConvBERT Model with a `language modeling` head on top.\"\"\", CONVBERT_START_DOCSTRING)\nclass TFConvBertForMaskedLM(TFConvBertPreTrainedModel, TFMaskedLanguageModelingLoss):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, **kwargs)\n\n self.vocab_size = config.vocab_size\n self.convbert = TFConvBertMainLayer(config, name=\"convbert\")\n self.generator_predictions = TFConvBertGeneratorPredictions(config, name=\"generator_predictions\")\n\n if isinstance(config.hidden_act, str):\n self.activation = get_tf_activation(config.hidden_act)\n else:\n self.activation = config.hidden_act\n\n self.generator_lm_head = TFConvBertMaskedLMHead(config, self.convbert.embeddings, name=\"generator_lm_head\")\n\n def get_lm_head(self):\n return self.generator_lm_head\n\n def get_prefix_bias_name(self):\n return self.name + \"/\" + self.generator_lm_head.name\n\n @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFMaskedLMOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,\n config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the\n loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n labels=labels,\n training=training,\n kwargs_call=kwargs,\n )\n generator_hidden_states = self.convbert(\n input_ids=inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n generator_sequence_output = generator_hidden_states[0]\n prediction_scores = self.generator_predictions(generator_sequence_output, training=inputs[\"training\"])\n prediction_scores = self.generator_lm_head(prediction_scores, training=inputs[\"training\"])\n loss = None if inputs[\"labels\"] is None else self.compute_loss(inputs[\"labels\"], prediction_scores)\n\n if not inputs[\"return_dict\"]:\n output = (prediction_scores,) + generator_hidden_states[1:]\n\n return ((loss,) + output) if loss is not None else output\n\n return TFMaskedLMOutput(\n loss=loss,\n logits=prediction_scores,\n hidden_states=generator_hidden_states.hidden_states,\n attentions=generator_hidden_states.attentions,\n )\n\n # Copied from transformers.models.bert.modeling_tf_bert.TFBertForMaskedLM.serving_output\n def serving_output(self, output):\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFMaskedLMOutput(logits=output.logits, hidden_states=hs, attentions=attns)\n\n\nclass TFConvBertClassificationHead(tf.keras.layers.Layer):\n \"\"\"Head for sentence-level classification tasks.\"\"\"\n\n def __init__(self, config, **kwargs):\n super().__init__(**kwargs)\n\n self.dense = tf.keras.layers.Dense(\n config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name=\"dense\"\n )\n classifier_dropout = (\n config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob\n )\n self.dropout = tf.keras.layers.Dropout(classifier_dropout)\n self.out_proj = tf.keras.layers.Dense(\n config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name=\"out_proj\"\n )\n\n self.config = config\n\n def call(self, hidden_states, **kwargs):\n x = hidden_states[:, 0, :] # take <s> token (equiv. to [CLS])\n x = self.dropout(x)\n x = self.dense(x)\n x = get_tf_activation(self.config.hidden_act)(x)\n x = self.dropout(x)\n x = self.out_proj(x)\n\n return x\n\n\n@add_start_docstrings(\n \"\"\"\n ConvBERT Model transformer with a sequence classification/regression head on top e.g., for GLUE tasks.\n \"\"\",\n CONVBERT_START_DOCSTRING,\n)\nclass TFConvBertForSequenceClassification(TFConvBertPreTrainedModel, TFSequenceClassificationLoss):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.num_labels = config.num_labels\n self.convbert = TFConvBertMainLayer(config, name=\"convbert\")\n self.classifier = TFConvBertClassificationHead(config, name=\"classifier\")\n\n @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFSequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n labels=labels,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.convbert(\n inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n logits = self.classifier(outputs[0], training=inputs[\"training\"])\n loss = None if inputs[\"labels\"] is None else self.compute_loss(inputs[\"labels\"], logits)\n\n if not inputs[\"return_dict\"]:\n output = (logits,) + outputs[1:]\n\n return ((loss,) + output) if loss is not None else output\n\n return TFSequenceClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n def serving_output(self, output):\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFSequenceClassifierOutput(logits=output.logits, hidden_states=hs, attentions=attns)\n\n\n@add_start_docstrings(\n \"\"\"\n ConvBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a\n softmax) e.g. for RocStories/SWAG tasks.\n \"\"\",\n CONVBERT_START_DOCSTRING,\n)\nclass TFConvBertForMultipleChoice(TFConvBertPreTrainedModel, TFMultipleChoiceLoss):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n\n self.convbert = TFConvBertMainLayer(config, name=\"convbert\")\n self.sequence_summary = TFSequenceSummary(\n config, initializer_range=config.initializer_range, name=\"sequence_summary\"\n )\n self.classifier = tf.keras.layers.Dense(\n 1, kernel_initializer=get_initializer(config.initializer_range), name=\"classifier\"\n )\n\n @property\n def dummy_inputs(self):\n \"\"\"\n Dummy inputs to build the network.\n\n Returns:\n tf.Tensor with dummy inputs\n \"\"\"\n return {\"input_ids\": tf.convert_to_tensor(MULTIPLE_CHOICE_DUMMY_INPUTS)}\n\n @add_start_docstrings_to_model_forward(\n CONVBERT_INPUTS_DOCSTRING.format(\"batch_size, num_choices, sequence_length\")\n )\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFMultipleChoiceModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`\n where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n labels=labels,\n training=training,\n kwargs_call=kwargs,\n )\n\n if inputs[\"input_ids\"] is not None:\n num_choices = shape_list(inputs[\"input_ids\"])[1]\n seq_length = shape_list(inputs[\"input_ids\"])[2]\n else:\n num_choices = shape_list(inputs[\"inputs_embeds\"])[1]\n seq_length = shape_list(inputs[\"inputs_embeds\"])[2]\n\n flat_input_ids = tf.reshape(inputs[\"input_ids\"], (-1, seq_length)) if inputs[\"input_ids\"] is not None else None\n flat_attention_mask = (\n tf.reshape(inputs[\"attention_mask\"], (-1, seq_length)) if inputs[\"attention_mask\"] is not None else None\n )\n flat_token_type_ids = (\n tf.reshape(inputs[\"token_type_ids\"], (-1, seq_length)) if inputs[\"token_type_ids\"] is not None else None\n )\n flat_position_ids = (\n tf.reshape(inputs[\"position_ids\"], (-1, seq_length)) if inputs[\"position_ids\"] is not None else None\n )\n flat_inputs_embeds = (\n tf.reshape(inputs[\"inputs_embeds\"], (-1, seq_length, shape_list(inputs[\"inputs_embeds\"])[3]))\n if inputs[\"inputs_embeds\"] is not None\n else None\n )\n outputs = self.convbert(\n flat_input_ids,\n flat_attention_mask,\n flat_token_type_ids,\n flat_position_ids,\n inputs[\"head_mask\"],\n flat_inputs_embeds,\n inputs[\"output_attentions\"],\n inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n logits = self.sequence_summary(outputs[0], training=inputs[\"training\"])\n logits = self.classifier(logits)\n reshaped_logits = tf.reshape(logits, (-1, num_choices))\n loss = None if inputs[\"labels\"] is None else self.compute_loss(inputs[\"labels\"], reshaped_logits)\n\n if not inputs[\"return_dict\"]:\n output = (reshaped_logits,) + outputs[1:]\n\n return ((loss,) + output) if loss is not None else output\n\n return TFMultipleChoiceModelOutput(\n loss=loss,\n logits=reshaped_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n @tf.function(\n input_signature=[\n {\n \"input_ids\": tf.TensorSpec((None, None, None), tf.int32, name=\"input_ids\"),\n \"attention_mask\": tf.TensorSpec((None, None, None), tf.int32, name=\"attention_mask\"),\n \"token_type_ids\": tf.TensorSpec((None, None, None), tf.int32, name=\"token_type_ids\"),\n }\n ]\n )\n def serving(self, inputs):\n output = self.call(inputs)\n\n return self.serving_output(output)\n\n def serving_output(self, output):\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFMultipleChoiceModelOutput(logits=output.logits, hidden_states=hs, attentions=attns)\n\n\n@add_start_docstrings(\n \"\"\"\n ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for\n Named-Entity-Recognition (NER) tasks.\n \"\"\",\n CONVBERT_START_DOCSTRING,\n)\nclass TFConvBertForTokenClassification(TFConvBertPreTrainedModel, TFTokenClassificationLoss):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n\n self.num_labels = config.num_labels\n self.convbert = TFConvBertMainLayer(config, name=\"convbert\")\n classifier_dropout = (\n config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob\n )\n self.dropout = tf.keras.layers.Dropout(classifier_dropout)\n self.classifier = tf.keras.layers.Dense(\n config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name=\"classifier\"\n )\n\n @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFTokenClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n labels=labels,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.convbert(\n inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n sequence_output = outputs[0]\n sequence_output = self.dropout(sequence_output, training=inputs[\"training\"])\n logits = self.classifier(sequence_output)\n loss = None if inputs[\"labels\"] is None else self.compute_loss(inputs[\"labels\"], logits)\n\n if not inputs[\"return_dict\"]:\n output = (logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TFTokenClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n def serving_output(self, output):\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFTokenClassifierOutput(logits=output.logits, hidden_states=hs, attentions=attns)\n\n\n@add_start_docstrings(\n \"\"\"\n ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear\n layer on top of the hidden-states output to compute `span start logits` and `span end logits`).\n \"\"\",\n CONVBERT_START_DOCSTRING,\n)\nclass TFConvBertForQuestionAnswering(TFConvBertPreTrainedModel, TFQuestionAnsweringLoss):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n\n self.num_labels = config.num_labels\n self.convbert = TFConvBertMainLayer(config, name=\"convbert\")\n self.qa_outputs = tf.keras.layers.Dense(\n config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name=\"qa_outputs\"\n )\n\n @add_start_docstrings_to_model_forward(CONVBERT_INPUTS_DOCSTRING.format(\"batch_size, sequence_length\"))\n @add_code_sample_docstrings(\n processor_class=_TOKENIZER_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=TFQuestionAnsweringModelOutput,\n config_class=_CONFIG_FOR_DOC,\n )\n def call(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n start_positions=None,\n end_positions=None,\n training=False,\n **kwargs,\n ):\n r\"\"\"\n start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):\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`). Position outside of the sequence\n are not taken into account for computing the loss.\n end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):\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`). Position outside of the sequence\n are not taken into account for computing the loss.\n \"\"\"\n inputs = input_processing(\n func=self.call,\n config=self.config,\n input_ids=input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n start_positions=start_positions,\n end_positions=end_positions,\n training=training,\n kwargs_call=kwargs,\n )\n outputs = self.convbert(\n inputs[\"input_ids\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n sequence_output = outputs[0]\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = tf.split(logits, 2, axis=-1)\n start_logits = tf.squeeze(start_logits, axis=-1)\n end_logits = tf.squeeze(end_logits, axis=-1)\n loss = None\n\n if inputs[\"start_positions\"] is not None and inputs[\"end_positions\"] is not None:\n labels = {\"start_position\": inputs[\"start_positions\"]}\n labels[\"end_position\"] = inputs[\"end_positions\"]\n loss = self.compute_loss(labels, (start_logits, end_logits))\n\n if not inputs[\"return_dict\"]:\n output = (start_logits, end_logits) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TFQuestionAnsweringModelOutput(\n loss=loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n def serving_output(self, output):\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFQuestionAnsweringModelOutput(\n start_logits=output.start_logits, end_logits=output.end_logits, hidden_states=hs, attentions=attns\n )\n", "# coding=utf-8\n# Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. 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\"\"\" TensorFlow Hubert model.\"\"\"\nimport inspect\nimport warnings\nfrom typing import Any, Dict, Optional, Tuple, Union\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom ...activations_tf import get_tf_activation\nfrom ...file_utils import (\n ModelOutput,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n replace_return_docstrings,\n)\nfrom ...modeling_tf_outputs import TFBaseModelOutput, TFCausalLMOutput\nfrom ...modeling_tf_utils import (\n TFPreTrainedModel,\n booleans_processing,\n get_initializer,\n keras_serializable,\n shape_list,\n)\nfrom ...tokenization_utils_base import BatchEncoding\nfrom ...utils import logging\nfrom .configuration_hubert import HubertConfig\n\n\nlogger = logging.get_logger(__name__)\n\n_CONFIG_FOR_DOC = \"HubertConfig\"\n\nTF_HUBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"facebook/hubert-base-ls960\",\n # See all Hubert models at https://huggingface.co/models?filter=hubert\n]\n\nLARGE_NEGATIVE = -1e8\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.input_values_processing\ndef input_values_processing(func, config, input_values, **kwargs):\n \"\"\"\n Process the input of each TensorFlow model including the booleans. In case of a list of symbolic inputs, each input\n has to be named accordingly to the parameters name, i.e. `input_values = tf.keras.Input(shape=(128,),\n dtype='float32', name=\"input_values\")` otherwise the order of the tensors will not be guaranteed during the\n training.\n\n Args:\n func (`callable`):\n The callable function of the TensorFlow model.\n config ([`PretrainedConfig`]):\n The config of the running model.\n **kwargs:\n The inputs of the model.\n\n Returns:\n Two lists, one for the missing layers, and another one for the unexpected layers.\n \"\"\"\n signature = dict(inspect.signature(func).parameters)\n signature.pop(\"kwargs\", None)\n signature.pop(\"self\", None)\n parameter_names = list(signature.keys())\n output = {}\n allowed_types = (tf.Tensor, bool, int, ModelOutput, tuple, list, dict, np.ndarray)\n\n for k, v in kwargs.items():\n if isinstance(v, allowed_types) or v is None:\n output[k] = v\n else:\n raise ValueError(f\"Data of type {type(v)} is not allowed only {allowed_types} is accepted for {k}.\")\n\n if isinstance(input_values, (tuple, list)):\n for i, input in enumerate(input_values):\n # EagerTensors don't allow to use the .name property so we check for a real Tensor\n if type(input) == tf.Tensor:\n # Tensor names have always the pattern `name:id` then we check only the\n # `name` part\n tensor_name = input.name.split(\":\")[0]\n\n if tensor_name in parameter_names:\n output[tensor_name] = input\n else:\n output[parameter_names[i]] = input\n elif isinstance(input, allowed_types) or input is None:\n output[parameter_names[i]] = input\n else:\n raise ValueError(\n f\"Data of type {type(input)} is not allowed only {allowed_types} is accepted for {parameter_names[i]}.\"\n )\n elif isinstance(input_values, (dict, BatchEncoding)):\n if \"inputs\" in input_values:\n warnings.warn(\n \"The `inputs` argument is deprecated and will be removed in a future version, use `input_values` instead.\",\n FutureWarning,\n )\n\n output[\"input_values\"] = input_values.pop(\"inputs\")\n\n if \"decoder_cached_states\" in input_values:\n warnings.warn(\n \"The `decoder_cached_states` argument is deprecated and will be removed in a future version, use `past_key_values` instead.\",\n FutureWarning,\n )\n output[\"past_key_values\"] = input_values.pop(\"decoder_cached_states\")\n\n for k, v in dict(input_values).items():\n if isinstance(v, allowed_types) or v is None:\n output[k] = v\n elif k not in parameter_names and \"args\" not in parameter_names:\n logger.warning(\n f\"The parameter {k} does not belongs to the parameter list {parameter_names} and will be ignored.\"\n )\n continue\n else:\n raise ValueError(f\"Data of type {type(v)} is not allowed only {allowed_types} is accepted for {k}.\")\n else:\n if isinstance(input_values, tf.Tensor) or input_values is None:\n output[parameter_names[0]] = input_values\n else:\n raise ValueError(\n f\"Data of type {type(input_values)} is not allowed only {allowed_types} is accepted for {parameter_names[0]}.\"\n )\n\n for name in parameter_names:\n if name not in list(output.keys()) and name != \"args\":\n output[name] = kwargs.pop(name, signature[name].default)\n\n # When creating a SavedModel TF calls the method with LayerCall.__call__(args, **kwargs)\n # So to respect the proper output we have to add this exception\n if \"args\" in output:\n if output[\"args\"] is not None and type(output[\"args\"]) == tf.Tensor:\n tensor_name = output[\"args\"].name.split(\":\")[0]\n output[tensor_name] = output[\"args\"]\n else:\n # `args` in this case is always the first parameter, then `input_values`\n output[\"input_values\"] = output[\"args\"]\n\n del output[\"args\"]\n\n if \"kwargs\" in output:\n del output[\"kwargs\"]\n\n boolean_dict = {\n k: v\n for k, v in output.items()\n if k in [\"return_dict\", \"output_attentions\", \"output_hidden_states\", \"use_cache\"]\n }\n\n output.update(booleans_processing(config=config, **boolean_dict))\n\n return output\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2._sample_without_replacement\ndef _sample_without_replacement(distribution, num_samples):\n \"\"\"\n Categorical sampling without replacement is currently not implemented. The gumbel-max trick will do for now - see\n https://github.com/tensorflow/tensorflow/issues/9260 for more info\n \"\"\"\n z = -tf.math.log(tf.random.uniform(shape_list(distribution), 0, 1))\n _, indices = tf.nn.top_k(distribution + z, num_samples)\n return indices\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2._scatter_values_on_batch_indices\ndef _scatter_values_on_batch_indices(values, batch_indices, output_shape):\n \"\"\"\n Scatter function as in PyTorch with indices in format (batch_dim, indixes)\n \"\"\"\n indices_shape = shape_list(batch_indices)\n # broadcast batch dim to indices_shape\n broad_casted_batch_dims = tf.reshape(\n tf.broadcast_to(tf.expand_dims(tf.range(indices_shape[0]), axis=-1), indices_shape), [1, -1]\n )\n # transform batch_indices to pair_indices\n pair_indices = tf.transpose(tf.concat([broad_casted_batch_dims, tf.reshape(batch_indices, [1, -1])], 0))\n # scatter values to pair indices\n return tf.scatter_nd(pair_indices, tf.reshape(values, [-1]), output_shape)\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2._compute_mask_indices\ndef _compute_mask_indices(\n shape: Tuple[int, int],\n mask_prob: float,\n mask_length: int,\n min_masks: int = 0,\n) -> tf.Tensor:\n \"\"\"\n Computes random mask spans for a given shape\n\n Args:\n shape: the the shape for which to compute masks.\n should be of size 2 where first element is batch size and 2nd is timesteps\n attention_mask: optional padding mask of the same size as shape, which will prevent masking padded elements\n mask_prob:\n probability for each token to be chosen as start of the span to be masked. this will be multiplied by\n number of timesteps divided by length of mask span to mask approximately this percentage of all elements.\n however due to overlaps, the actual number will be smaller (unless no_overlap is True)\n mask_length: size of the mask\n min_masks: minimum number of masked spans\n\n Adapted from [fairseq's\n data_utils.py](https://github.com/pytorch/fairseq/blob/e0788f7007a8473a76db573985031f3c94201e79/fairseq/data/data_utils.py#L376).\n \"\"\"\n batch_size, sequence_length = shape\n\n if mask_length < 1:\n raise ValueError(\"`mask_length` has to be bigger than 0.\")\n\n if mask_length > sequence_length:\n raise ValueError(\n f\"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length} and `sequence_length`: {sequence_length}`\"\n )\n # compute number of masked spans in batch\n num_masked_spans = int(mask_prob * sequence_length / mask_length + tf.random.uniform((1,)))\n num_masked_spans = max(num_masked_spans, min_masks)\n\n # make sure num masked indices <= sequence_length\n if num_masked_spans * mask_length > sequence_length:\n num_masked_spans = sequence_length // mask_length\n\n # SpecAugment mask to fill\n spec_aug_mask = tf.zeros((batch_size, sequence_length), dtype=tf.int32)\n\n # uniform distribution to sample from, make sure that offset samples are < sequence_length\n uniform_dist = tf.ones((batch_size, sequence_length - (mask_length - 1)))\n\n # get random indices to mask\n spec_aug_mask_idxs = _sample_without_replacement(uniform_dist, num_masked_spans)\n\n # expand masked indices to masked spans\n spec_aug_mask_idxs = tf.expand_dims(spec_aug_mask_idxs, -1)\n spec_aug_mask_idxs = tf.tile(spec_aug_mask_idxs, (1, 1, mask_length))\n spec_aug_mask_idxs = tf.reshape(spec_aug_mask_idxs, (batch_size, num_masked_spans * mask_length))\n\n offsets = tf.range(mask_length)[tf.newaxis, tf.newaxis, :]\n offsets = tf.tile(offsets, (batch_size, num_masked_spans, 1))\n offsets = tf.reshape(offsets, (batch_size, num_masked_spans * mask_length))\n\n spec_aug_mask_idxs = spec_aug_mask_idxs + offsets\n\n # scatter indices to mask\n spec_aug_mask = _scatter_values_on_batch_indices(\n tf.ones_like(spec_aug_mask_idxs), spec_aug_mask_idxs, spec_aug_mask.shape\n )\n\n return spec_aug_mask\n\n\n# Copied from transformers.models.bart.modeling_tf_bart._expand_mask\ndef _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None, past_key_values_length: int = 0):\n \"\"\"\n Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.\n \"\"\"\n src_len = shape_list(mask)[1]\n tgt_len = tgt_len if tgt_len is not None else src_len\n one_cst = tf.constant(1.0)\n mask = tf.cast(mask, dtype=one_cst.dtype)\n expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))\n\n return (one_cst - expanded_mask) * LARGE_NEGATIVE\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2GroupNorm with Wav2Vec2->Hubert\nclass TFHubertGroupNorm(tf.keras.layers.Layer):\n \"\"\"\n From tensorflow-addons https://www.tensorflow.org/addons/api_docs/python/tfa/layers/GroupNormalization\n \"\"\"\n\n def __init__(\n self,\n groups: int = 32,\n axis: int = -1,\n epsilon: float = 1e-3,\n center: bool = True,\n scale: bool = True,\n beta_initializer: tf.keras.initializers.Initializer = \"zeros\",\n gamma_initializer: tf.keras.initializers.Initializer = \"ones\",\n beta_regularizer: tf.keras.regularizers.Regularizer = None,\n gamma_regularizer: tf.keras.regularizers.Regularizer = None,\n beta_constraint: tf.keras.constraints.Constraint = None,\n gamma_constraint: tf.keras.constraints.Constraint = None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.supports_masking = True\n self.groups = groups\n self.axis = axis\n self.epsilon = epsilon\n self.center = center\n self.scale = scale\n self.beta_initializer = tf.keras.initializers.get(beta_initializer)\n self.gamma_initializer = tf.keras.initializers.get(gamma_initializer)\n self.beta_regularizer = tf.keras.regularizers.get(beta_regularizer)\n self.gamma_regularizer = tf.keras.regularizers.get(gamma_regularizer)\n self.beta_constraint = tf.keras.constraints.get(beta_constraint)\n self.gamma_constraint = tf.keras.constraints.get(gamma_constraint)\n self._check_axis()\n\n def build(self, input_shape):\n\n self._check_if_input_shape_is_none(input_shape)\n self._set_number_of_groups_for_instance_norm(input_shape)\n self._check_size_of_dimensions(input_shape)\n self._create_input_spec(input_shape)\n\n self._add_gamma_weight(input_shape)\n self._add_beta_weight(input_shape)\n self.built = True\n super().build(input_shape)\n\n def call(self, inputs):\n\n input_shape = tf.keras.backend.int_shape(inputs)\n tensor_input_shape = tf.shape(inputs)\n\n reshaped_inputs, group_shape = self._reshape_into_groups(inputs, input_shape, tensor_input_shape)\n\n normalized_inputs = self._apply_normalization(reshaped_inputs, input_shape)\n\n is_instance_norm = (input_shape[self.axis] // self.groups) == 1\n if not is_instance_norm:\n outputs = tf.reshape(normalized_inputs, tensor_input_shape)\n else:\n outputs = normalized_inputs\n\n return outputs\n\n def get_config(self):\n config = {\n \"groups\": self.groups,\n \"axis\": self.axis,\n \"epsilon\": self.epsilon,\n \"center\": self.center,\n \"scale\": self.scale,\n \"beta_initializer\": tf.keras.initializers.serialize(self.beta_initializer),\n \"gamma_initializer\": tf.keras.initializers.serialize(self.gamma_initializer),\n \"beta_regularizer\": tf.keras.regularizers.serialize(self.beta_regularizer),\n \"gamma_regularizer\": tf.keras.regularizers.serialize(self.gamma_regularizer),\n \"beta_constraint\": tf.keras.constraints.serialize(self.beta_constraint),\n \"gamma_constraint\": tf.keras.constraints.serialize(self.gamma_constraint),\n }\n base_config = super().get_config()\n return {**base_config, **config}\n\n def compute_output_shape(self, input_shape):\n return input_shape\n\n def _reshape_into_groups(self, inputs, input_shape, tensor_input_shape):\n\n group_shape = [tensor_input_shape[i] for i in range(len(input_shape))]\n is_instance_norm = (input_shape[self.axis] // self.groups) == 1\n if not is_instance_norm:\n group_shape[self.axis] = input_shape[self.axis] // self.groups\n group_shape.insert(self.axis, self.groups)\n group_shape = tf.stack(group_shape)\n reshaped_inputs = tf.reshape(inputs, group_shape)\n return reshaped_inputs, group_shape\n else:\n return inputs, group_shape\n\n def _apply_normalization(self, reshaped_inputs, input_shape):\n\n group_shape = tf.keras.backend.int_shape(reshaped_inputs)\n group_reduction_axes = list(range(1, len(group_shape)))\n is_instance_norm = (input_shape[self.axis] // self.groups) == 1\n if not is_instance_norm:\n axis = -2 if self.axis == -1 else self.axis - 1\n else:\n axis = -1 if self.axis == -1 else self.axis - 1\n group_reduction_axes.pop(axis)\n\n mean, variance = tf.nn.moments(reshaped_inputs, group_reduction_axes, keepdims=True)\n\n gamma, beta = self._get_reshaped_weights(input_shape)\n normalized_inputs = tf.nn.batch_normalization(\n reshaped_inputs,\n mean=mean,\n variance=variance,\n scale=gamma,\n offset=beta,\n variance_epsilon=self.epsilon,\n )\n return normalized_inputs\n\n def _get_reshaped_weights(self, input_shape):\n broadcast_shape = self._create_broadcast_shape(input_shape)\n gamma = None\n beta = None\n if self.scale:\n gamma = tf.reshape(self.gamma, broadcast_shape)\n\n if self.center:\n beta = tf.reshape(self.beta, broadcast_shape)\n return gamma, beta\n\n def _check_if_input_shape_is_none(self, input_shape):\n dim = input_shape[self.axis]\n if dim is None:\n raise ValueError(\n \"Axis \" + str(self.axis) + \" of \"\n \"input tensor should have a defined dimension \"\n \"but the layer received an input with shape \" + str(input_shape) + \".\"\n )\n\n def _set_number_of_groups_for_instance_norm(self, input_shape):\n dim = input_shape[self.axis]\n\n if self.groups == -1:\n self.groups = dim\n\n def _check_size_of_dimensions(self, input_shape):\n\n dim = input_shape[self.axis]\n if dim < self.groups:\n raise ValueError(\n \"Number of groups (\" + str(self.groups) + \") cannot be \"\n \"more than the number of channels (\" + str(dim) + \").\"\n )\n\n if dim % self.groups != 0:\n raise ValueError(\n \"Number of groups (\" + str(self.groups) + \") must be a \"\n \"multiple of the number of channels (\" + str(dim) + \").\"\n )\n\n def _check_axis(self):\n\n if self.axis == 0:\n raise ValueError(\n \"You are trying to normalize your batch axis. Do you want to \"\n \"use tf.layer.batch_normalization instead\"\n )\n\n def _create_input_spec(self, input_shape):\n\n dim = input_shape[self.axis]\n self.input_spec = tf.keras.layers.InputSpec(ndim=len(input_shape), axes={self.axis: dim})\n\n def _add_gamma_weight(self, input_shape):\n\n dim = input_shape[self.axis]\n shape = (dim,)\n\n if self.scale:\n self.gamma = self.add_weight(\n shape=shape,\n name=\"gamma\",\n initializer=self.gamma_initializer,\n regularizer=self.gamma_regularizer,\n constraint=self.gamma_constraint,\n )\n else:\n self.gamma = None\n\n def _add_beta_weight(self, input_shape):\n\n dim = input_shape[self.axis]\n shape = (dim,)\n\n if self.center:\n self.beta = self.add_weight(\n shape=shape,\n name=\"beta\",\n initializer=self.beta_initializer,\n regularizer=self.beta_regularizer,\n constraint=self.beta_constraint,\n )\n else:\n self.beta = None\n\n def _create_broadcast_shape(self, input_shape):\n broadcast_shape = [1] * len(input_shape)\n is_instance_norm = (input_shape[self.axis] // self.groups) == 1\n if not is_instance_norm:\n broadcast_shape[self.axis] = input_shape[self.axis] // self.groups\n broadcast_shape.insert(self.axis, self.groups)\n else:\n broadcast_shape[self.axis] = self.groups\n return broadcast_shape\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2WeightNormConv1D with Wav2Vec2->Hubert\nclass TFHubertWeightNormConv1D(tf.keras.layers.Conv1D):\n \"\"\"Adapted from https://www.tensorflow.org/probability/api_docs/python/tfp/layers/weight_norm/WeightNorm\"\"\"\n\n def __init__(self, filters, kernel_size, groups, explicit_padding, **kwargs):\n super().__init__(\n filters=filters,\n kernel_size=kernel_size,\n groups=groups,\n padding=\"valid\",\n use_bias=True,\n bias_initializer=\"he_normal\",\n **kwargs,\n )\n self.explicit_padding = explicit_padding\n self.filter_axis = 2\n self.initialized = False\n self.kernel_norm_axes = tf.constant([0, 1])\n\n def _init_norm(self):\n \"\"\"Set the norm of the weight vector.\"\"\"\n kernel_norm = tf.sqrt(tf.reduce_sum(tf.square(self.weight_v), axis=self.kernel_norm_axes))\n self.weight_g.assign(kernel_norm[:, tf.newaxis, tf.newaxis])\n\n def _normalize_kernel(self):\n \"\"\"Generate normalized weights.\"\"\"\n kernel = tf.nn.l2_normalize(self.weight_v, axis=self.kernel_norm_axes) * tf.transpose(self.weight_g)\n self.kernel = tf.transpose(kernel)\n\n def build(self, input_shape):\n if not self.built:\n input_shape = input_shape.as_list()\n # Conv1D output shapes are checked at build time since TF 2.7, so we need to account for padding\n input_shape[-2] += self.explicit_padding * 2\n super().build(input_shape)\n\n self.kernel = tf.Variable(tf.transpose(self.kernel), name=\"weight_v\", trainable=True)\n self.weight_v = self.kernel\n\n self.weight_g = self.add_weight(\n name=\"weight_g\",\n shape=(int(self.weight_v.shape[self.filter_axis]), 1, 1),\n initializer=\"ones\",\n dtype=self.weight_v.dtype,\n trainable=True,\n )\n self.bias = self.add_weight(name=\"bias\", shape=(self.filters,), initializer=\"zeros\", trainable=True)\n\n def call(self, inputs):\n if not self.initialized:\n self._init_norm()\n self.initialized = True\n\n self._normalize_kernel()\n\n padded_inputs = tf.pad(inputs, ((0, 0), (self.explicit_padding, self.explicit_padding), (0, 0)))\n output = super().call(padded_inputs)\n\n return output\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2NoLayerNormConvLayer with Wav2Vec2->Hubert\nclass TFHubertNoLayerNormConvLayer(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, layer_id: int = 0, **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.in_conv_dim = config.conv_dim[layer_id] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = tf.keras.layers.Conv1D(\n filters=self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n strides=config.conv_stride[layer_id],\n use_bias=config.conv_bias,\n name=\"conv\",\n )\n self.activation = get_tf_activation(config.feat_extract_activation)\n\n def call(self, hidden_states: tf.Tensor) -> tf.Tensor:\n hidden_states = self.conv(hidden_states)\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2LayerNormConvLayer with Wav2Vec2->Hubert\nclass TFHubertLayerNormConvLayer(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, layer_id: int = 0, **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.in_conv_dim = config.conv_dim[layer_id] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = tf.keras.layers.Conv1D(\n filters=self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n strides=config.conv_stride[layer_id],\n use_bias=config.conv_bias,\n name=\"conv\",\n )\n self.layer_norm = tf.keras.layers.LayerNormalization(name=\"layer_norm\", epsilon=config.layer_norm_eps)\n self.activation = get_tf_activation(config.feat_extract_activation)\n\n def call(self, hidden_states: tf.Tensor) -> tf.Tensor:\n hidden_states = self.conv(hidden_states)\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2GroupNormConvLayer with Wav2Vec2->Hubert\nclass TFHubertGroupNormConvLayer(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, layer_id: int = 0, **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.in_conv_dim = config.conv_dim[layer_id] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = tf.keras.layers.Conv1D(\n filters=self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n strides=config.conv_stride[layer_id],\n use_bias=config.conv_bias,\n name=\"conv\",\n )\n self.activation = get_tf_activation(config.feat_extract_activation)\n self.layer_norm = TFHubertGroupNorm(groups=self.out_conv_dim, epsilon=config.layer_norm_eps, name=\"layer_norm\")\n\n def call(self, hidden_states: tf.Tensor) -> tf.Tensor:\n hidden_states = self.conv(hidden_states)\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2PositionalConvEmbedding with Wav2Vec2->Hubert\nclass TFHubertPositionalConvEmbedding(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.conv = TFHubertWeightNormConv1D(\n filters=config.hidden_size,\n kernel_size=config.num_conv_pos_embeddings,\n groups=config.num_conv_pos_embedding_groups,\n explicit_padding=config.num_conv_pos_embeddings // 2,\n name=\"conv\",\n )\n self.padding = TFHubertSamePadLayer(config.num_conv_pos_embeddings)\n self.activation = get_tf_activation(config.feat_extract_activation)\n\n def call(self, hidden_states: tf.Tensor) -> tf.Tensor:\n hidden_states = self.conv(hidden_states)\n hidden_states = self.padding(hidden_states)\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2SamePadLayer with Wav2Vec2->Hubert\nclass TFHubertSamePadLayer(tf.keras.layers.Layer):\n def __init__(self, num_conv_pos_embeddings, **kwargs):\n super().__init__(**kwargs)\n self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0\n\n def call(self, hidden_states):\n if self.num_pad_remove > 0:\n hidden_states = hidden_states[:, : -self.num_pad_remove, :]\n return hidden_states\n\n\nclass TFHubertFeatureEncoder(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, **kwargs: Any) -> None:\n super().__init__(**kwargs)\n\n if config.feat_extract_norm == \"group\":\n conv_layers = [TFHubertGroupNormConvLayer(config, layer_id=0, name=f\"conv_layers.{0}\")] + [\n TFHubertNoLayerNormConvLayer(config, layer_id=i + 1, name=f\"conv_layers.{i+1}\")\n for i in range(config.num_feat_extract_layers - 1)\n ]\n elif config.feat_extract_norm == \"layer\":\n conv_layers = [\n TFHubertLayerNormConvLayer(config, layer_id=i, name=f\"conv_layers.{i}\")\n for i in range(config.num_feat_extract_layers)\n ]\n else:\n raise ValueError(\n f\"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']\"\n )\n self.conv_layers = conv_layers\n\n def call(self, input_values):\n hidden_states = tf.expand_dims(input_values, -1)\n for conv_layer in self.conv_layers:\n hidden_states = conv_layer(hidden_states)\n return hidden_states\n\n\nclass TFHubertFeatureExtractor(TFHubertFeatureEncoder):\n def __init__(self, config, **kwargs):\n super().__init__(config, **kwargs)\n warnings.warn(\n f\"The class `{self.__class__.__name__}` has been depreciated \"\n \"and will be removed in Transformers v5. \"\n f\"Use `{self.__class__.__bases__[0].__name__}` instead.\",\n FutureWarning,\n )\n\n\nclass TFHubertFeatureProjection(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, **kwargs):\n super().__init__(**kwargs)\n\n self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=\"layer_norm\")\n self.projection = tf.keras.layers.Dense(\n units=config.hidden_size,\n kernel_initializer=get_initializer(config.initializer_range),\n bias_initializer=\"zeros\",\n name=\"projection\",\n )\n self.dropout = tf.keras.layers.Dropout(rate=config.feat_proj_dropout)\n\n def call(self, hidden_states: tf.Tensor, training: bool = False) -> tf.Tensor:\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.projection(hidden_states)\n hidden_states = self.dropout(hidden_states, training=training)\n return hidden_states\n\n\n# Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with TFBart->TFHubert\nclass TFHubertAttention(tf.keras.layers.Layer):\n \"\"\"Multi-headed attention from \"Attention Is All You Need\"\"\"\n\n def __init__(\n self,\n embed_dim: int,\n num_heads: int,\n dropout: float = 0.0,\n is_decoder: bool = False,\n bias: bool = True,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.embed_dim = embed_dim\n\n self.num_heads = num_heads\n self.dropout = tf.keras.layers.Dropout(dropout)\n self.head_dim = embed_dim // num_heads\n assert self.head_dim * num_heads == self.embed_dim, \"embed_dim must be divisible by num_heads\"\n self.scaling = self.head_dim ** -0.5\n self.is_decoder = is_decoder\n\n self.k_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name=\"k_proj\")\n self.q_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name=\"q_proj\")\n self.v_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name=\"v_proj\")\n self.out_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name=\"out_proj\")\n\n def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):\n return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))\n\n def call(\n self,\n hidden_states: tf.Tensor,\n key_value_states: Optional[tf.Tensor] = None,\n past_key_value: Optional[Tuple[Tuple[tf.Tensor]]] = None,\n attention_mask: Optional[tf.Tensor] = None,\n layer_head_mask: Optional[tf.Tensor] = None,\n training=False,\n ) -> Tuple[tf.Tensor, Optional[tf.Tensor]]:\n \"\"\"Input shape: Batch x Time x Channel\"\"\"\n\n # if key_value_states are provided this layer is used as a cross-attention layer\n # for the decoder\n is_cross_attention = key_value_states is not None\n bsz, tgt_len, embed_dim = shape_list(hidden_states)\n\n # get query proj\n query_states = self.q_proj(hidden_states) * self.scaling\n # get key, value proj\n if is_cross_attention and past_key_value is not None:\n # reuse k,v, cross_attentions\n key_states = past_key_value[0]\n value_states = past_key_value[1]\n elif is_cross_attention:\n # cross_attentions\n key_states = self._shape(self.k_proj(key_value_states), -1, bsz)\n value_states = self._shape(self.v_proj(key_value_states), -1, bsz)\n elif past_key_value is not None:\n # reuse k, v, self_attention\n key_states = self._shape(self.k_proj(hidden_states), -1, bsz)\n value_states = self._shape(self.v_proj(hidden_states), -1, bsz)\n key_states = tf.concat([past_key_value[0], key_states], axis=2)\n value_states = tf.concat([past_key_value[1], value_states], axis=2)\n else:\n # self_attention\n key_states = self._shape(self.k_proj(hidden_states), -1, bsz)\n value_states = self._shape(self.v_proj(hidden_states), -1, bsz)\n\n if self.is_decoder:\n # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.\n # Further calls to cross_attention layer can then reuse all cross-attention\n # key/value_states (first \"if\" case)\n # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of\n # all previous decoder key/value_states. Further calls to uni-directional self-attention\n # can concat previous decoder key/value_states to current projected key/value_states (third \"elif\" case)\n # if encoder bi-directional self-attention `past_key_value` is always `None`\n past_key_value = (key_states, value_states)\n\n proj_shape = (bsz * self.num_heads, -1, self.head_dim)\n query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)\n key_states = tf.reshape(key_states, proj_shape)\n value_states = tf.reshape(value_states, proj_shape)\n\n src_len = shape_list(key_states)[1]\n attn_weights = tf.matmul(query_states, key_states, transpose_b=True)\n\n # The tf.debugging asserts are not compliant with XLA then they\n # have to be disabled in other modes than eager.\n if tf.executing_eagerly():\n tf.debugging.assert_equal(\n shape_list(attn_weights),\n [bsz * self.num_heads, tgt_len, src_len],\n message=f\"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {shape_list(attn_weights)}\",\n )\n\n if attention_mask is not None:\n # The tf.debugging asserts are not compliant with XLA then they\n # have to be disabled in other modes than eager.\n if tf.executing_eagerly():\n tf.debugging.assert_equal(\n shape_list(attention_mask),\n [bsz, 1, tgt_len, src_len],\n message=f\"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {shape_list(attention_mask)}\",\n )\n\n attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)\n attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask\n attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))\n\n attn_weights = tf.nn.softmax(attn_weights, axis=-1)\n\n if layer_head_mask is not None:\n # The tf.debugging asserts are not compliant with XLA then they\n # have to be disabled in other modes than eager.\n if tf.executing_eagerly():\n tf.debugging.assert_equal(\n shape_list(layer_head_mask),\n [self.num_heads],\n message=f\"Head mask for a single layer should be of size {(self.num_heads)}, but is {shape_list(layer_head_mask)}\",\n )\n\n attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(\n attn_weights, (bsz, self.num_heads, tgt_len, src_len)\n )\n attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))\n\n attn_probs = self.dropout(attn_weights, training=training)\n attn_output = tf.matmul(attn_probs, value_states)\n\n # The tf.debugging asserts are not compliant with XLA then they\n # have to be disabled in other modes than eager.\n if tf.executing_eagerly():\n tf.debugging.assert_equal(\n shape_list(attn_output),\n [bsz * self.num_heads, tgt_len, self.head_dim],\n message=f\"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {shape_list(attn_output)}\",\n )\n\n attn_output = tf.transpose(\n tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)\n )\n attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))\n\n attn_output = self.out_proj(attn_output)\n attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))\n\n return attn_output, attn_weights, past_key_value\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2FeedForward with Wav2Vec2->Hubert\nclass TFHubertFeedForward(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, **kwargs):\n super().__init__(**kwargs)\n\n self.intermediate_dropout = tf.keras.layers.Dropout(config.activation_dropout)\n\n self.intermediate_dense = tf.keras.layers.Dense(\n units=config.intermediate_size,\n kernel_initializer=get_initializer(config.initializer_range),\n bias_initializer=\"zeros\",\n name=\"intermediate_dense\",\n )\n self.intermediate_act_fn = get_tf_activation(config.hidden_act)\n\n self.output_dense = tf.keras.layers.Dense(\n units=config.hidden_size,\n kernel_initializer=get_initializer(config.initializer_range),\n bias_initializer=\"zeros\",\n name=\"output_dense\",\n )\n self.output_dropout = tf.keras.layers.Dropout(config.hidden_dropout)\n\n def call(self, hidden_states: tf.Tensor, training: bool = False) -> tf.Tensor:\n hidden_states = self.intermediate_dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n hidden_states = self.intermediate_dropout(hidden_states, training=training)\n\n hidden_states = self.output_dense(hidden_states)\n hidden_states = self.output_dropout(hidden_states, training=training)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2EncoderLayer with Wav2Vec2->Hubert\nclass TFHubertEncoderLayer(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, **kwargs):\n super().__init__(**kwargs)\n self.attention = TFHubertAttention(\n embed_dim=config.hidden_size,\n num_heads=config.num_attention_heads,\n dropout=config.attention_dropout,\n is_decoder=False,\n name=\"attention\",\n )\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout)\n self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=\"layer_norm\")\n self.feed_forward = TFHubertFeedForward(config, name=\"feed_forward\")\n self.final_layer_norm = tf.keras.layers.LayerNormalization(\n epsilon=config.layer_norm_eps, name=\"final_layer_norm\"\n )\n\n def call(\n self,\n hidden_states: tf.Tensor,\n attention_mask: Optional[tf.Tensor] = None,\n output_attentions: Optional[bool] = False,\n training: bool = False,\n ) -> Tuple[tf.Tensor]:\n attn_residual = hidden_states\n hidden_states, attn_weights, _ = self.attention(\n hidden_states, attention_mask=attention_mask, training=training\n )\n hidden_states = self.dropout(hidden_states, training=training)\n hidden_states = attn_residual + hidden_states\n\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = hidden_states + self.feed_forward(hidden_states)\n hidden_states = self.final_layer_norm(hidden_states)\n\n outputs = (hidden_states,)\n\n if output_attentions:\n outputs += (attn_weights,)\n\n return outputs\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2EncoderLayerStableLayerNorm with Wav2Vec2->Hubert\nclass TFHubertEncoderLayerStableLayerNorm(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, **kwargs):\n super().__init__(**kwargs)\n self.attention = TFHubertAttention(\n embed_dim=config.hidden_size,\n num_heads=config.num_attention_heads,\n dropout=config.attention_dropout,\n is_decoder=False,\n name=\"attention\",\n )\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout)\n self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=\"layer_norm\")\n self.feed_forward = TFHubertFeedForward(config, name=\"feed_forward\")\n self.final_layer_norm = tf.keras.layers.LayerNormalization(\n epsilon=config.layer_norm_eps, name=\"final_layer_norm\"\n )\n\n def call(\n self,\n hidden_states: tf.Tensor,\n attention_mask: Optional[tf.Tensor] = None,\n output_attentions: Optional[bool] = False,\n training: bool = False,\n ) -> Tuple[tf.Tensor]:\n attn_residual = hidden_states\n hidden_states = self.layer_norm(hidden_states)\n hidden_states, attn_weights, _ = self.attention(\n hidden_states, attention_mask=attention_mask, training=training\n )\n hidden_states = self.dropout(hidden_states, training=training)\n hidden_states = attn_residual + hidden_states\n hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))\n\n outputs = (hidden_states,)\n\n if output_attentions:\n outputs += (attn_weights,)\n\n return outputs\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2Encoder with Wav2Vec2->Hubert\nclass TFHubertEncoder(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, **kwargs):\n super().__init__(**kwargs)\n self.config = config\n self.pos_conv_embed = TFHubertPositionalConvEmbedding(config, name=\"pos_conv_embed\")\n self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=\"layer_norm\")\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout)\n self.layer = [TFHubertEncoderLayer(config, name=f\"layers.{i}\") for i in range(config.num_hidden_layers)]\n\n def call(\n self,\n hidden_states: tf.Tensor,\n attention_mask: Optional[tf.Tensor] = None,\n output_attentions: Optional[bool] = False,\n output_hidden_states: Optional[bool] = False,\n return_dict: Optional[bool] = True,\n training: Optional[bool] = False,\n ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:\n all_hidden_states = () if output_hidden_states else None\n all_self_attentions = () if output_attentions else None\n\n if attention_mask is not None:\n hidden_states = hidden_states * tf.expand_dims(attention_mask, -1)\n attention_mask = _expand_mask(attention_mask)\n else:\n attention_mask = None\n\n position_embeddings = self.pos_conv_embed(hidden_states)\n hidden_states = hidden_states + position_embeddings\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.dropout(hidden_states, training=training)\n\n for i, layer_module in enumerate(self.layer):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = np.random.uniform(0, 1)\n if training and (dropout_probability < self.config.layerdrop): # skip the layer\n continue\n\n layer_outputs = layer_module(\n hidden_states=hidden_states,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n training=training,\n )\n hidden_states = layer_outputs[0]\n\n if output_attentions:\n all_self_attentions = all_self_attentions + (layer_outputs[1],)\n\n # Add last layer\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)\n return TFBaseModelOutput(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n attentions=all_self_attentions,\n )\n\n\n# Copied from transformers.models.wav2vec2.modeling_tf_wav2vec2.TFWav2Vec2EncoderStableLayerNorm with Wav2Vec2->Hubert\nclass TFHubertEncoderStableLayerNorm(tf.keras.layers.Layer):\n def __init__(self, config: HubertConfig, **kwargs):\n super().__init__(**kwargs)\n self.config = config\n self.pos_conv_embed = TFHubertPositionalConvEmbedding(config, name=\"pos_conv_embed\")\n self.layer_norm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=\"layer_norm\")\n self.dropout = tf.keras.layers.Dropout(config.hidden_dropout)\n self.layer = [\n TFHubertEncoderLayerStableLayerNorm(config, name=f\"layers.{i}\") for i in range(config.num_hidden_layers)\n ]\n\n def call(\n self,\n hidden_states: tf.Tensor,\n attention_mask: Optional[tf.Tensor] = None,\n output_attentions: Optional[bool] = False,\n output_hidden_states: Optional[bool] = False,\n return_dict: Optional[bool] = True,\n training: Optional[bool] = False,\n ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:\n all_hidden_states = () if output_hidden_states else None\n all_self_attentions = () if output_attentions else None\n\n if attention_mask is not None:\n hidden_states = hidden_states * tf.expand_dims(attention_mask, -1)\n attention_mask = _expand_mask(attention_mask)\n else:\n attention_mask = None\n\n position_embeddings = self.pos_conv_embed(hidden_states)\n hidden_states = hidden_states + position_embeddings\n hidden_states = self.dropout(hidden_states, training=training)\n\n for i, layer_module in enumerate(self.layer):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = np.random.uniform(0, 1)\n if training and (dropout_probability < self.config.layerdrop): # skip the layer\n continue\n\n layer_outputs = layer_module(\n hidden_states=hidden_states,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n training=training,\n )\n hidden_states = layer_outputs[0]\n\n if output_attentions:\n all_self_attentions = all_self_attentions + (layer_outputs[1],)\n\n hidden_states = self.layer_norm(hidden_states)\n\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)\n return TFBaseModelOutput(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n attentions=all_self_attentions,\n )\n\n\n@keras_serializable\nclass TFHubertMainLayer(tf.keras.layers.Layer):\n config_class = HubertConfig\n\n def __init__(self, config: HubertConfig, **kwargs):\n super().__init__(**kwargs)\n self.config = config\n self.feature_extractor = TFHubertFeatureEncoder(config, name=\"feature_extractor\")\n self.feature_projection = TFHubertFeatureProjection(config, name=\"feature_projection\")\n\n if config.do_stable_layer_norm:\n self.encoder = TFHubertEncoderStableLayerNorm(config, name=\"encoder\")\n else:\n self.encoder = TFHubertEncoder(config, name=\"encoder\")\n\n def build(self, input_shape: tf.TensorShape):\n self.masked_spec_embed = self.add_weight(\n shape=(self.config.hidden_size,), initializer=\"uniform\", trainable=True, name=\"masked_spec_embed\"\n )\n\n super().build(input_shape)\n\n def _get_feat_extract_output_lengths(self, input_lengths: tf.Tensor):\n \"\"\"\n Computes the output length of the convolutional layers\n \"\"\"\n\n def _conv_out_length(input_length, kernel_size, stride):\n # 1D convolutional layer output length formula taken\n # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html\n return (input_length - kernel_size) // stride + 1\n\n for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):\n input_lengths = _conv_out_length(input_lengths, kernel_size, stride)\n\n return input_lengths\n\n def _mask_hidden_states(self, hidden_states: tf.Tensor, mask_time_indices: Optional[tf.Tensor] = None):\n \"\"\"\n Masks extracted features along time axis and/or along feature axis according to\n [SpecAugment](https://arxiv.org/abs/1904.08779).\n \"\"\"\n batch_size, sequence_length, hidden_size = shape_list(hidden_states)\n\n # `config.apply_spec_augment` can set masking to False\n if not getattr(self.config, \"apply_spec_augment\", True):\n return hidden_states\n\n if mask_time_indices is not None:\n # apply SpecAugment along time axis with given mask_time_indices\n hidden_states = tf.where(\n tf.cast(mask_time_indices[:, :, tf.newaxis], tf.bool),\n self.masked_spec_embed[tf.newaxis, tf.newaxis, :],\n hidden_states,\n )\n\n elif self.config.mask_time_prob > 0:\n # generate indices & apply SpecAugment along time axis\n mask_time_indices = _compute_mask_indices(\n (batch_size, sequence_length),\n mask_prob=self.config.mask_time_prob,\n mask_length=self.config.mask_time_length,\n min_masks=2,\n )\n hidden_states = tf.where(\n tf.cast(mask_time_indices[:, :, tf.newaxis], tf.bool),\n self.masked_spec_embed[tf.newaxis, tf.newaxis, :],\n hidden_states,\n )\n\n # apply SpecAugment along feature axis\n if self.config.mask_feature_prob > 0:\n mask_feature_indices = _compute_mask_indices(\n (batch_size, hidden_size),\n mask_prob=self.config.mask_feature_prob,\n mask_length=self.config.mask_feature_length,\n )\n hidden_states = tf.where(mask_feature_indices[:, tf.newaxis, :], hidden_states, 0)\n\n return hidden_states\n\n def call(\n self,\n input_values: tf.Tensor,\n attention_mask: Optional[tf.Tensor] = None,\n token_type_ids: Optional[tf.Tensor] = None,\n position_ids: Optional[tf.Tensor] = None,\n head_mask: Optional[tf.Tensor] = None,\n inputs_embeds: Optional[tf.Tensor] = None,\n output_attentions: Optional[tf.Tensor] = None,\n output_hidden_states: Optional[tf.Tensor] = None,\n return_dict: Optional[bool] = None,\n training: bool = False,\n **kwargs: Any,\n ):\n inputs = input_values_processing(\n func=self.call,\n config=self.config,\n input_values=input_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n kwargs_call=kwargs,\n )\n\n hidden_states = self.feature_extractor(\n tf.cast(inputs[\"input_values\"], tf.float32), training=inputs[\"training\"]\n )\n\n if inputs[\"attention_mask\"] is not None:\n # compute real output lengths according to convolution formula\n output_lengths = self._get_feat_extract_output_lengths(tf.reduce_sum(inputs[\"attention_mask\"], -1))\n\n attention_mask = tf.sequence_mask(\n output_lengths, maxlen=shape_list(hidden_states)[1], dtype=hidden_states.dtype\n )\n\n hidden_states = self.feature_projection(hidden_states, training=inputs[\"training\"])\n\n mask_time_indices = kwargs.get(\"mask_time_indices\", None)\n if inputs[\"training\"]:\n hidden_states = self._mask_hidden_states(hidden_states, mask_time_indices=mask_time_indices)\n\n encoder_outputs = self.encoder(\n hidden_states,\n attention_mask=attention_mask,\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n hidden_states = encoder_outputs[0]\n\n if not inputs[\"return_dict\"]:\n return (hidden_states,) + encoder_outputs[1:]\n\n return TFBaseModelOutput(\n last_hidden_state=hidden_states,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n )\n\n\nclass TFHubertPreTrainedModel(TFPreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = HubertConfig\n base_model_prefix = \"hubert\"\n main_input_name = \"input_values\"\n\n @property\n def dummy_inputs(self) -> Dict[str, tf.Tensor]:\n pad_token = 0.0\n input_values = tf.convert_to_tensor(np.random.rand(1, 16000), tf.float32)\n dummy_inputs = {\n \"input_values\": input_values,\n \"attention_mask\": tf.cast(tf.not_equal(input_values, pad_token), tf.float32),\n }\n return dummy_inputs\n\n @tf.function\n def serving(self, inputs):\n output = self.call(input_values=inputs, training=False)\n\n return self.serving_output(output)\n\n\nHUBERT_START_DOCSTRING = r\"\"\"\n\n This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the\n library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n etc.)\n\n This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it\n as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and\n behavior.\n\n <Tip>\n\n TF 2.0 models accepts two formats as inputs:\n\n - having all inputs as keyword arguments (like PyTorch models), or\n - having all inputs as a list, tuple or dict in the first positional arguments.\n\n This second option is useful when using [`tf.keras.Model.fit`] method which currently requires having all the\n tensors in the first argument of the model call function: `model(inputs)`.\n\n If you choose this second option, there are three possibilities you can use to gather all the input Tensors in the\n first positional argument :\n\n - a single Tensor with `input_values` only and nothing else: `model(inputs_ids)`\n - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:\n `model([input_values, attention_mask])` or `model([input_values, attention_mask, token_type_ids])`\n - a dictionary with one or several input Tensors associated to the input names given in the docstring:\n `model({\"input_values\": input_values, \"token_type_ids\": token_type_ids})`\n\n </Tip>\n\n Args:\n config ([`HubertConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n\"\"\"\n\nHUBERT_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_values (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `({0})`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.__call__`] and\n [`PreTrainedTokenizer.encode`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n token_type_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):\n Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,\n 1]`:\n\n - 0 corresponds to a *sentence A* token,\n - 1 corresponds to a *sentence B* token.\n\n [What are token type IDs?](../glossary#token-type-ids)\n position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n config.max_position_embeddings - 1]`.\n\n [What are position IDs?](../glossary#position-ids)\n head_mask (`np.ndarray` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):\n Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n inputs_embeds (`np.ndarray` or `tf.Tensor` of shape `({0}, hidden_size)`, *optional*):\n Optionally, instead of passing `input_values` you can choose to directly pass an embedded representation.\n This is useful if you want more control over how to convert `input_values` indices into associated vectors\n than the model's internal embedding lookup matrix.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the\n config will be used instead.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail. This argument can be used only in eager mode, in graph mode the value in the config will be\n used instead.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. This argument can be used\n in eager mode, in graph mode the value will always be set to True.\n training (`bool`, *optional*, defaults to `False``):\n Whether or not to use the model in training mode (some modules like dropout modules have different\n behaviors between training and evaluation).\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare TFHubert Model transformer outputing raw hidden-states without any specific head on top.\",\n HUBERT_START_DOCSTRING,\n)\nclass TFHubertModel(TFHubertPreTrainedModel):\n def __init__(self, config: HubertConfig, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.config = config\n self.hubert = TFHubertMainLayer(config, name=\"hubert\")\n\n @add_start_docstrings_to_model_forward(HUBERT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFBaseModelOutput, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_values: tf.Tensor,\n attention_mask: Optional[tf.Tensor] = None,\n token_type_ids: Optional[tf.Tensor] = None,\n position_ids: Optional[tf.Tensor] = None,\n head_mask: Optional[tf.Tensor] = None,\n inputs_embeds: Optional[tf.Tensor] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: bool = False,\n ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]:\n \"\"\"\n\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import Wav2Vec2Processor, TFHubertModel\n >>> from datasets import load_dataset\n >>> import soundfile as sf\n\n >>> processor = Wav2Vec2Processor.from_pretrained(\"facebook/hubert-base-960h\")\n >>> model = TFHubertModel.from_pretrained(\"facebook/hubert-base-960h\")\n\n\n >>> def map_to_array(batch):\n ... speech, _ = sf.read(batch[\"file\"])\n ... batch[\"speech\"] = speech\n ... return batch\n\n\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n >>> ds = ds.map(map_to_array)\n\n >>> input_values = processor(ds[\"speech\"][0], return_tensors=\"tf\").input_values # Batch size 1\n >>> hidden_states = model(input_values).last_hidden_state\n ```\"\"\"\n\n inputs = input_values_processing(\n func=self.call,\n config=self.config,\n input_values=input_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n inputs[\"output_hidden_states\"] = (\n inputs[\"output_hidden_states\"] if inputs[\"output_hidden_states\"] else self.config.output_hidden_states\n )\n inputs[\"output_attentions\"] = (\n inputs[\"output_attentions\"] if inputs[\"output_attentions\"] else self.config.output_attentions\n )\n inputs[\"return_dict\"] = inputs[\"return_dict\"] if inputs[\"return_dict\"] else self.config.return_dict\n\n outputs = self.hubert(\n input_values=inputs[\"input_values\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n\n return outputs\n\n def serving_output(self, output):\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n\n return TFBaseModelOutput(last_hidden_state=output.last_hidden_state, hidden_states=hs, attentions=attns)\n\n\n@add_start_docstrings(\n \"\"\"TFHubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\"\"\",\n HUBERT_START_DOCSTRING,\n)\nclass TFHubertForCTC(TFHubertPreTrainedModel):\n def __init__(self, config: HubertConfig, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n\n self.hubert = TFHubertMainLayer(config, name=\"hubert\")\n self.dropout = tf.keras.layers.Dropout(config.final_dropout)\n self.lm_head = tf.keras.layers.Dense(config.vocab_size, name=\"lm_head\")\n\n def freeze_feature_extractor(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameters will\n not be updated during training.\n \"\"\"\n warnings.warn(\n \"The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5.\"\n \"Please use the equivalent `freeze_feature_encoder` method instead.\",\n FutureWarning,\n )\n self.freeze_feature_encoder()\n\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.hubert.feature_extractor.trainable = False\n\n @add_start_docstrings_to_model_forward(HUBERT_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=TFCausalLMOutput, config_class=_CONFIG_FOR_DOC)\n def call(\n self,\n input_values: tf.Tensor,\n attention_mask: Optional[tf.Tensor] = None,\n token_type_ids: Optional[tf.Tensor] = None,\n position_ids: Optional[tf.Tensor] = None,\n head_mask: Optional[tf.Tensor] = None,\n inputs_embeds: Optional[tf.Tensor] = None,\n output_attentions: Optional[bool] = None,\n labels: Optional[tf.Tensor] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n training: Optional[bool] = False,\n ) -> Union[TFCausalLMOutput, Tuple[tf.Tensor]]:\n r\"\"\"\n labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,\n config.vocab_size]` (see `input_values` docstring) Tokens with indices set to `-100` are ignored (masked),\n the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`\n\n Returns:\n\n Example:\n\n ```python\n >>> import tensorflow as tf\n >>> from transformers import Wav2Vec2Processor, TFHubertForCTC\n >>> from datasets import load_dataset\n >>> import soundfile as sf\n\n >>> processor = Wav2Vec2Processor.from_pretrained(\"facebook/hubert-base-960h\")\n >>> model = TFHubertForCTC.from_pretrained(\"facebook/hubert-base-960h\")\n\n\n >>> def map_to_array(batch):\n ... speech, _ = sf.read(batch[\"file\"])\n ... batch[\"speech\"] = speech\n ... return batch\n\n\n >>> ds = load_dataset(\"hf-internal-testing/librispeech_asr_dummy\", \"clean\", split=\"validation\")\n >>> ds = ds.map(map_to_array)\n\n >>> input_values = processor(ds[\"speech\"][0], return_tensors=\"tf\").input_values # Batch size 1\n >>> logits = model(input_values).logits\n >>> predicted_ids = tf.argmax(logits, axis=-1)\n\n >>> transcription = processor.decode(predicted_ids[0])\n\n >>> # compute loss\n >>> target_transcription = \"A MAN SAID TO THE UNIVERSE SIR I EXIST\"\n\n >>> # wrap processor as target processor to encode labels\n >>> with processor.as_target_processor():\n ... labels = processor(transcription, return_tensors=\"tf\").input_values\n\n >>> loss = model(input_values, labels=labels).loss\n ```\"\"\"\n inputs = input_values_processing(\n func=self.call,\n config=self.config,\n input_values=input_values,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n training=training,\n )\n\n outputs = self.hubert(\n input_values=inputs[\"input_values\"],\n attention_mask=inputs[\"attention_mask\"],\n token_type_ids=inputs[\"token_type_ids\"],\n position_ids=inputs[\"position_ids\"],\n head_mask=inputs[\"head_mask\"],\n inputs_embeds=inputs[\"inputs_embeds\"],\n output_attentions=inputs[\"output_attentions\"],\n output_hidden_states=inputs[\"output_hidden_states\"],\n return_dict=inputs[\"return_dict\"],\n training=inputs[\"training\"],\n )\n hidden_states = outputs[0]\n hidden_states = self.dropout(hidden_states, training=inputs[\"training\"])\n\n logits = self.lm_head(hidden_states)\n\n if labels is not None:\n\n if tf.reduce_max(labels) >= self.config.vocab_size:\n raise ValueError(f\"Label values must be <= vocab_size: {self.config.vocab_size}\")\n\n attention_mask = (\n inputs[\"attention_mask\"]\n if inputs[\"attention_mask\"] is not None\n else tf.ones_like(inputs[\"input_values\"], dtype=tf.float32)\n )\n input_lengths = self.hubert._get_feat_extract_output_lengths(tf.reduce_sum(attention_mask, axis=-1))\n\n # assuming that padded tokens are filled with -100\n # when not being attended to\n labels_mask = tf.cast(labels >= 0, tf.int32)\n target_lengths = tf.reduce_sum(labels_mask, axis=-1)\n\n loss = tf.nn.ctc_loss(\n logits=logits,\n labels=labels,\n logit_length=input_lengths,\n label_length=target_lengths,\n blank_index=self.config.pad_token_id,\n logits_time_major=False,\n )\n\n if self.config.ctc_loss_reduction == \"sum\":\n loss = tf.reduce_sum(loss)\n if self.config.ctc_loss_reduction == \"mean\":\n loss = tf.reduce_mean(loss)\n else:\n loss = None\n\n if not inputs[\"return_dict\"]:\n output = (logits,) + outputs[1:]\n return ((loss,) + output) if loss is not None else output\n\n return TFCausalLMOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n def serving_output(self, output: TFCausalLMOutput) -> TFCausalLMOutput:\n hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None\n attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None\n return TFCausalLMOutput(logits=output.logits, hidden_states=hs, attentions=attns)\n", "# coding=utf-8\n# Copyright 2021 The Facebook, Inc. and The HuggingFace Inc. team. 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\"\"\" Flax BlenderbotSmall model.\"\"\"\n\n\nimport math\nimport random\nfrom functools import partial\nfrom typing import Callable, Optional, Tuple\n\nimport numpy as np\n\nimport flax.linen as nn\nimport jax\nimport jax.numpy as jnp\nfrom flax.core.frozen_dict import FrozenDict, unfreeze\nfrom flax.linen import combine_masks, make_causal_mask\nfrom flax.linen.attention import dot_product_attention_weights\nfrom jax import lax\nfrom jax.random import PRNGKey\n\nfrom ...file_utils import add_start_docstrings, replace_return_docstrings\nfrom ...modeling_flax_outputs import (\n FlaxBaseModelOutput,\n FlaxBaseModelOutputWithPastAndCrossAttentions,\n FlaxCausalLMOutputWithCrossAttentions,\n FlaxSeq2SeqLMOutput,\n FlaxSeq2SeqModelOutput,\n)\nfrom ...modeling_flax_utils import (\n ACT2FN,\n FlaxPreTrainedModel,\n append_call_sample_docstring,\n append_replace_return_docstrings,\n overwrite_call_docstring,\n)\nfrom ...utils import logging\nfrom .configuration_blenderbot_small import BlenderbotSmallConfig\n\n\nlogger = logging.get_logger(__name__)\n\n_CHECKPOINT_FOR_DOC = \"facebook/blenderbot_small-90M\"\n_CONFIG_FOR_DOC = \"BlenderbotSmallConfig\"\n_TOKENIZER_FOR_DOC = \"BlenderbotSmallTokenizer\"\n\nBLENDERBOT_SMALL_START_DOCSTRING = r\"\"\"\n This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the\n library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n etc.)\n\n This model is also a Flax Linen\n [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a\n regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.\n\n Finally, this model supports inherent JAX features such as:\n\n - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)\n - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)\n - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)\n - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)\n\n Parameters:\n config ([`BlenderbotSmallConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.\n dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):\n The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and\n `jax.numpy.bfloat16` (on TPUs).\n\n This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If\n specified all the computation will be performed with the given `dtype`.\n\n **Note that this only specifies the dtype of the computation and does not influence the dtype of model\n parameters.**\n\n If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and\n [`~FlaxPreTrainedModel.to_bf16`].\n\"\"\"\n\nBLENDERBOT_SMALL_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide\n it.\n\n Indices can be obtained using [`BlenderbotSmallTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):\n Indices of decoder input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`BlenderbotSmallTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are decoder input IDs?](../glossary#decoder-input-ids)\n\n For translation and summarization training, `decoder_input_ids` should be provided. If no\n `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right\n for denoising pre-training following the paper.\n decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):\n Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also\n be used by default.\n\n If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the\n paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.\n position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n config.max_position_embeddings - 1]`.\n decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the\n range `[0, config.max_position_embeddings - 1]`.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\n\n\nBLENDERBOT_SMALL_ENCODE_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide\n it.\n\n Indices can be obtained using [`BlenderbotSmallTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,\n config.max_position_embeddings - 1]`.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\n\nBLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING = r\"\"\"\n Args:\n decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):\n Indices of decoder input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`BlenderbotSmallTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are decoder input IDs?](../glossary#decoder-input-ids)\n\n For translation and summarization training, `decoder_input_ids` should be provided. If no\n `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right\n for denoising pre-training following the paper.\n encoder_outputs (`tuple(tuple(jnp.ndarray)`):\n Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)\n `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of\n hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.\n encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):\n Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also\n be used by default.\n\n If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the\n paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.\n decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):\n Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the\n range `[0, config.max_position_embeddings - 1]`.\n past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):\n Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast\n auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\n\n\n# Copied from transformers.models.bart.modeling_flax_bart.shift_tokens_right\ndef shift_tokens_right(input_ids: jnp.ndarray, pad_token_id: int, decoder_start_token_id: int) -> jnp.ndarray:\n \"\"\"\n Shift input ids one token to the right.\n \"\"\"\n shifted_input_ids = np.zeros_like(input_ids)\n shifted_input_ids[:, 1:] = input_ids[:, :-1]\n shifted_input_ids[:, 0] = decoder_start_token_id\n\n shifted_input_ids = np.where(shifted_input_ids == -100, pad_token_id, shifted_input_ids)\n return shifted_input_ids\n\n\n# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention with Bart->BlenderbotSmall\nclass FlaxBlenderbotSmallAttention(nn.Module):\n config: BlenderbotSmallConfig\n embed_dim: int\n num_heads: int\n dropout: float = 0.0\n causal: bool = False\n bias: bool = True\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n def setup(self) -> None:\n self.head_dim = self.embed_dim // self.num_heads\n if self.head_dim * self.num_heads != self.embed_dim:\n raise ValueError(\n f\"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}\"\n f\" and `num_heads`: {self.num_heads}).\"\n )\n\n dense = partial(\n nn.Dense,\n self.embed_dim,\n use_bias=self.bias,\n dtype=self.dtype,\n kernel_init=jax.nn.initializers.normal(self.config.init_std),\n )\n\n self.q_proj, self.k_proj, self.v_proj = dense(), dense(), dense()\n self.out_proj = dense()\n\n self.dropout_layer = nn.Dropout(rate=self.dropout)\n\n if self.causal:\n self.causal_mask = make_causal_mask(\n jnp.ones((1, self.config.max_position_embeddings), dtype=\"bool\"), dtype=\"bool\"\n )\n\n def _split_heads(self, hidden_states):\n return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads, self.head_dim))\n\n def _merge_heads(self, hidden_states):\n return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))\n\n @nn.compact\n def _concatenate_to_cache(self, key, value, query, attention_mask):\n \"\"\"\n This function takes projected key, value states from a single input token and concatenates the states to cached\n states from previous steps. This function is slighly adapted from the official Flax repository:\n https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252\n \"\"\"\n # detect if we're initializing by absence of existing cache data.\n is_initialized = self.has_variable(\"cache\", \"cached_key\")\n cached_key = self.variable(\"cache\", \"cached_key\", jnp.zeros, key.shape, key.dtype)\n cached_value = self.variable(\"cache\", \"cached_value\", jnp.zeros, value.shape, value.dtype)\n cache_index = self.variable(\"cache\", \"cache_index\", lambda: jnp.array(0, dtype=jnp.int32))\n\n if is_initialized:\n *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape\n # update key, value caches with our new 1d spatial slices\n cur_index = cache_index.value\n indices = (0,) * len(batch_dims) + (cur_index, 0, 0)\n key = lax.dynamic_update_slice(cached_key.value, key, indices)\n value = lax.dynamic_update_slice(cached_value.value, value, indices)\n cached_key.value = key\n cached_value.value = value\n num_updated_cache_vectors = query.shape[1]\n cache_index.value = cache_index.value + num_updated_cache_vectors\n # causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.\n pad_mask = jnp.broadcast_to(\n jnp.arange(max_length) < cur_index + num_updated_cache_vectors,\n tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),\n )\n attention_mask = combine_masks(pad_mask, attention_mask)\n return key, value, attention_mask\n\n def __call__(\n self,\n hidden_states: jnp.ndarray,\n key_value_states: Optional[jnp.ndarray] = None,\n attention_mask: Optional[jnp.ndarray] = None,\n init_cache: bool = False,\n deterministic: bool = True,\n ) -> Tuple[jnp.ndarray]:\n \"\"\"Input shape: Batch x Time x Channel\"\"\"\n\n # if key_value_states are provided this layer is used as a cross-attention layer\n # for the decoder\n is_cross_attention = key_value_states is not None\n batch_size = hidden_states.shape[0]\n\n # get query proj\n query_states = self.q_proj(hidden_states)\n # get key, value proj\n if is_cross_attention:\n # cross_attentions\n key_states = self.k_proj(key_value_states)\n value_states = self.v_proj(key_value_states)\n else:\n # self_attention\n key_states = self.k_proj(hidden_states)\n value_states = self.v_proj(hidden_states)\n\n query_states = self._split_heads(query_states)\n key_states = self._split_heads(key_states)\n value_states = self._split_heads(value_states)\n\n # handle cache prepare causal attention mask\n if self.causal:\n query_length, key_length = query_states.shape[1], key_states.shape[1]\n if self.has_variable(\"cache\", \"cached_key\"):\n mask_shift = self.variables[\"cache\"][\"cache_index\"]\n max_decoder_length = self.variables[\"cache\"][\"cached_key\"].shape[1]\n causal_mask = lax.dynamic_slice(\n self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)\n )\n else:\n causal_mask = self.causal_mask[:, :, :query_length, :key_length]\n causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])\n\n # combine masks if needed\n if attention_mask is not None and self.causal:\n attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)\n attention_mask = combine_masks(attention_mask, causal_mask)\n elif self.causal:\n attention_mask = causal_mask\n elif attention_mask is not None:\n attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))\n\n # During fast autoregressive decoding, we feed one position at a time,\n # and cache the keys and values step by step.\n if self.causal and (self.has_variable(\"cache\", \"cached_key\") or init_cache):\n key_states, value_states, attention_mask = self._concatenate_to_cache(\n key_states, value_states, query_states, attention_mask\n )\n\n # Convert the boolean attention mask to an attention bias.\n if attention_mask is not None:\n # attention mask in the form of attention bias\n attention_bias = lax.select(\n attention_mask > 0,\n jnp.full(attention_mask.shape, 0.0).astype(self.dtype),\n jnp.full(attention_mask.shape, float(\"-inf\")).astype(self.dtype),\n )\n else:\n attention_bias = None\n\n dropout_rng = None\n if not deterministic and self.dropout > 0.0:\n dropout_rng = self.make_rng(\"dropout\")\n\n attn_weights = dot_product_attention_weights(\n query_states,\n key_states,\n bias=attention_bias,\n dropout_rng=dropout_rng,\n dropout_rate=self.dropout,\n broadcast_dropout=True,\n deterministic=deterministic,\n dtype=self.dtype,\n precision=None,\n )\n\n attn_output = jnp.einsum(\"...hqk,...khd->...qhd\", attn_weights, value_states)\n attn_output = self._merge_heads(attn_output)\n attn_output = self.out_proj(attn_output)\n\n return attn_output, attn_weights\n\n\n# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayer with Bart->BlenderbotSmall\nclass FlaxBlenderbotSmallEncoderLayer(nn.Module):\n config: BlenderbotSmallConfig\n dtype: jnp.dtype = jnp.float32\n\n def setup(self) -> None:\n self.embed_dim = self.config.d_model\n self.self_attn = FlaxBlenderbotSmallAttention(\n config=self.config,\n embed_dim=self.embed_dim,\n num_heads=self.config.encoder_attention_heads,\n dropout=self.config.attention_dropout,\n dtype=self.dtype,\n )\n self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)\n self.dropout_layer = nn.Dropout(rate=self.config.dropout)\n self.activation_fn = ACT2FN[self.config.activation_function]\n self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)\n self.fc1 = nn.Dense(\n self.config.encoder_ffn_dim,\n dtype=self.dtype,\n kernel_init=jax.nn.initializers.normal(self.config.init_std),\n )\n self.fc2 = nn.Dense(\n self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)\n )\n self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)\n\n def __call__(\n self,\n hidden_states: jnp.ndarray,\n attention_mask: jnp.ndarray,\n output_attentions: bool = True,\n deterministic: bool = True,\n ) -> Tuple[jnp.ndarray]:\n residual = hidden_states\n hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask)\n\n hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)\n hidden_states = residual + hidden_states\n hidden_states = self.self_attn_layer_norm(hidden_states)\n\n residual = hidden_states\n hidden_states = self.activation_fn(self.fc1(hidden_states))\n hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)\n hidden_states = self.fc2(hidden_states)\n hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)\n hidden_states = residual + hidden_states\n hidden_states = self.final_layer_norm(hidden_states)\n\n outputs = (hidden_states,)\n\n if output_attentions:\n outputs += (attn_weights,)\n\n return outputs\n\n\n# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayerCollection with Bart->BlenderbotSmall\nclass FlaxBlenderbotSmallEncoderLayerCollection(nn.Module):\n config: BlenderbotSmallConfig\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n def setup(self):\n self.layers = [\n FlaxBlenderbotSmallEncoderLayer(self.config, name=str(i), dtype=self.dtype)\n for i in range(self.config.encoder_layers)\n ]\n self.layerdrop = self.config.encoder_layerdrop\n\n def __call__(\n self,\n hidden_states,\n attention_mask,\n deterministic: bool = True,\n output_attentions: bool = False,\n output_hidden_states: bool = False,\n return_dict: bool = True,\n ):\n all_attentions = () if output_attentions else None\n all_hidden_states = () if output_hidden_states else None\n\n for encoder_layer in self.layers:\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = random.uniform(0, 1)\n if not deterministic and (dropout_probability < self.layerdrop): # skip the layer\n layer_outputs = (None, None)\n else:\n layer_outputs = encoder_layer(\n hidden_states,\n attention_mask,\n output_attentions,\n deterministic,\n )\n hidden_states = layer_outputs[0]\n if output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n\n outputs = (hidden_states, all_hidden_states, all_attentions)\n\n if not return_dict:\n return tuple(v for v in outputs if v is not None)\n\n return FlaxBaseModelOutput(\n last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions\n )\n\n\n# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayer with Bart->BlenderbotSmall\nclass FlaxBlenderbotSmallDecoderLayer(nn.Module):\n config: BlenderbotSmallConfig\n dtype: jnp.dtype = jnp.float32\n\n def setup(self) -> None:\n self.embed_dim = self.config.d_model\n self.self_attn = FlaxBlenderbotSmallAttention(\n config=self.config,\n embed_dim=self.embed_dim,\n num_heads=self.config.decoder_attention_heads,\n dropout=self.config.attention_dropout,\n causal=True,\n dtype=self.dtype,\n )\n self.dropout_layer = nn.Dropout(rate=self.config.dropout)\n self.activation_fn = ACT2FN[self.config.activation_function]\n self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)\n\n self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)\n self.encoder_attn = FlaxBlenderbotSmallAttention(\n config=self.config,\n embed_dim=self.embed_dim,\n num_heads=self.config.decoder_attention_heads,\n dropout=self.config.attention_dropout,\n dtype=self.dtype,\n )\n self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)\n self.fc1 = nn.Dense(\n self.config.encoder_ffn_dim,\n dtype=self.dtype,\n kernel_init=jax.nn.initializers.normal(self.config.init_std),\n )\n self.fc2 = nn.Dense(\n self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)\n )\n self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)\n\n def __call__(\n self,\n hidden_states: jnp.ndarray,\n attention_mask: jnp.ndarray,\n encoder_hidden_states: Optional[jnp.ndarray] = None,\n encoder_attention_mask: Optional[jnp.ndarray] = None,\n init_cache: bool = False,\n output_attentions: bool = True,\n deterministic: bool = True,\n ) -> Tuple[jnp.ndarray]:\n residual = hidden_states\n\n # Self Attention\n hidden_states, self_attn_weights = self.self_attn(\n hidden_states=hidden_states, attention_mask=attention_mask, init_cache=init_cache\n )\n hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)\n hidden_states = residual + hidden_states\n hidden_states = self.self_attn_layer_norm(hidden_states)\n\n # Cross-Attention Block\n cross_attn_weights = None\n if encoder_hidden_states is not None:\n residual = hidden_states\n\n hidden_states, cross_attn_weights = self.encoder_attn(\n hidden_states=hidden_states,\n key_value_states=encoder_hidden_states,\n attention_mask=encoder_attention_mask,\n )\n hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)\n hidden_states = residual + hidden_states\n hidden_states = self.encoder_attn_layer_norm(hidden_states)\n\n # Fully Connected\n residual = hidden_states\n hidden_states = self.activation_fn(self.fc1(hidden_states))\n hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)\n hidden_states = self.fc2(hidden_states)\n hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)\n hidden_states = residual + hidden_states\n hidden_states = self.final_layer_norm(hidden_states)\n\n outputs = (hidden_states,)\n\n if output_attentions:\n outputs += (self_attn_weights, cross_attn_weights)\n\n return outputs\n\n\n# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayerCollection with Bart->BlenderbotSmall\nclass FlaxBlenderbotSmallDecoderLayerCollection(nn.Module):\n config: BlenderbotSmallConfig\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n def setup(self):\n self.layers = [\n FlaxBlenderbotSmallDecoderLayer(self.config, name=str(i), dtype=self.dtype)\n for i in range(self.config.decoder_layers)\n ]\n self.layerdrop = self.config.decoder_layerdrop\n\n def __call__(\n self,\n hidden_states,\n attention_mask,\n encoder_hidden_states: Optional[jnp.ndarray] = None,\n encoder_attention_mask: Optional[jnp.ndarray] = None,\n deterministic: bool = True,\n init_cache: bool = False,\n output_attentions: bool = False,\n output_hidden_states: bool = False,\n return_dict: bool = True,\n ):\n # decoder layers\n all_hidden_states = () if output_hidden_states else None\n all_self_attns = () if output_attentions else None\n all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None\n\n for decoder_layer in self.layers:\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = random.uniform(0, 1)\n if not deterministic and (dropout_probability < self.layerdrop):\n layer_outputs = (None, None, None)\n else:\n layer_outputs = decoder_layer(\n hidden_states,\n attention_mask=attention_mask,\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=encoder_attention_mask,\n init_cache=init_cache,\n output_attentions=output_attentions,\n deterministic=deterministic,\n )\n\n hidden_states = layer_outputs[0]\n if output_attentions:\n all_self_attns += (layer_outputs[1],)\n\n if encoder_hidden_states is not None:\n all_cross_attentions += (layer_outputs[2],)\n\n # add hidden states from the last decoder layer\n if output_hidden_states:\n all_hidden_states += (hidden_states,)\n\n outputs = [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions]\n\n if not return_dict:\n return tuple(v for v in outputs if v is not None)\n\n return FlaxBaseModelOutputWithPastAndCrossAttentions(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n attentions=all_self_attns,\n cross_attentions=all_cross_attentions,\n )\n\n\nclass FlaxBlenderbotSmallEncoder(nn.Module):\n config: BlenderbotSmallConfig\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n embed_tokens: Optional[nn.Embed] = None\n\n def setup(self):\n self.dropout_layer = nn.Dropout(rate=self.config.dropout)\n\n embed_dim = self.config.d_model\n self.padding_idx = self.config.pad_token_id\n self.max_source_positions = self.config.max_position_embeddings\n self.embed_scale = math.sqrt(embed_dim) if self.config.scale_embedding else 1.0\n\n if self.embed_tokens is None:\n self.embed_tokens = nn.Embed(\n self.config.vocab_size,\n embed_dim,\n embedding_init=jax.nn.initializers.normal(self.config.init_std),\n )\n\n self.embed_positions = nn.Embed(\n self.config.max_position_embeddings,\n embed_dim,\n embedding_init=jax.nn.initializers.normal(self.config.init_std),\n )\n self.layers = FlaxBlenderbotSmallEncoderLayerCollection(self.config, self.dtype)\n self.layernorm_embedding = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)\n\n def __call__(\n self,\n input_ids,\n attention_mask,\n position_ids,\n output_attentions: bool = False,\n output_hidden_states: bool = False,\n return_dict: bool = True,\n deterministic: bool = True,\n ):\n input_shape = input_ids.shape\n input_ids = input_ids.reshape(-1, input_shape[-1])\n\n inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale\n\n embed_pos = self.embed_positions(position_ids)\n\n hidden_states = inputs_embeds + embed_pos\n hidden_states = self.layernorm_embedding(hidden_states)\n hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)\n\n outputs = self.layers(\n hidden_states,\n attention_mask,\n deterministic=deterministic,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return outputs\n\n return FlaxBaseModelOutput(\n last_hidden_state=outputs.last_hidden_state,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n\nclass FlaxBlenderbotSmallDecoder(nn.Module):\n config: BlenderbotSmallConfig\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n embed_tokens: Optional[nn.Embed] = None\n\n def setup(self):\n self.dropout_layer = nn.Dropout(rate=self.config.dropout)\n\n embed_dim = self.config.d_model\n self.padding_idx = self.config.pad_token_id\n self.max_target_positions = self.config.max_position_embeddings\n self.embed_scale = math.sqrt(self.config.d_model) if self.config.scale_embedding else 1.0\n\n if self.embed_tokens is None:\n self.embed_tokens = nn.Embed(\n self.config.vocab_size,\n embed_dim,\n embedding_init=jax.nn.initializers.normal(self.config.init_std),\n )\n\n self.embed_positions = nn.Embed(\n self.config.max_position_embeddings,\n embed_dim,\n embedding_init=jax.nn.initializers.normal(self.config.init_std),\n )\n\n self.layers = FlaxBlenderbotSmallDecoderLayerCollection(self.config, self.dtype)\n self.layernorm_embedding = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)\n\n def __call__(\n self,\n input_ids,\n attention_mask,\n position_ids,\n encoder_hidden_states: Optional[jnp.ndarray] = None,\n encoder_attention_mask: Optional[jnp.ndarray] = None,\n init_cache: bool = False,\n output_attentions: bool = False,\n output_hidden_states: bool = False,\n return_dict: bool = True,\n deterministic: bool = True,\n ):\n input_shape = input_ids.shape\n input_ids = input_ids.reshape(-1, input_shape[-1])\n\n inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale\n\n # embed positions\n positions = self.embed_positions(position_ids)\n\n # BlenderbotSmall applies layer norm on inputs_embeds in decoder\n inputs_embeds = self.layernorm_embedding(inputs_embeds)\n hidden_states = inputs_embeds + positions\n\n hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)\n\n outputs = self.layers(\n hidden_states,\n attention_mask,\n encoder_hidden_states,\n encoder_attention_mask,\n deterministic=deterministic,\n init_cache=init_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if not return_dict:\n return outputs\n\n return FlaxBaseModelOutputWithPastAndCrossAttentions(\n last_hidden_state=outputs.last_hidden_state,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n cross_attentions=outputs.cross_attentions,\n )\n\n\n# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartModule with Bart->BlenderbotSmall\nclass FlaxBlenderbotSmallModule(nn.Module):\n config: BlenderbotSmallConfig\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n\n def setup(self):\n self.shared = nn.Embed(\n self.config.vocab_size,\n self.config.d_model,\n embedding_init=jax.nn.initializers.normal(self.config.init_std),\n )\n\n self.encoder = FlaxBlenderbotSmallEncoder(self.config, dtype=self.dtype, embed_tokens=self.shared)\n self.decoder = FlaxBlenderbotSmallDecoder(self.config, dtype=self.dtype, embed_tokens=self.shared)\n\n def _get_encoder_module(self):\n return self.encoder\n\n def _get_decoder_module(self):\n return self.decoder\n\n def __call__(\n self,\n input_ids,\n attention_mask,\n decoder_input_ids,\n decoder_attention_mask,\n position_ids,\n decoder_position_ids,\n output_attentions: bool = False,\n output_hidden_states: bool = False,\n return_dict: bool = True,\n deterministic: bool = True,\n ):\n encoder_outputs = self.encoder(\n input_ids=input_ids,\n attention_mask=attention_mask,\n position_ids=position_ids,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n deterministic=deterministic,\n )\n\n decoder_outputs = self.decoder(\n input_ids=decoder_input_ids,\n attention_mask=decoder_attention_mask,\n position_ids=decoder_position_ids,\n encoder_hidden_states=encoder_outputs[0],\n encoder_attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n deterministic=deterministic,\n )\n\n if not return_dict:\n return decoder_outputs + encoder_outputs\n\n return FlaxSeq2SeqModelOutput(\n last_hidden_state=decoder_outputs.last_hidden_state,\n decoder_hidden_states=decoder_outputs.hidden_states,\n decoder_attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n encoder_last_hidden_state=encoder_outputs.last_hidden_state,\n encoder_hidden_states=encoder_outputs.hidden_states,\n encoder_attentions=encoder_outputs.attentions,\n )\n\n\nclass FlaxBlenderbotSmallPreTrainedModel(FlaxPreTrainedModel):\n config_class = BlenderbotSmallConfig\n base_model_prefix: str = \"model\"\n module_class: nn.Module = None\n\n def __init__(\n self,\n config: BlenderbotSmallConfig,\n input_shape: Tuple[int] = (1, 1),\n seed: int = 0,\n dtype: jnp.dtype = jnp.float32,\n **kwargs\n ):\n module = self.module_class(config=config, dtype=dtype, **kwargs)\n super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype)\n\n def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple) -> FrozenDict:\n # init input tensors\n input_ids = jnp.zeros(input_shape, dtype=\"i4\")\n # make sure initialization pass will work for FlaxBlenderbotSmallForSequenceClassificationModule\n input_ids = jax.ops.index_update(input_ids, (..., -1), self.config.eos_token_id)\n attention_mask = jnp.ones_like(input_ids)\n decoder_input_ids = input_ids\n decoder_attention_mask = jnp.ones_like(input_ids)\n\n batch_size, sequence_length = input_ids.shape\n position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))\n decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))\n\n params_rng, dropout_rng = jax.random.split(rng)\n rngs = {\"params\": params_rng, \"dropout\": dropout_rng}\n\n return self.module.init(\n rngs,\n input_ids,\n attention_mask,\n decoder_input_ids,\n decoder_attention_mask,\n position_ids,\n decoder_position_ids,\n )[\"params\"]\n\n def init_cache(self, batch_size, max_length, encoder_outputs):\n r\"\"\"\n Args:\n batch_size (`int`):\n batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.\n max_length (`int`):\n maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized\n cache.\n encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):\n `encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:\n `attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)\n is a sequence of hidden-states at the output of the last layer of the encoder. Used in the\n cross-attention of the decoder.\n \"\"\"\n # init input variables to retrieve cache\n decoder_input_ids = jnp.ones((batch_size, max_length), dtype=\"i4\")\n decoder_attention_mask = jnp.ones_like(decoder_input_ids)\n decoder_position_ids = jnp.broadcast_to(\n jnp.arange(jnp.atleast_2d(decoder_input_ids).shape[-1]), decoder_input_ids.shape\n )\n\n def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):\n decoder_module = module._get_decoder_module()\n return decoder_module(\n decoder_input_ids,\n decoder_attention_mask,\n decoder_position_ids,\n **kwargs,\n )\n\n init_variables = self.module.init(\n jax.random.PRNGKey(0),\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n decoder_position_ids=decoder_position_ids,\n encoder_hidden_states=encoder_outputs[0],\n init_cache=True,\n method=_decoder_forward, # we only need to call the decoder to init the cache\n )\n return unfreeze(init_variables[\"cache\"])\n\n @add_start_docstrings(BLENDERBOT_SMALL_ENCODE_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=BlenderbotSmallConfig)\n def encode(\n self,\n input_ids: jnp.ndarray,\n attention_mask: Optional[jnp.ndarray] = None,\n position_ids: Optional[jnp.ndarray] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n train: bool = False,\n params: dict = None,\n dropout_rng: PRNGKey = None,\n ):\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import BlenderbotSmallTokenizer, FlaxBlenderbotSmallForConditionalGeneration\n\n >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained(\"facebook/blenderbot_small-90M\")\n >>> tokenizer = BlenderbotSmallTokenizer.from_pretrained(\"facebook/blenderbot_small-90M\")\n\n >>> text = \"My friends are cool but they eat too many carbs.\"\n >>> inputs = tokenizer(text, max_length=1024, return_tensors=\"np\")\n >>> encoder_outputs = model.encode(**inputs)\n ```\"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.return_dict\n\n if attention_mask is None:\n attention_mask = jnp.ones_like(input_ids)\n if position_ids is None:\n batch_size, sequence_length = input_ids.shape\n position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))\n\n # Handle any PRNG if needed\n rngs = {}\n if dropout_rng is not None:\n rngs[\"dropout\"] = dropout_rng\n\n def _encoder_forward(module, input_ids, attention_mask, position_ids, **kwargs):\n encode_module = module._get_encoder_module()\n return encode_module(input_ids, attention_mask, position_ids, **kwargs)\n\n return self.module.apply(\n {\"params\": params or self.params},\n input_ids=jnp.array(input_ids, dtype=\"i4\"),\n attention_mask=jnp.array(attention_mask, dtype=\"i4\"),\n position_ids=jnp.array(position_ids, dtype=\"i4\"),\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n deterministic=not train,\n rngs=rngs,\n method=_encoder_forward,\n )\n\n @add_start_docstrings(BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING)\n @replace_return_docstrings(\n output_type=FlaxBaseModelOutputWithPastAndCrossAttentions, config_class=BlenderbotSmallConfig\n )\n def decode(\n self,\n decoder_input_ids,\n encoder_outputs,\n encoder_attention_mask: Optional[jnp.ndarray] = None,\n decoder_attention_mask: Optional[jnp.ndarray] = None,\n decoder_position_ids: Optional[jnp.ndarray] = None,\n past_key_values: dict = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n train: bool = False,\n params: dict = None,\n dropout_rng: PRNGKey = None,\n ):\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import BlenderbotSmallTokenizer, FlaxBlenderbotSmallForConditionalGeneration\n\n >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained(\"facebook/blenderbot_small-90M\")\n >>> tokenizer = BlenderbotSmallTokenizer.from_pretrained(\"facebook/blenderbot_small-90M\")\n\n >>> text = \"My friends are cool but they eat too many carbs.\"\n >>> inputs = tokenizer(text, max_length=1024, return_tensors=\"np\")\n >>> encoder_outputs = model.encode(**inputs)\n\n >>> decoder_start_token_id = model.config.decoder_start_token_id\n >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype=\"i4\") * decoder_start_token_id\n\n >>> outputs = model.decode(decoder_input_ids, encoder_outputs)\n >>> last_decoder_hidden_states = outputs.last_hidden_state\n ```\"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.return_dict\n\n encoder_hidden_states = encoder_outputs[0]\n if encoder_attention_mask is None:\n batch_size, sequence_length = encoder_hidden_states.shape[:2]\n encoder_attention_mask = jnp.ones((batch_size, sequence_length))\n\n batch_size, sequence_length = decoder_input_ids.shape\n if decoder_attention_mask is None:\n decoder_attention_mask = jnp.ones((batch_size, sequence_length))\n\n if decoder_position_ids is None:\n if past_key_values is not None:\n raise ValueError(\"Make sure to provide `decoder_position_ids` when passing `past_key_values`.\")\n\n decoder_position_ids = jnp.broadcast_to(\n jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)\n )\n\n # Handle any PRNG if needed\n rngs = {}\n if dropout_rng is not None:\n rngs[\"dropout\"] = dropout_rng\n\n inputs = {\"params\": params or self.params}\n\n # if past_key_values are passed then cache is already initialized a private flag init_cache has to be\n # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that\n # it can be changed by FlaxBlenderbotSmallAttention module\n if past_key_values:\n inputs[\"cache\"] = past_key_values\n mutable = [\"cache\"]\n else:\n mutable = False\n\n def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):\n decoder_module = module._get_decoder_module()\n return decoder_module(\n decoder_input_ids,\n decoder_attention_mask,\n decoder_position_ids,\n **kwargs,\n )\n\n outputs = self.module.apply(\n inputs,\n decoder_input_ids=jnp.array(decoder_input_ids, dtype=\"i4\"),\n decoder_attention_mask=jnp.array(decoder_attention_mask, dtype=\"i4\"),\n decoder_position_ids=jnp.array(decoder_position_ids, dtype=\"i4\"),\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=jnp.array(encoder_attention_mask, dtype=\"i4\"),\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n deterministic=not train,\n rngs=rngs,\n mutable=mutable,\n method=_decoder_forward,\n )\n\n # add updated cache to model output\n if past_key_values is not None and return_dict:\n outputs, past = outputs\n outputs[\"past_key_values\"] = unfreeze(past[\"cache\"])\n return outputs\n elif past_key_values is not None and not return_dict:\n outputs, past = outputs\n outputs = outputs[:1] + (unfreeze(past[\"cache\"]),) + outputs[1:]\n\n return outputs\n\n def __call__(\n self,\n input_ids: jnp.ndarray,\n attention_mask: Optional[jnp.ndarray] = None,\n decoder_input_ids: Optional[jnp.ndarray] = None,\n decoder_attention_mask: Optional[jnp.ndarray] = None,\n position_ids: Optional[jnp.ndarray] = None,\n decoder_position_ids: Optional[jnp.ndarray] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n train: bool = False,\n params: dict = None,\n dropout_rng: PRNGKey = None,\n ):\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.return_dict\n\n # prepare encoder inputs\n if attention_mask is None:\n attention_mask = jnp.ones_like(input_ids)\n if position_ids is None:\n batch_size, sequence_length = input_ids.shape\n position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))\n\n # prepare decoder inputs\n if decoder_input_ids is None:\n decoder_input_ids = shift_tokens_right(\n input_ids, self.config.pad_token_id, decoder_start_token_id=self.config.decoder_start_token_id\n )\n if decoder_attention_mask is None:\n decoder_attention_mask = jnp.ones_like(decoder_input_ids)\n if decoder_position_ids is None:\n batch_size, sequence_length = decoder_input_ids.shape\n decoder_position_ids = jnp.broadcast_to(\n jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)\n )\n\n # Handle any PRNG if needed\n rngs = {\"dropout\": dropout_rng} if dropout_rng is not None else {}\n\n return self.module.apply(\n {\"params\": params or self.params},\n input_ids=jnp.array(input_ids, dtype=\"i4\"),\n attention_mask=jnp.array(attention_mask, dtype=\"i4\"),\n position_ids=jnp.array(position_ids, dtype=\"i4\"),\n decoder_input_ids=jnp.array(decoder_input_ids, dtype=\"i4\"),\n decoder_attention_mask=jnp.array(decoder_attention_mask, dtype=\"i4\"),\n decoder_position_ids=jnp.array(decoder_position_ids, dtype=\"i4\"),\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n deterministic=not train,\n rngs=rngs,\n )\n\n\n@add_start_docstrings(\n \"The bare BlenderbotSmall Model transformer outputting raw hidden-states without any specific head on top.\",\n BLENDERBOT_SMALL_START_DOCSTRING,\n)\nclass FlaxBlenderbotSmallModel(FlaxBlenderbotSmallPreTrainedModel):\n config: BlenderbotSmallConfig\n dtype: jnp.dtype = jnp.float32 # the dtype of the computation\n module_class = FlaxBlenderbotSmallModule\n\n\nappend_call_sample_docstring(\n FlaxBlenderbotSmallModel, _TOKENIZER_FOR_DOC, _CHECKPOINT_FOR_DOC, FlaxSeq2SeqModelOutput, _CONFIG_FOR_DOC\n)\n\n\n# Copied from transformers.models.bart.modeling_flax_bart.FlaxBartForConditionalGenerationModule with Bart->BlenderbotSmall\nclass FlaxBlenderbotSmallForConditionalGenerationModule(nn.Module):\n config: BlenderbotSmallConfig\n dtype: jnp.dtype = jnp.float32\n bias_init: Callable[..., jnp.ndarray] = jax.nn.initializers.zeros\n\n def setup(self):\n self.model = FlaxBlenderbotSmallModule(config=self.config, dtype=self.dtype)\n self.lm_head = nn.Dense(\n self.model.shared.num_embeddings,\n use_bias=False,\n dtype=self.dtype,\n kernel_init=jax.nn.initializers.normal(self.config.init_std),\n )\n self.final_logits_bias = self.param(\"final_logits_bias\", self.bias_init, (1, self.model.shared.num_embeddings))\n\n def _get_encoder_module(self):\n return self.model.encoder\n\n def _get_decoder_module(self):\n return self.model.decoder\n\n def __call__(\n self,\n input_ids,\n attention_mask,\n decoder_input_ids,\n decoder_attention_mask,\n position_ids,\n decoder_position_ids,\n output_attentions: bool = False,\n output_hidden_states: bool = False,\n return_dict: bool = True,\n deterministic: bool = True,\n ):\n outputs = self.model(\n input_ids=input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n position_ids=position_ids,\n decoder_position_ids=decoder_position_ids,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n deterministic=deterministic,\n )\n\n hidden_states = outputs[0]\n\n if self.config.tie_word_embeddings:\n shared_embedding = self.model.variables[\"params\"][\"shared\"][\"embedding\"]\n lm_logits = self.lm_head.apply({\"params\": {\"kernel\": shared_embedding.T}}, hidden_states)\n else:\n lm_logits = self.lm_head(hidden_states)\n\n lm_logits += self.final_logits_bias.astype(self.dtype)\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return output\n\n return FlaxSeq2SeqLMOutput(\n logits=lm_logits,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )\n\n\n@add_start_docstrings(\n \"The BLENDERBOT_SMALL Model with a language modeling head. Can be used for summarization.\",\n BLENDERBOT_SMALL_START_DOCSTRING,\n)\nclass FlaxBlenderbotSmallForConditionalGeneration(FlaxBlenderbotSmallPreTrainedModel):\n module_class = FlaxBlenderbotSmallForConditionalGenerationModule\n dtype: jnp.dtype = jnp.float32\n\n @add_start_docstrings(BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING)\n @replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=BlenderbotSmallConfig)\n def decode(\n self,\n decoder_input_ids,\n encoder_outputs,\n encoder_attention_mask: Optional[jnp.ndarray] = None,\n decoder_attention_mask: Optional[jnp.ndarray] = None,\n decoder_position_ids: Optional[jnp.ndarray] = None,\n past_key_values: dict = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n deterministic: bool = True,\n params: dict = None,\n dropout_rng: PRNGKey = None,\n ):\n r\"\"\"\n Returns:\n\n Example:\n\n ```python\n >>> from transformers import BlenderbotSmallTokenizer, FlaxBlenderbotSmallForConditionalGeneration\n\n >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained(\"facebook/blenderbot_small-90M\")\n >>> tokenizer = BlenderbotSmallTokenizer.from_pretrained(\"facebook/blenderbot_small-90M\")\n\n >>> text = \"My friends are cool but they eat too many carbs.\"\n >>> inputs = tokenizer(text, max_length=1024, return_tensors=\"np\")\n >>> encoder_outputs = model.encode(**inputs)\n\n >>> decoder_start_token_id = model.config.decoder_start_token_id\n >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype=\"i4\") * decoder_start_token_id\n\n >>> outputs = model.decode(decoder_input_ids, encoder_outputs)\n >>> logits = outputs.logits\n ```\"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.return_dict\n\n encoder_hidden_states = encoder_outputs[0]\n if encoder_attention_mask is None:\n batch_size, sequence_length = encoder_hidden_states.shape[:2]\n encoder_attention_mask = jnp.ones((batch_size, sequence_length))\n\n batch_size, sequence_length = decoder_input_ids.shape\n if decoder_attention_mask is None:\n decoder_attention_mask = jnp.ones((batch_size, sequence_length))\n\n if decoder_position_ids is None:\n if past_key_values is not None:\n raise ValueError(\"Make sure to provide `decoder_position_ids` when passing `past_key_values`.\")\n\n decoder_position_ids = jnp.broadcast_to(\n jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)\n )\n\n # Handle any PRNG if needed\n rngs = {}\n if dropout_rng is not None:\n rngs[\"dropout\"] = dropout_rng\n\n inputs = {\"params\": params or self.params}\n\n # if past_key_values are passed then cache is already initialized a private flag init_cache has to be\n # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that\n # it can be changed by FlaxBlenderbotSmallAttention module\n if past_key_values:\n inputs[\"cache\"] = past_key_values\n mutable = [\"cache\"]\n else:\n mutable = False\n\n def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):\n decoder_module = module._get_decoder_module()\n outputs = decoder_module(\n decoder_input_ids,\n decoder_attention_mask,\n decoder_position_ids,\n **kwargs,\n )\n hidden_states = outputs[0]\n\n if self.config.tie_word_embeddings:\n shared_embedding = module.model.variables[\"params\"][\"shared\"][\"embedding\"]\n lm_logits = module.lm_head.apply({\"params\": {\"kernel\": shared_embedding.T}}, hidden_states)\n else:\n lm_logits = module.lm_head(hidden_states)\n\n lm_logits += module.final_logits_bias.astype(self.dtype)\n return lm_logits, outputs\n\n outputs = self.module.apply(\n inputs,\n decoder_input_ids=jnp.array(decoder_input_ids, dtype=\"i4\"),\n decoder_attention_mask=jnp.array(decoder_attention_mask, dtype=\"i4\"),\n decoder_position_ids=jnp.array(decoder_position_ids, dtype=\"i4\"),\n encoder_hidden_states=encoder_hidden_states,\n encoder_attention_mask=jnp.array(encoder_attention_mask, dtype=\"i4\"),\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n deterministic=deterministic,\n rngs=rngs,\n mutable=mutable,\n method=_decoder_forward,\n )\n\n if past_key_values is None:\n lm_logits, decoder_outputs = outputs\n else:\n (lm_logits, decoder_outputs), past = outputs\n\n if return_dict:\n outputs = FlaxCausalLMOutputWithCrossAttentions(\n logits=lm_logits,\n hidden_states=decoder_outputs.hidden_states,\n attentions=decoder_outputs.attentions,\n cross_attentions=decoder_outputs.cross_attentions,\n )\n else:\n outputs = (lm_logits,) + decoder_outputs[1:]\n\n # add updated cache to model output\n if past_key_values is not None and return_dict:\n outputs[\"past_key_values\"] = unfreeze(past[\"cache\"])\n return outputs\n elif past_key_values is not None and not return_dict:\n outputs = outputs[:1] + (unfreeze(past[\"cache\"]),) + outputs[1:]\n\n return outputs\n\n def prepare_inputs_for_generation(\n self,\n decoder_input_ids,\n max_length,\n attention_mask: Optional[jnp.DeviceArray] = None,\n decoder_attention_mask: Optional[jnp.DeviceArray] = None,\n encoder_outputs=None,\n **kwargs\n ):\n # initializing the cache\n batch_size, seq_length = decoder_input_ids.shape\n\n past_key_values = self.init_cache(batch_size, max_length, encoder_outputs)\n # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.\n # But since the decoder uses a causal mask, those positions are masked anyways.\n # Thus we can create a single static attention_mask here, which is more efficient for compilation\n extended_attention_mask = jnp.ones((batch_size, max_length), dtype=\"i4\")\n if decoder_attention_mask is not None:\n position_ids = decoder_attention_mask.cumsum(axis=-1) - 1\n extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, decoder_attention_mask, (0, 0))\n else:\n position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype=\"i4\")[None, :], (batch_size, seq_length))\n\n return {\n \"past_key_values\": past_key_values,\n \"encoder_outputs\": encoder_outputs,\n \"encoder_attention_mask\": attention_mask,\n \"decoder_attention_mask\": extended_attention_mask,\n \"decoder_position_ids\": position_ids,\n }\n\n def update_inputs_for_generation(self, model_outputs, model_kwargs):\n model_kwargs[\"past_key_values\"] = model_outputs.past_key_values\n model_kwargs[\"decoder_position_ids\"] = model_kwargs[\"decoder_position_ids\"][:, -1:] + 1\n return model_kwargs\n\n\nFLAX_BLENDERBOT_SMALL_CONDITIONAL_GENERATION_DOCSTRING = \"\"\"\n Returns:\n\n Summarization example::\n\n >>> from transformers import BlenderbotSmallTokenizer, FlaxBlenderbotSmallForConditionalGeneration\n\n >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained('facebook/blenderbot_small-90M') >>>\n tokenizer = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot_small-90M')\n\n >>> ARTICLE_TO_SUMMARIZE = \"My friends are cool but they eat too many carbs.\" >>> inputs =\n tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors='np')\n\n >>> # Generate Summary >>> summary_ids = model.generate(inputs['input_ids']).sequences >>>\n print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False))\n\n Mask filling example::\n\n >>> from transformers import BlenderbotSmallTokenizer, FlaxBlenderbotSmallForConditionalGeneration >>>\n tokenizer = BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot_small-90M') >>> TXT = \"My friends are\n <mask> but they eat too many carbs.\"\n\n >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained('facebook/blenderbot_small-90M') >>>\n input_ids = tokenizer([TXT], return_tensors='np')['input_ids'] >>> logits = model(input_ids).logits\n\n >>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item() >>> probs =\n jax.nn.softmax(logits[0, masked_index], axis=0) >>> values, predictions = jax.lax.top_k(probs)\n\n >>> tokenizer.decode(predictions).split()\n\"\"\"\n\noverwrite_call_docstring(\n FlaxBlenderbotSmallForConditionalGeneration,\n BLENDERBOT_SMALL_INPUTS_DOCSTRING + FLAX_BLENDERBOT_SMALL_CONDITIONAL_GENERATION_DOCSTRING,\n)\nappend_replace_return_docstrings(\n FlaxBlenderbotSmallForConditionalGeneration, output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC\n)\n", "# coding=utf-8\n# Copyright 2021 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\"\"\"\n Sequence feature extraction class for common feature extractors to preprocess sequences.\n\"\"\"\nfrom typing import Dict, List, Optional, Union\n\nimport numpy as np\n\nfrom .feature_extraction_utils import BatchFeature, FeatureExtractionMixin\nfrom .file_utils import (\n PaddingStrategy,\n TensorType,\n _is_tensorflow,\n _is_torch,\n is_tf_available,\n is_torch_available,\n to_numpy,\n)\nfrom .utils import logging\n\n\nlogger = logging.get_logger(__name__)\n\n\nclass SequenceFeatureExtractor(FeatureExtractionMixin):\n \"\"\"\n This is a general feature extraction class for speech recognition.\n\n Args:\n feature_size (`int`):\n The feature dimension of the extracted features.\n sampling_rate (`int`):\n The sampling rate at which the audio files should be digitalized expressed in Hertz per second (Hz).\n padding_value (`float`):\n The value that is used to fill the padding values / vectors.\n \"\"\"\n\n def __init__(self, feature_size: int, sampling_rate: int, padding_value: float, **kwargs):\n self.feature_size = feature_size\n self.sampling_rate = sampling_rate\n self.padding_value = padding_value\n\n self.padding_side = kwargs.pop(\"padding_side\", \"right\")\n self.return_attention_mask = kwargs.pop(\"return_attention_mask\", True)\n\n super().__init__(**kwargs)\n\n def pad(\n self,\n processed_features: Union[\n BatchFeature,\n List[BatchFeature],\n Dict[str, BatchFeature],\n Dict[str, List[BatchFeature]],\n List[Dict[str, BatchFeature]],\n ],\n padding: Union[bool, str, PaddingStrategy] = True,\n max_length: Optional[int] = None,\n truncation: bool = False,\n pad_to_multiple_of: Optional[int] = None,\n return_attention_mask: Optional[bool] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n ) -> BatchFeature:\n \"\"\"\n Pad input values / input vectors or a batch of input values / input vectors up to predefined length or to the\n max sequence length in the batch.\n\n Padding side (left/right) padding values are defined at the feature extractor level (with `self.padding_side`,\n `self.padding_value`)\n\n <Tip>\n\n If the `processed_features` passed are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the\n result will use the same type unless you provide a different tensor type with `return_tensors`. In the case of\n PyTorch tensors, you will lose the specific device of your tensors however.\n\n </Tip>\n\n Args:\n processed_features ([`BatchFeature`], list of [`BatchFeature`], `Dict[str, List[float]]`, `Dict[str, List[List[float]]` or `List[Dict[str, List[float]]]`):\n Processed inputs. Can represent one input ([`BatchFeature`] or `Dict[str, List[float]]`) or a batch of\n input values / vectors (list of [`BatchFeature`], *Dict[str, List[List[float]]]* or *List[Dict[str,\n List[float]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader\n collate function.\n\n Instead of `List[float]` you can have tensors (numpy arrays, PyTorch tensors or TensorFlow tensors),\n see the note above for the return type.\n padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `True`):\n Select a strategy to pad the returned sequences (according to the model's padding side and padding\n index) among:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single\n sequence if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n max_length (`int`, *optional*):\n Maximum length of the returned list and optionally padding length (see above).\n truncation (`bool`):\n Activates truncation to cut input sequences longer than `max_length` to `max_length`.\n pad_to_multiple_of (`int`, *optional*):\n If set will pad the sequence to a multiple of the provided value.\n\n This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability\n >= 7.5 (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.\n return_attention_mask (`bool`, *optional*):\n Whether to return the attention mask. If left to the default, will return the attention mask according\n to the specific feature_extractor's default.\n\n [What are attention masks?](../glossary#attention-mask)\n return_tensors (`str` or [`~file_utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n \"\"\"\n # If we have a list of dicts, let's convert it in a dict of lists\n # We do this to allow using this method as a collate_fn function in PyTorch Dataloader\n if isinstance(processed_features, (list, tuple)) and isinstance(processed_features[0], (dict, BatchFeature)):\n processed_features = {\n key: [example[key] for example in processed_features] for key in processed_features[0].keys()\n }\n\n # The model's main input name, usually `input_values`, has be passed for padding\n if self.model_input_names[0] not in processed_features:\n raise ValueError(\n \"You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature` to this method \"\n f\"that includes {self.model_input_names[0]}, but you provided {list(processed_features.keys())}\"\n )\n\n required_input = processed_features[self.model_input_names[0]]\n return_attention_mask = (\n return_attention_mask if return_attention_mask is not None else self.return_attention_mask\n )\n\n if not required_input:\n if return_attention_mask:\n processed_features[\"attention_mask\"] = []\n return processed_features\n\n # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays\n # and rebuild them afterwards if no return_tensors is specified\n # Note that we lose the specific device the tensor may be on for PyTorch\n\n first_element = required_input[0]\n if isinstance(first_element, (list, tuple)):\n # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.\n index = 0\n while len(required_input[index]) == 0:\n index += 1\n if index < len(required_input):\n first_element = required_input[index][0]\n\n if return_tensors is None:\n if is_tf_available() and _is_tensorflow(first_element):\n return_tensors = \"tf\"\n elif is_torch_available() and _is_torch(first_element):\n return_tensors = \"pt\"\n elif isinstance(first_element, (int, float, list, tuple, np.ndarray)):\n return_tensors = \"np\"\n else:\n raise ValueError(\n f\"type of {first_element} unknown: {type(first_element)}. \"\n f\"Should be one of a python, numpy, pytorch or tensorflow object.\"\n )\n\n for key, value in processed_features.items():\n if isinstance(value[0], (int, float)):\n processed_features[key] = to_numpy(value)\n else:\n processed_features[key] = [to_numpy(v) for v in value]\n\n # Convert padding_strategy in PaddingStrategy\n padding_strategy = self._get_padding_strategies(padding=padding, max_length=max_length)\n\n required_input = processed_features[self.model_input_names[0]]\n\n batch_size = len(required_input)\n if not all(len(v) == batch_size for v in processed_features.values()):\n raise ValueError(\"Some items in the output dictionary have a different batch size than others.\")\n\n truncated_inputs = []\n for i in range(batch_size):\n inputs = dict((k, v[i]) for k, v in processed_features.items())\n # truncation\n inputs_slice = self._truncate(\n inputs,\n max_length=max_length,\n pad_to_multiple_of=pad_to_multiple_of,\n truncation=truncation,\n )\n truncated_inputs.append(inputs_slice)\n\n if padding_strategy == PaddingStrategy.LONGEST:\n # make sure that `max_length` cannot be longer than the longest truncated length\n max_length = max(len(input_slice[self.model_input_names[0]]) for input_slice in truncated_inputs)\n padding_strategy = PaddingStrategy.MAX_LENGTH\n\n batch_outputs = {}\n for i in range(batch_size):\n # padding\n outputs = self._pad(\n truncated_inputs[i],\n max_length=max_length,\n padding_strategy=padding_strategy,\n pad_to_multiple_of=pad_to_multiple_of,\n return_attention_mask=return_attention_mask,\n )\n\n for key, value in outputs.items():\n if key not in batch_outputs:\n batch_outputs[key] = []\n if value.dtype is np.dtype(np.float64):\n value = value.astype(np.float32)\n batch_outputs[key].append(value)\n\n return BatchFeature(batch_outputs, tensor_type=return_tensors)\n\n def _pad(\n self,\n processed_features: Union[Dict[str, np.ndarray], BatchFeature],\n max_length: Optional[int] = None,\n padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,\n pad_to_multiple_of: Optional[int] = None,\n return_attention_mask: Optional[bool] = None,\n ) -> dict:\n \"\"\"\n Pad inputs (on left/right and up to predefined length or max length in the batch)\n\n Args:\n processed_features:\n Dictionary of input values (`np.ndarray[float]`) / input vectors (`List[np.ndarray[float]]`) or batch\n of inputs values (`List[np.ndarray[int]]`) / input vectors (`List[np.ndarray[int]]`)\n max_length: maximum length of the returned list and optionally padding length (see below)\n padding_strategy: PaddingStrategy to use for padding.\n\n - PaddingStrategy.LONGEST Pad to the longest sequence in the batch\n - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)\n - PaddingStrategy.DO_NOT_PAD: Do not pad\n The feature_extractor padding sides are defined in self.padding_side:\n\n - 'left': pads on the left of the sequences\n - 'right': pads on the right of the sequences\n pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.\n This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability\n >= 7.5 (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.\n return_attention_mask:\n (optional) Set to False to avoid returning attention mask (default: set to model specifics)\n \"\"\"\n required_input = processed_features[self.model_input_names[0]]\n\n if padding_strategy == PaddingStrategy.LONGEST:\n max_length = len(required_input)\n\n if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):\n max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of\n\n needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) < max_length\n\n if return_attention_mask and \"attention_mask\" not in processed_features:\n processed_features[\"attention_mask\"] = np.ones(len(required_input), dtype=np.int32)\n\n if needs_to_be_padded:\n difference = max_length - len(required_input)\n if self.padding_side == \"right\":\n if return_attention_mask:\n processed_features[\"attention_mask\"] = np.pad(\n processed_features[\"attention_mask\"], (0, difference)\n )\n padding_shape = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)\n processed_features[self.model_input_names[0]] = np.pad(\n required_input, padding_shape, \"constant\", constant_values=self.padding_value\n )\n elif self.padding_side == \"left\":\n if return_attention_mask:\n processed_features[\"attention_mask\"] = np.pad(\n processed_features[\"attention_mask\"], (difference, 0)\n )\n padding_shape = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)\n processed_features[self.model_input_names[0]] = np.pad(\n required_input, padding_shape, \"constant\", constant_values=self.padding_value\n )\n else:\n raise ValueError(\"Invalid padding strategy:\" + str(self.padding_side))\n\n return processed_features\n\n def _truncate(\n self,\n processed_features: Union[Dict[str, np.ndarray], BatchFeature],\n max_length: Optional[int] = None,\n pad_to_multiple_of: Optional[int] = None,\n truncation: Optional[bool] = None,\n ):\n \"\"\"\n Truncate inputs to predefined length or max length in the batch\n\n Args:\n processed_features:\n Dictionary of input values (`np.ndarray[float]`) / input vectors (`List[np.ndarray[float]]`) or batch\n of inputs values (`List[np.ndarray[int]]`) / input vectors (`List[np.ndarray[int]]`)\n max_length: maximum length of the returned list and optionally padding length (see below)\n pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.\n This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability\n >= 7.5 (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.\n truncation:\n (optional) Activates truncation to cut input sequences longer than `max_length` to `max_length`.\n \"\"\"\n if not truncation:\n return processed_features\n elif truncation and max_length is None:\n raise ValueError(\"When setting ``truncation=True``, make sure that ``max_length`` is defined.\")\n\n required_input = processed_features[self.model_input_names[0]]\n\n # find `max_length` that fits `pad_to_multiple_of`\n if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):\n max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of\n\n needs_to_be_truncated = len(required_input) > max_length\n\n if needs_to_be_truncated:\n processed_features[self.model_input_names[0]] = processed_features[self.model_input_names[0]][:max_length]\n if \"attention_mask\" in processed_features:\n processed_features[\"attention_mask\"] = processed_features[\"attention_mask\"][:max_length]\n\n return processed_features\n\n def _get_padding_strategies(self, padding=False, max_length=None):\n \"\"\"\n Find the correct padding strategy\n \"\"\"\n\n # Get padding strategy\n if padding is not False:\n if padding is True:\n padding_strategy = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch\n elif not isinstance(padding, PaddingStrategy):\n padding_strategy = PaddingStrategy(padding)\n elif isinstance(padding, PaddingStrategy):\n padding_strategy = padding\n else:\n padding_strategy = PaddingStrategy.DO_NOT_PAD\n\n # Set max length if needed\n if max_length is None:\n if padding_strategy == PaddingStrategy.MAX_LENGTH:\n raise ValueError(\n f\"When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that\" f\" max_length is defined\"\n )\n\n # Test if we have a padding value\n if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):\n raise ValueError(\n \"Asking to pad but the feature_extractor does not have a padding value. \"\n \"Please select a value to use as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.\"\n )\n\n return padding_strategy\n" ]
[ [ "tensorflow.keras.layers.LayerNormalization", "tensorflow.convert_to_tensor", "tensorflow.concat", "tensorflow.cast", "tensorflow.pad", "tensorflow.squeeze", "tensorflow.gather", "tensorflow.name_scope", "tensorflow.matmul", "tensorflow.fill", "tensorflow.keras.layers.Dense", "tensorflow.split", "tensorflow.nn.bias_add", "tensorflow.multiply", "tensorflow.transpose", "tensorflow.nn.softmax", "tensorflow.math.sqrt", "tensorflow.range", "tensorflow.reshape", "tensorflow.keras.layers.Dropout", "tensorflow.TensorSpec" ], [ "tensorflow.keras.layers.LayerNormalization", "tensorflow.convert_to_tensor", "tensorflow.concat", "tensorflow.zeros", "tensorflow.keras.constraints.serialize", "tensorflow.stack", "tensorflow.reduce_sum", "tensorflow.cast", "tensorflow.keras.regularizers.serialize", "tensorflow.pad", "tensorflow.where", "tensorflow.keras.backend.int_shape", "tensorflow.nn.moments", "tensorflow.nn.top_k", "tensorflow.square", "tensorflow.tile", "tensorflow.keras.initializers.get", "tensorflow.nn.l2_normalize", "tensorflow.matmul", "tensorflow.nn.batch_normalization", "tensorflow.executing_eagerly", "tensorflow.shape", "tensorflow.keras.layers.Dense", "tensorflow.random.uniform", "tensorflow.keras.initializers.serialize", "numpy.random.rand", "tensorflow.nn.ctc_loss", "tensorflow.not_equal", "tensorflow.reduce_max", "tensorflow.nn.softmax", "tensorflow.constant", "tensorflow.transpose", "tensorflow.range", "tensorflow.keras.constraints.get", "tensorflow.reduce_mean", "tensorflow.keras.layers.Conv1D", "tensorflow.reshape", "tensorflow.ones_like", "tensorflow.expand_dims", "tensorflow.ones", "tensorflow.keras.regularizers.get", "numpy.random.uniform", "tensorflow.keras.layers.Dropout" ], [ "numpy.zeros_like", "numpy.where" ], [ "numpy.pad", "numpy.dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
maotto/movement_primitives
[ "ce355837f06cb5fada24be7259cb0305e8ea5d91", "ce355837f06cb5fada24be7259cb0305e8ea5d91", "b79c78a5a0667cc24a26b7b6cc64a5762d8f4dd4", "ce355837f06cb5fada24be7259cb0305e8ea5d91" ]
[ "examples/plot_obstacle_avoidance_2d.py", "examples/plot_dmp_potential_field.py", "examples/external_dependencies/vis_solar_panel.py", "movement_primitives/data/_lasa.py" ]
[ "\"\"\"\n========================\nObstacle Avoidance in 2D\n========================\n\nPlots a 2D DMP that goes through a point obstacle when there is no coupling\nterm for obstacle avoidance and a 2D DMP that avoids the point obstacle with\na coupling term.\n\"\"\"\nprint(__doc__)\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom movement_primitives.dmp import DMP, CouplingTermObstacleAvoidance2D\n\n\nexecution_time = 1.0\nstart_y = np.zeros(2)\ngoal_y = np.ones(2)\n\ndmp = DMP(n_dims=2, execution_time=execution_time, n_weights_per_dim=3)\ndmp.configure(start_y=start_y, goal_y=goal_y)\ndmp.set_weights(np.array([-50.0, 100.0, 300.0, -200.0, -200.0, -200.0]))\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\nobstacle_position = np.array([0.92, 0.5])\nT, Y = dmp.open_loop(run_t=execution_time)\nax.plot(Y[:, 0], Y[:, 1], label=\"Original\")\ncoupling_term = CouplingTermObstacleAvoidance2D(obstacle_position)\nT, Y = dmp.open_loop(run_t=execution_time, coupling_term=coupling_term)\nax.plot(Y[:, 0], Y[:, 1], label=\"Obstacle avoidance\")\nax.scatter(start_y[0], start_y[1], c=\"r\", label=\"Start\")\nax.scatter(goal_y[0], goal_y[1], c=\"g\", label=\"Goal\")\nax.scatter(obstacle_position[0], obstacle_position[1], c=\"y\", label=\"Obstacle\")\nax.legend()\nplt.tight_layout()\nplt.show()\n", "\"\"\"\n======================\nDMP as Potential Field\n======================\n\nA Dynamical Movement Primitive defines a potential field that superimposes\nseveral components: transformation system (goal-directed movement), forcing\nterm (learned shape), and coupling terms (e.g., obstacle avoidance).\n\"\"\"\nprint(__doc__)\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom movement_primitives.dmp import DMP, CouplingTermObstacleAvoidance2D\nfrom movement_primitives.dmp_potential_field import plot_potential_field_2d\n\n\nstart_y = np.array([0, 0], dtype=float)\ngoal_y = np.array([1, 1], dtype=float)\nobstacle = np.array([0.85, 0.5])\nrandom_state = np.random.RandomState(1)\n\ndmp = DMP(n_dims=2, n_weights_per_dim=10, dt=0.01, execution_time=1.0)\ndmp.configure(start_y=start_y, goal_y=goal_y)\n\ndmp_ft = DMP(n_dims=2, n_weights_per_dim=10, dt=0.01, execution_time=1.0)\ndmp_ft.forcing_term.weights[:, :] = random_state.randn(\n *dmp_ft.forcing_term.weights.shape) * 500.0\ndmp_ft.configure(start_y=start_y, goal_y=goal_y)\n\ndmp_ct = DMP(n_dims=2, n_weights_per_dim=10, dt=0.01, execution_time=1.0)\ndmp_ct.forcing_term.weights[:, :] = dmp_ft.forcing_term.weights[:, :]\ndmp_ct.configure(start_y=start_y, goal_y=goal_y)\ncoupling_term = CouplingTermObstacleAvoidance2D(obstacle)\n\nn_rows, n_cols = 2, 4\nn_subplots = n_rows * n_cols\nx_range = -0.2, 1.2\ny_range = -0.2, 1.2\n\nposition = np.copy(start_y)\nvelocity = np.zeros_like(start_y)\n\nposition_ft = np.copy(start_y)\nvelocity_ft = np.zeros_like(start_y)\n\nposition_ct = np.copy(start_y)\nvelocity_ct = np.zeros_like(start_y)\n\nplt.figure(figsize=(12, 6))\npositions = [position]\npositions_ft = [position_ft]\npositions_ct = [position_ct]\nfor i in range(n_subplots):\n ax = plt.subplot(n_rows, n_cols, i + 1, aspect=\"equal\")\n ax.set_title(f\"t = {dmp.t:.02f}\", backgroundcolor=\"#ffffffff\", y=0.05)\n\n plot_potential_field_2d(\n ax, dmp_ct, x_range=x_range, y_range=y_range, n_ticks=15,\n obstacle=obstacle)\n plt.plot(start_y[0], start_y[1], \"o\", color=\"b\", markersize=10)\n plt.plot(goal_y[0], goal_y[1], \"o\", color=\"g\", markersize=10)\n plt.plot(obstacle[0], obstacle[1], \"o\", color=\"y\", markersize=10)\n\n path = np.array(positions)\n plt.plot(path[:, 0], path[:, 1], lw=5, color=\"g\", label=\"Transformation System\")\n path_ft = np.array(positions_ft)\n plt.plot(path_ft[:, 0], path_ft[:, 1], lw=5, color=\"r\", label=\"+ Forcing Term\")\n path_ct = np.array(positions_ct)\n plt.plot(path_ct[:, 0], path_ct[:, 1], lw=5, color=\"y\", label=\"+ Obstacle Avoidance\")\n\n ax.set_xlim(x_range)\n ax.set_ylim(y_range)\n plt.setp(ax, xticks=(), yticks=())\n if i == 0:\n ax.legend(loc=\"upper left\")\n\n if i == n_subplots - 1:\n break\n\n while dmp.t <= dmp.execution_time * (1 + i) / (n_subplots - 1):\n position, velocity = dmp.step(position, velocity)\n positions.append(position)\n position_ft, velocity_ft = dmp_ft.step(position_ft, velocity_ft)\n positions_ft.append(position_ft)\n position_ct, velocity_ct = dmp_ct.step(\n position_ct, velocity_ct, coupling_term=coupling_term)\n positions_ct.append(position_ct)\nplt.subplots_adjust(\n left=0.0, bottom=0.0, right=1.0, top=1.0, wspace=0.01, hspace=0.01)\nplt.show()\n", "import numpy as np\nimport pytransform3d.visualizer as pv\nimport pytransform3d.rotations as pr\nimport pytransform3d.transformations as pt\nimport pytransform3d.trajectories as ptr\nfrom mocap.cleaning import smooth_exponential_coordinates, smooth_quaternion_trajectory\nfrom movement_primitives.kinematics import Kinematics\nfrom movement_primitives.dmp import DualCartesianDMP\nfrom movement_primitives.io import (write_json, write_yaml, write_pickle)\nfrom movement_primitives.testing.simulation import get_absolute_path\n\n\ndef panel_pose(tm):\n tcp_left = tm.get_transform(\"LTCP_Link\", \"RH5_Root_Link\")\n tcp_right = tm.get_transform(\"RTCP_Link\", \"RH5_Root_Link\")\n tcp_left_pos = tcp_left[:3, 3]\n tcp_right_pos = tcp_right[:3, 3]\n tcp_middle = 0.5 * (tcp_left_pos + tcp_right_pos)\n x_axis = pr.norm_vector(tcp_right_pos - tcp_left_pos)\n y_axis = -pr.norm_vector(0.5 * (tcp_left[:3, 1] + tcp_right[:3, 1]))\n R_panel = pr.matrix_from_two_vectors(x_axis, y_axis)\n return pt.transform_from(R_panel, tcp_middle)\n\n\ndef animation_callback(step, graph, left_arm, right_arm, left_joint_trajectory, right_joint_trajectory, panel_mesh):\n left_arm.forward(left_joint_trajectory[step])\n right_arm.forward(right_joint_trajectory[step])\n graph.set_data()\n panel_mesh.set_data(panel_pose(graph.tm))\n return graph, panel_mesh\n\n\nsolar_panel_idx = 0\npanel_rotation_angle = np.deg2rad(90)\nn_steps = 201\n\nwith open(get_absolute_path(\"pybullet-only-arms-urdf/urdf/RH5.urdf\", \"models/robots/rh5_models\"), \"r\") as f:\n kin = Kinematics(f.read(), mesh_path=get_absolute_path(\"pybullet-only-arms-urdf/urdf/\", \"models/robots/rh5_models\"))\n#kin.tm.write_png(\"graph.png\", \"twopi\")\nleft_arm = kin.create_chain(\n [\"ALShoulder1\", \"ALShoulder2\", \"ALShoulder3\",\n \"ALElbow\", \"ALWristRoll\", \"ALWristYaw\", \"ALWristPitch\"],\n \"RH5_Root_Link\", \"LTCP_Link\")\nright_arm = kin.create_chain(\n [\"ARShoulder1\", \"ARShoulder2\", \"ARShoulder3\",\n \"ARElbow\", \"ARWristRoll\", \"ARWristYaw\", \"ARWristPitch\"],\n \"RH5_Root_Link\", \"RTCP_Link\")\n\n#q0_left = np.array([-1.57, 1.25, 0, -1.75, 0, 0, 0.8])\n#q0_right = np.array([1.57, -1.25, 0, 1.75, 0, 0, 0.8])\nq0_left = np.array([-1.57, 0.9, 0, -1.3, 0, 0, -0.55])\nq0_right = np.array([1.57, -0.9, 0, 1.3, 0, 0, -0.55])\n\nleft_arm.forward(q0_left)\nright_arm.forward(q0_right)\n\nleft2base_start = kin.tm.get_transform(\"LTCP_Link\", \"RH5_Root_Link\")\nright2base_start = kin.tm.get_transform(\"RTCP_Link\", \"RH5_Root_Link\")\ntcp_left_pos = left2base_start[:3, 3]\ntcp_right_pos = right2base_start[:3, 3]\n\npanel2base_start = panel_pose(kin.tm)\nleft2panel_start = pt.concat(left2base_start, pt.invert_transform(panel2base_start))\nright2panel_start = pt.concat(right2base_start, pt.invert_transform(panel2base_start))\n\n\nrotation_axis = -pr.unity\n\nstart2end = pt.rotate_transform(np.eye(4), pr.matrix_from_compact_axis_angle(rotation_axis * panel_rotation_angle))\nleft2panel_end = pt.concat(left2panel_start, start2end)\nright2panel_end = pt.concat(right2panel_start, start2end)\n\nleft2base_end = pt.concat(left2panel_end, panel2base_start)\nright2base_end = pt.concat(right2panel_end, panel2base_start)\n\nstart_left = pt.exponential_coordinates_from_transform(left2base_start)\nend_left = pt.exponential_coordinates_from_transform(left2base_end)\nstart_right = pt.exponential_coordinates_from_transform(right2base_start)\nend_right = pt.exponential_coordinates_from_transform(right2base_end)\nstart_left, end_left = smooth_exponential_coordinates(np.array([start_left, end_left]))\nstart_right, end_right = smooth_exponential_coordinates(np.array([start_right, end_right]))\n\nT = np.linspace(0, 1, n_steps)\nleft_trajectory = start_left[np.newaxis] + T[:, np.newaxis] * (end_left[np.newaxis] - start_left[np.newaxis])\nright_trajectory = start_right[np.newaxis] + T[:, np.newaxis] * (end_right[np.newaxis] - start_right[np.newaxis])\n\n\"\"\"# axis-angle SLERP\nimport pytransform3d.batch_rotations as pbr\na_start = np.hstack((rotation_axis, (0,)))\na_end = np.hstack((rotation_axis, (panel_rotation_angle,)))\nA = np.array([pr.axis_angle_slerp(a_start, a_end, t) for t in np.linspace(0, 1, n_steps)])\nRs = pbr.matrices_from_compact_axis_angles(A[:, :3] * A[:, 3, np.newaxis])\nstart2current = np.empty((n_steps, 4, 4))\nstart2current[:] = np.eye(4)\nstart2current[:, :3, :3] = Rs\nleft_trajectory = np.empty((n_steps, 4, 4))\nright_trajectory = np.empty((n_steps, 4, 4))\nfor t in range(n_steps):\n left2panel_current = pt.concat(left2panel_start, start2current[t])\n left2base_current = pt.concat(left2panel_current, panel2base_start)\n left_trajectory[t] = left2base_current\n right2panel_current = pt.concat(right2panel_start, start2current[t])\n right2base_current = pt.concat(right2panel_current, panel2base_start)\n right_trajectory[t] = right2base_current\nleft_trajectory = ptr.exponential_coordinates_from_transforms(left_trajectory)\nright_trajectory = ptr.exponential_coordinates_from_transforms(right_trajectory)\n#\"\"\"\n\nprint(\"Imitation...\")\ndt = 0.01\nexecution_time = (n_steps - 1) * dt\nT = np.linspace(0, execution_time, n_steps)\nY = np.hstack((smooth_exponential_coordinates(left_trajectory),\n smooth_exponential_coordinates(right_trajectory)))\n#dmp = DMP(n_dims=Y.shape[1], execution_time=execution_time, dt=dt, n_weights_per_dim=10)\n#dmp.imitate(T, Y)\n#_, Y = dmp.open_loop()\n\n########################################################################################################################\n# DMP export\n\n########################################################################################################################\n\nleft_trajectory = Y[:, :6]\nright_trajectory = Y[:, 6:]\n\nleft_trajectory = ptr.transforms_from_exponential_coordinates(left_trajectory)\nright_trajectory = ptr.transforms_from_exponential_coordinates(right_trajectory)\n\nprint(\"Inverse kinematics...\")\nrandom_state = np.random.RandomState(0)\nleft_joint_trajectory = left_arm.inverse_trajectory(left_trajectory, q0_left, random_state=random_state)\nright_joint_trajectory = right_arm.inverse_trajectory(right_trajectory, q0_right, random_state=random_state)\n\n########################################################################################################################\n# Data export\nlwp2ltcp = kin.tm.get_transform(\"ALWristPitch_Link\", \"LTCP_Link\")\nrwp2rtcp = kin.tm.get_transform(\"ARWristPitch_Link\", \"RTCP_Link\")\n\nlwp_trajectory = np.array([pt.concat(lwp2ltcp, ltcp2base) for ltcp2base in left_trajectory])\nrwp_trajectory = np.array([pt.concat(rwp2rtcp, rtcp2base) for rtcp2base in right_trajectory])\n\nleft_trajectory_pq = ptr.pqs_from_transforms(lwp_trajectory)\nright_trajectory_pq = ptr.pqs_from_transforms(rwp_trajectory)\n\ndmp = DualCartesianDMP(execution_time=execution_time, dt=dt, n_weights_per_dim=10)\nY_pq = np.empty((len(Y), 14))\nY_pq[:, :7] = left_trajectory_pq\nY_pq[:, 7:] = right_trajectory_pq\nY_pq[:, 3:7] = smooth_quaternion_trajectory(Y_pq[:, 3:7])\nY_pq[:, 10:14] = smooth_quaternion_trajectory(Y_pq[:, 10:14])\ndmp.imitate(T, Y_pq)\n\nwrite_yaml(\"rh5_dual_arm_dmp.yaml\", dmp)\nwrite_json(\"rh5_dual_arm_dmp.json\", dmp)\nwrite_pickle(\"rh5_dual_arm_dmp.pickle\", dmp)\n\nimport pandas as pd\ndata_export = np.hstack((\n left_trajectory_pq,\n right_trajectory_pq\n))\ndf = pd.DataFrame(\n data=data_export, columns=[\n \"left_pos_x\", \"left_pos_y\", \"left_pos_z\", \"left_ori_w\", \"left_ori_x\", \"left_ori_y\", \"left_ori_z\",\n \"right_pos_x\", \"right_pos_y\", \"right_pos_z\", \"right_ori_w\", \"right_ori_x\", \"right_ori_y\", \"right_ori_z\"],\n index=pd.Index(np.linspace(0, execution_time, len(left_trajectory_pq)), name=\"Time\"))\ndf.to_csv(\"rh5_dual_arm_rotate_panel_posquat.csv\")\n\ndata_export = np.hstack((left_joint_trajectory, right_joint_trajectory))\ndf = pd.DataFrame(\n data=data_export, columns=left_arm.joint_names + right_arm.joint_names,\n index=pd.Index(np.linspace(0, execution_time, len(left_trajectory_pq)), name=\"Time\"))\ndf.to_csv(\"rh5_dual_arm_rotate_panel_joints.csv\")# float_format=\"%.20f\"\n########################################################################################################################\n\n#\"\"\"\nimport matplotlib.pyplot as plt\nfrom movement_primitives.plot import plot_trajectory_in_rows\naxes = plot_trajectory_in_rows(np.hstack((left_joint_trajectory, right_joint_trajectory)))\nfor i, jn in enumerate(left_arm.joint_names + right_arm.joint_names):\n joint_limits = kin.tm._joints[jn][-2]\n axes[i].plot([0, len(left_joint_trajectory)], [joint_limits[0]] * 2, c=\"r\")\n axes[i].plot([0, len(left_joint_trajectory)], [joint_limits[1]] * 2, c=\"r\")\nplt.show()\n#\"\"\"\n\nfig = pv.figure()\nfig.plot_transform(s=0.3)\n\n# \"solar_panels/solar_panel_02/meshes/stl/base link.stl\"\n# \"solar_panels/solar_panel_03/meshes/stl/base link.stl\"\npanel_mesh = fig.plot_mesh(\"solar_panels/solar_panel_02/meshes/stl/base link.stl\", A2B=panel2base_start)\n\ngraph = fig.plot_graph(\n kin.tm, \"RH5_Root_Link\", show_visuals=True, show_collision_objects=False, show_frames=True, s=0.1,\n whitelist=[\"ALWristPitch_Link\", \"ARWristPitch_Link\", \"LTCP_Link\", \"RTCP_Link\"])\n\nfig.plot_transform(panel2base_start, s=0.2)\n\nfig.plot_transform(left2base_start, s=0.15)\nfig.plot_transform(right2base_start, s=0.15)\nfig.plot_transform(left_trajectory[-1], s=0.15)\nfig.plot_transform(right_trajectory[-1], s=0.15)\n\n#pv.Trajectory(left_trajectory, s=0.05).add_artist(fig)\n#pv.Trajectory(right_trajectory, s=0.05).add_artist(fig)\n\npv.Trajectory(lwp_trajectory, s=0.05).add_artist(fig)\npv.Trajectory(rwp_trajectory, s=0.05).add_artist(fig)\n\nfig.view_init()\nfig.animate(\n animation_callback, len(left_joint_trajectory), loop=True,\n fargs=(graph, left_arm, right_arm, left_joint_trajectory, right_joint_trajectory, panel_mesh))\nfig.show()\n", "import os\nimport zipfile\nimport io\nimport scipy.io\nimport numpy as np\ntry:\n from urllib2 import urlopen\nexcept ImportError:\n from urllib.request import urlopen\n\n\nLASA_URL = (\"http://bitbucket.org/khansari/lasahandwritingdataset/get/\"\n \"38304f7c0ac4.zip\")\n\n\ndef load_lasa(shape_idx):\n \"\"\"Load demonstrations from LASA dataset.\n\n The LASA dataset contains 2D handwriting motions recorded from a\n Tablet-PC. It can be found `here\n <https://bitbucket.org/khansari/lasahandwritingdataset>`_\n Take a look at the `detailed explanation\n <http://cs.stanford.edu/people/khansari/DSMotions#SEDS_Benchmark_Dataset>`_\n for more information.\n\n The following plot shows multiple demonstrations for the same shape.\n\n .. plot::\n\n import matplotlib.pyplot as plt\n from movement_primitives.data import load_lasa\n X, Xd, Xdd, dt, shape_name = load_lasa(0)\n plt.figure()\n plt.title(shape_name)\n plt.plot(X[:, :, 0].T, X[:, :, 1].T)\n plt.show()\n\n Parameters\n ----------\n shape_idx : int\n Choose demonstrated shape, must be within range(30).\n\n Returns\n -------\n T : array, shape (n_demos, n_steps)\n Times\n\n X : array, shape (n_demos, n_steps, n_dims)\n Positions\n\n Xd : array, shape (n_demos, n_steps, n_dims)\n Velocities\n\n Xdd : array, shape (n_demos, n_steps, n_dims)\n Accelerations\n\n dt : float\n Time between steps\n\n shape_name : string\n Name of the Matlab file from which we load the demonstrations\n (without suffix).\n \"\"\"\n dataset_path = get_common_dataset_path()\n if not os.path.isdir(dataset_path + \"lasa_data\"): # pragma: no cover\n url = urlopen(LASA_URL)\n z = zipfile.ZipFile(io.BytesIO(url.read()))\n z.extractall(dataset_path)\n os.rename(dataset_path + z.namelist()[0],\n dataset_path + \"lasa_data\" + os.sep)\n\n dataset_path += \"lasa_data\" + os.sep + \"DataSet\" + os.sep\n demos, shape_name = _load_from_matlab_file(dataset_path, shape_idx)\n X, Xd, Xdd, dt = _convert_demonstrations(demos)\n t = np.linspace(0, X.shape[1], X.shape[1])\n T = np.tile(t, (X.shape[0], 1))\n return T, X, Xd, Xdd, dt, shape_name\n\n\ndef _load_from_matlab_file(dataset_path, shape_idx):\n \"\"\"Load demonstrations from Matlab files.\n\n Parameters\n ----------\n dataset_path : str\n Path where external datasets are stored.\n\n shape_idx : int\n Index of the shape in the LASA dataset.\n\n Returns\n -------\n demos : array\n Demonstrations.\n\n shape_name : string\n Name of the Matlab file from which we load the demonstrations\n (without suffix).\n \"\"\"\n file_name = sorted(os.listdir(dataset_path))[shape_idx]\n return (scipy.io.loadmat(dataset_path + file_name)[\"demos\"][0],\n file_name[:-4])\n\n\ndef _convert_demonstrations(demos):\n \"\"\"Convert Matlab struct to numpy arrays.\n\n Parameters\n ----------\n demos : array\n Demonstrations.\n\n Returns\n -------\n X : array, shape (n_demos, n_steps, n_dims)\n Positions\n\n Xd : array, shape (n_demos, n_steps, n_dims)\n Velocities\n\n Xdd : array, shape (n_demos, n_steps, n_dims)\n Accelerations\n\n dt : float\n Time between steps\n \"\"\"\n tmp = []\n for demo_idx in range(demos.shape[0]):\n # The Matlab format is strange...\n demo = demos[demo_idx][0, 0]\n # Positions, velocities and accelerations\n tmp.append((demo[0], demo[2], demo[3]))\n\n X = np.transpose([P for P, _, _ in tmp], [0, 2, 1])\n Xd = np.transpose([V for _, V, _ in tmp], [0, 2, 1])\n Xdd = np.transpose([A for _, _, A in tmp], [0, 2, 1])\n\n dt = float(demos[0][0, 0][4])\n\n return X, Xd, Xdd, dt\n\n\ndef get_common_dataset_path():\n \"\"\"Returns the path where all external datasets are stored.\n\n Returns\n -------\n dataset_path : str\n Path where external datasets are stored.\n \"\"\"\n dataset_path = os.path.expanduser(\"~\")\n dataset_path += os.sep + \".movement_primitive_data\" + os.sep\n return dataset_path\n" ]
[ [ "matplotlib.pyplot.tight_layout", "numpy.ones", "numpy.array", "numpy.zeros", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ], [ "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "numpy.copy", "matplotlib.pyplot.subplot", "numpy.zeros_like", "matplotlib.pyplot.setp", "matplotlib.pyplot.subplots_adjust", "numpy.array", "numpy.random.RandomState", "matplotlib.pyplot.figure" ], [ "numpy.hstack", "numpy.linspace", "numpy.eye", "numpy.deg2rad", "numpy.array", "numpy.random.RandomState", "matplotlib.pyplot.show" ], [ "numpy.tile", "numpy.linspace", "numpy.transpose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
dongzhiming/cgp-cnn-PyTorch
[ "be9d3ee63741ef59bac7cf3c905833d747267207" ]
[ "exp_main.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport pickle\nimport pandas as pd\n\nfrom cgp import *\nfrom cgp_config import *\nfrom cnn_train import CNN_train\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Evolving CAE structures')\n parser.add_argument('--gpu_num', '-g', type=int, default=1, help='Num. of GPUs')\n parser.add_argument('--lam', '-l', type=int, default=2, help='Num. of offsprings')\n parser.add_argument('--net_info_file', default='network_info.pickle', help='Network information file name')\n parser.add_argument('--log_file', default='./log_cgp.txt', help='Log file name')\n parser.add_argument('--mode', '-m', default='evolution', help='Mode (evolution / retrain / reevolution)')\n parser.add_argument('--init', '-i', action='store_true')\n args = parser.parse_args()\n\n # --- Optimization of the CNN architecture ---\n if args.mode == 'evolution':\n # Create CGP configuration and save network information\n network_info = CgpInfoConvSet(rows=5, cols=30, level_back=10, min_active_num=1, max_active_num=30)\n with open(args.net_info_file, mode='wb') as f:\n pickle.dump(network_info, f)\n # Evaluation function for CGP (training CNN and return validation accuracy)\n imgSize = 32\n eval_f = CNNEvaluation(gpu_num=args.gpu_num, dataset='cifar10', verbose=True, epoch_num=50, batchsize=128,\n imgSize=imgSize)\n\n # Execute evolution\n cgp = CGP(network_info, eval_f, lam=args.lam, imgSize=imgSize, init=args.init)\n cgp.modified_evolution(max_eval=250, mutation_rate=0.1, log_file=args.log_file)\n\n # --- Retraining evolved architecture ---\n elif args.mode == 'retrain':\n print('Retrain')\n # In the case of existing log_cgp.txt\n # Load CGP configuration\n with open(args.net_info_file, mode='rb') as f:\n network_info = pickle.load(f)\n # Load network architecture\n cgp = CGP(network_info, None)\n data = pd.read_csv(args.log_file, header=None) # Load log file\n cgp.load_log(list(data.tail(1).values.flatten().astype(int))) # Read the log at final generation\n print(cgp._log_data(net_info_type='active_only', start_time=0))\n # Retraining the network\n temp = CNN_train('cifar10', validation=False, verbose=True, batchsize=128)\n acc = temp(cgp.pop[0].active_net_list(), 0, epoch_num=500, out_model='retrained_net.model')\n print(acc)\n\n # # otherwise (in the case where we do not have a log file.)\n # temp = CNN_train('haze1', validation=False, verbose=True, imgSize=128, batchsize=16)\n # cgp = [['input', 0], ['S_SumConvBlock_64_3', 0], ['S_ConvBlock_64_5', 1], ['S_SumConvBlock_128_1', 2], ['S_SumConvBlock_64_1', 3], ['S_SumConvBlock_64_5', 4], ['S_DeConvBlock_3_3', 5]]\n # acc = temp(cgp, 0, epoch_num=500, out_model='retrained_net.model')\n\n elif args.mode == 'reevolution':\n # restart evolution\n print('Restart Evolution')\n imgSize = 64\n with open('network_info.pickle', mode='rb') as f:\n network_info = pickle.load(f)\n eval_f = CNNEvaluation(gpu_num=args.gpu_num, dataset='cifar10', verbose=True, epoch_num=50, batchsize=128,\n imgSize=imgSize)\n cgp = CGP(network_info, eval_f, lam=args.lam, imgSize=imgSize)\n\n data = pd.read_csv('./log_cgp.txt', header=None)\n cgp.load_log(list(data.tail(1).values.flatten().astype(int)))\n cgp.modified_evolution(max_eval=250, mutation_rate=0.1, log_file='./log_restat.txt')\n\n else:\n print('Undefined mode. Please check the \"-m evolution or retrain or reevolution\" ')\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
jwrth/scanpy
[ "9fa01020d1f0712166b3591e67d0c766c765eca0" ]
[ "scanpy/_utils.py" ]
[ "\"\"\"Utility functions and classes\n\"\"\"\nimport sys\nimport inspect\nimport warnings\nimport importlib.util\nfrom enum import Enum\nfrom pathlib import Path\nfrom weakref import WeakSet\nfrom collections import namedtuple\nfrom functools import partial, wraps\nfrom types import ModuleType, MethodType\nfrom typing import Union, Callable, Optional, Mapping, Any, Dict, Tuple\n\nimport numpy as np\nfrom numpy import random\nfrom scipy import sparse\nfrom anndata import AnnData, __version__ as anndata_version\nfrom textwrap import dedent\nfrom packaging import version\n\nfrom ._settings import settings\nfrom ._compat import Literal\nfrom . import logging as logg\n\n\nclass Empty(Enum):\n token = 0\n\n\n_empty = Empty.token\n\n# e.g. https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html\nAnyRandom = Union[None, int, random.RandomState] # maybe in the future random.Generator\n\nEPS = 1e-15\n\n\ndef check_versions():\n from ._compat import pkg_version\n\n umap_version = pkg_version(\"umap-learn\")\n\n if version.parse(anndata_version) < version.parse('0.6.10'):\n from . import __version__\n\n raise ImportError(\n f'Scanpy {__version__} needs anndata version >=0.6.10, '\n f'not {anndata_version}.\\nRun `pip install anndata -U --no-deps`.'\n )\n\n if umap_version < version.parse('0.3.0'):\n from . import __version__\n\n # make this a warning, not an error\n # it might be useful for people to still be able to run it\n logg.warning(\n f'Scanpy {__version__} needs umap ' f'version >=0.3.0, not {umap_version}.'\n )\n\n\ndef getdoc(c_or_f: Union[Callable, type]) -> Optional[str]:\n if getattr(c_or_f, '__doc__', None) is None:\n return None\n doc = inspect.getdoc(c_or_f)\n if isinstance(c_or_f, type) and hasattr(c_or_f, '__init__'):\n sig = inspect.signature(c_or_f.__init__)\n else:\n sig = inspect.signature(c_or_f)\n\n def type_doc(name: str):\n param: inspect.Parameter = sig.parameters[name]\n cls = getattr(param.annotation, '__qualname__', repr(param.annotation))\n if param.default is not param.empty:\n return f'{cls}, optional (default: {param.default!r})'\n else:\n return cls\n\n return '\\n'.join(\n f'{line} : {type_doc(line)}' if line.strip() in sig.parameters else line\n for line in doc.split('\\n')\n )\n\n\ndef deprecated_arg_names(arg_mapping: Mapping[str, str]):\n \"\"\"\n Decorator which marks a functions keyword arguments as deprecated. It will\n result in a warning being emitted when the deprecated keyword argument is\n used, and the function being called with the new argument.\n\n Parameters\n ----------\n arg_mapping\n Mapping from deprecated argument name to current argument name.\n \"\"\"\n\n def decorator(func):\n @wraps(func)\n def func_wrapper(*args, **kwargs):\n warnings.simplefilter('always', DeprecationWarning) # turn off filter\n for old, new in arg_mapping.items():\n if old in kwargs:\n warnings.warn(\n f\"Keyword argument '{old}' has been \"\n f\"deprecated in favour of '{new}'. \"\n f\"'{old}' will be removed in a future version.\",\n category=DeprecationWarning,\n stacklevel=2,\n )\n val = kwargs.pop(old)\n kwargs[new] = val\n # reset filter\n warnings.simplefilter('default', DeprecationWarning)\n return func(*args, **kwargs)\n\n return func_wrapper\n\n return decorator\n\n\ndef _one_of_ours(obj, root: str):\n return (\n hasattr(obj, \"__name__\")\n and not obj.__name__.split(\".\")[-1].startswith(\"_\")\n and getattr(\n obj, '__module__', getattr(obj, '__qualname__', obj.__name__)\n ).startswith(root)\n )\n\n\ndef descend_classes_and_funcs(mod: ModuleType, root: str, encountered=None):\n if encountered is None:\n encountered = WeakSet()\n for obj in vars(mod).values():\n if not _one_of_ours(obj, root):\n continue\n if callable(obj) and not isinstance(obj, MethodType):\n yield obj\n if isinstance(obj, type):\n for m in vars(obj).values():\n if callable(m) and _one_of_ours(m, root):\n yield m\n elif isinstance(obj, ModuleType) and obj not in encountered:\n if obj.__name__.startswith('scanpy.tests'):\n # Python’s import mechanism seems to add this to `scanpy`’s attributes\n continue\n encountered.add(obj)\n yield from descend_classes_and_funcs(obj, root, encountered)\n\n\ndef annotate_doc_types(mod: ModuleType, root: str):\n for c_or_f in descend_classes_and_funcs(mod, root):\n c_or_f.getdoc = partial(getdoc, c_or_f)\n\n\ndef _doc_params(**kwds):\n \"\"\"\\\n Docstrings should start with \"\\\" in the first line for proper formatting.\n \"\"\"\n\n def dec(obj):\n obj.__orig_doc__ = obj.__doc__\n obj.__doc__ = dedent(obj.__doc__).format_map(kwds)\n return obj\n\n return dec\n\n\ndef _check_array_function_arguments(**kwargs):\n \"\"\"Checks for invalid arguments when an array is passed.\n\n Helper for functions that work on either AnnData objects or array-likes.\n \"\"\"\n # TODO: Figure out a better solution for documenting dispatched functions\n invalid_args = [k for k, v in kwargs.items() if v is not None]\n if len(invalid_args) > 0:\n raise TypeError(\n f\"Arguments {invalid_args} are only valid if an AnnData object is passed.\"\n )\n\n\ndef _check_use_raw(adata: AnnData, use_raw: Union[None, bool]) -> bool:\n \"\"\"\n Normalize checking `use_raw`.\n\n My intentention here is to also provide a single place to throw a deprecation warning from in future.\n \"\"\"\n if use_raw is not None:\n return use_raw\n else:\n if adata.raw is not None:\n return True\n else:\n return False\n\n\n# --------------------------------------------------------------------------------\n# Graph stuff\n# --------------------------------------------------------------------------------\n\n\ndef get_igraph_from_adjacency(adjacency, directed=None):\n \"\"\"Get igraph graph from adjacency matrix.\"\"\"\n import igraph as ig\n\n sources, targets = adjacency.nonzero()\n weights = adjacency[sources, targets]\n if isinstance(weights, np.matrix):\n weights = weights.A1\n g = ig.Graph(directed=directed)\n g.add_vertices(adjacency.shape[0]) # this adds adjacency.shape[0] vertices\n g.add_edges(list(zip(sources, targets)))\n try:\n g.es['weight'] = weights\n except:\n pass\n if g.vcount() != adjacency.shape[0]:\n logg.warning(\n f'The constructed graph has only {g.vcount()} nodes. '\n 'Your adjacency matrix contained redundant nodes.'\n )\n return g\n\n\ndef get_sparse_from_igraph(graph, weight_attr=None):\n from scipy.sparse import csr_matrix\n\n edges = graph.get_edgelist()\n if weight_attr is None:\n weights = [1] * len(edges)\n else:\n weights = graph.es[weight_attr]\n if not graph.is_directed():\n edges.extend([(v, u) for u, v in edges])\n weights.extend(weights)\n shape = graph.vcount()\n shape = (shape, shape)\n if len(edges) > 0:\n return csr_matrix((weights, zip(*edges)), shape=shape)\n else:\n return csr_matrix(shape)\n\n\n# --------------------------------------------------------------------------------\n# Group stuff\n# --------------------------------------------------------------------------------\n\n\ndef compute_association_matrix_of_groups(\n adata: AnnData,\n prediction: str,\n reference: str,\n normalization: Literal['prediction', 'reference'] = 'prediction',\n threshold: float = 0.01,\n max_n_names: Optional[int] = 2,\n):\n \"\"\"Compute overlaps between groups.\n\n See ``identify_groups`` for identifying the groups.\n\n Parameters\n ----------\n adata\n prediction\n Field name of adata.obs.\n reference\n Field name of adata.obs.\n normalization\n Whether to normalize with respect to the predicted groups or the\n reference groups.\n threshold\n Do not consider associations whose overlap is below this fraction.\n max_n_names\n Control how many reference names you want to be associated with per\n predicted name. Set to `None`, if you want all.\n\n Returns\n -------\n asso_names\n List of associated reference names\n (`max_n_names` for each predicted name).\n asso_matrix\n Matrix where rows correspond to the predicted labels and columns to the\n reference labels, entries are proportional to degree of association.\n \"\"\"\n if normalization not in {'prediction', 'reference'}:\n raise ValueError(\n '`normalization` needs to be either \"prediction\" or \"reference\".'\n )\n sanitize_anndata(adata)\n cats = adata.obs[reference].cat.categories\n for cat in cats:\n if cat in settings.categories_to_ignore:\n logg.info(\n f'Ignoring category {cat!r} '\n 'as it’s in `settings.categories_to_ignore`.'\n )\n asso_names = []\n asso_matrix = []\n for ipred_group, pred_group in enumerate(adata.obs[prediction].cat.categories):\n if '?' in pred_group:\n pred_group = str(ipred_group)\n # starting from numpy version 1.13, subtractions of boolean arrays are deprecated\n mask_pred = adata.obs[prediction].values == pred_group\n mask_pred_int = mask_pred.astype(np.int8)\n asso_matrix += [[]]\n for ref_group in adata.obs[reference].cat.categories:\n mask_ref = (adata.obs[reference].values == ref_group).astype(np.int8)\n mask_ref_or_pred = mask_ref.copy()\n mask_ref_or_pred[mask_pred] = 1\n # e.g. if the pred group is contained in mask_ref, mask_ref and\n # mask_ref_or_pred are the same\n if normalization == 'prediction':\n # compute which fraction of the predicted group is contained in\n # the ref group\n ratio_contained = (\n np.sum(mask_pred_int) - np.sum(mask_ref_or_pred - mask_ref)\n ) / np.sum(mask_pred_int)\n else:\n # compute which fraction of the reference group is contained in\n # the predicted group\n ratio_contained = (\n np.sum(mask_ref) - np.sum(mask_ref_or_pred - mask_pred_int)\n ) / np.sum(mask_ref)\n asso_matrix[-1] += [ratio_contained]\n name_list_pred = [\n cats[i] if cats[i] not in settings.categories_to_ignore else ''\n for i in np.argsort(asso_matrix[-1])[::-1]\n if asso_matrix[-1][i] > threshold\n ]\n asso_names += ['\\n'.join(name_list_pred[:max_n_names])]\n Result = namedtuple(\n 'compute_association_matrix_of_groups', ['asso_names', 'asso_matrix']\n )\n return Result(asso_names=asso_names, asso_matrix=np.array(asso_matrix))\n\n\ndef get_associated_colors_of_groups(reference_colors, asso_matrix):\n return [\n {\n reference_colors[i_ref]: asso_matrix[i_pred, i_ref]\n for i_ref in range(asso_matrix.shape[1])\n }\n for i_pred in range(asso_matrix.shape[0])\n ]\n\n\ndef identify_groups(ref_labels, pred_labels, return_overlaps=False):\n \"\"\"Which predicted label explains which reference label?\n\n A predicted label explains the reference label which maximizes the minimum\n of ``relative_overlaps_pred`` and ``relative_overlaps_ref``.\n\n Compare this with ``compute_association_matrix_of_groups``.\n\n Returns\n -------\n A dictionary of length ``len(np.unique(ref_labels))`` that stores for each\n reference label the predicted label that best explains it.\n\n If ``return_overlaps`` is ``True``, this will in addition return the overlap\n of the reference group with the predicted group; normalized with respect to\n the reference group size and the predicted group size, respectively.\n \"\"\"\n ref_unique, ref_counts = np.unique(ref_labels, return_counts=True)\n ref_dict = dict(zip(ref_unique, ref_counts))\n pred_unique, pred_counts = np.unique(pred_labels, return_counts=True)\n pred_dict = dict(zip(pred_unique, pred_counts))\n associated_predictions = {}\n associated_overlaps = {}\n for ref_label in ref_unique:\n sub_pred_unique, sub_pred_counts = np.unique(\n pred_labels[ref_label == ref_labels], return_counts=True\n )\n relative_overlaps_pred = [\n sub_pred_counts[i] / pred_dict[n] for i, n in enumerate(sub_pred_unique)\n ]\n relative_overlaps_ref = [\n sub_pred_counts[i] / ref_dict[ref_label]\n for i, n in enumerate(sub_pred_unique)\n ]\n relative_overlaps = np.c_[relative_overlaps_pred, relative_overlaps_ref]\n relative_overlaps_min = np.min(relative_overlaps, axis=1)\n pred_best_index = np.argsort(relative_overlaps_min)[::-1]\n associated_predictions[ref_label] = sub_pred_unique[pred_best_index]\n associated_overlaps[ref_label] = relative_overlaps[pred_best_index]\n if return_overlaps:\n return associated_predictions, associated_overlaps\n else:\n return associated_predictions\n\n\n# --------------------------------------------------------------------------------\n# Other stuff\n# --------------------------------------------------------------------------------\n\n\n# backwards compat... remove this in the future\ndef sanitize_anndata(adata):\n \"\"\"Transform string annotations to categoricals.\"\"\"\n adata._sanitize()\n\n\ndef view_to_actual(adata):\n if adata.is_view:\n warnings.warn(\n \"Revieved a view of an AnnData. Making a copy.\",\n stacklevel=2,\n )\n adata._init_as_actual(adata.copy())\n\n\ndef moving_average(a: np.ndarray, n: int):\n \"\"\"Moving average over one-dimensional array.\n\n Parameters\n ----------\n a\n One-dimensional array.\n n\n Number of entries to average over. n=2 means averaging over the currrent\n the previous entry.\n\n Returns\n -------\n An array view storing the moving average.\n \"\"\"\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1 :] / n\n\n\n# --------------------------------------------------------------------------------\n# Deal with tool parameters\n# --------------------------------------------------------------------------------\n\n\ndef update_params(\n old_params: Mapping[str, Any],\n new_params: Mapping[str, Any],\n check=False,\n) -> Dict[str, Any]:\n \"\"\"\\\n Update old_params with new_params.\n\n If check==False, this merely adds and overwrites the content of old_params.\n\n If check==True, this only allows updating of parameters that are already\n present in old_params.\n\n Parameters\n ----------\n old_params\n new_params\n check\n\n Returns\n -------\n updated_params\n \"\"\"\n updated_params = dict(old_params)\n if new_params: # allow for new_params to be None\n for key, val in new_params.items():\n if key not in old_params and check:\n raise ValueError(\n '\\''\n + key\n + '\\' is not a valid parameter key, '\n + 'consider one of \\n'\n + str(list(old_params.keys()))\n )\n if val is not None:\n updated_params[key] = val\n return updated_params\n\n\n# --------------------------------------------------------------------------------\n# Others\n# --------------------------------------------------------------------------------\n\n\ndef check_nonnegative_integers(X: Union[np.ndarray, sparse.spmatrix]):\n \"\"\"Checks values of X to ensure it is count data\"\"\"\n from numbers import Integral\n\n data = X if isinstance(X, np.ndarray) else X.data\n # Check no negatives\n if np.signbit(data).any():\n return False\n # Check all are integers\n elif issubclass(data.dtype.type, Integral):\n return True\n elif np.any(~np.equal(np.mod(data, 1), 0)):\n return False\n else:\n return True\n\n\ndef select_groups(adata, groups_order_subset='all', key='groups'):\n \"\"\"Get subset of groups in adata.obs[key].\"\"\"\n groups_order = adata.obs[key].cat.categories\n if key + '_masks' in adata.uns:\n groups_masks = adata.uns[key + '_masks']\n else:\n groups_masks = np.zeros(\n (len(adata.obs[key].cat.categories), adata.obs[key].values.size), dtype=bool\n )\n for iname, name in enumerate(adata.obs[key].cat.categories):\n # if the name is not found, fallback to index retrieval\n if adata.obs[key].cat.categories[iname] in adata.obs[key].values:\n mask = adata.obs[key].cat.categories[iname] == adata.obs[key].values\n else:\n mask = str(iname) == adata.obs[key].values\n groups_masks[iname] = mask\n groups_ids = list(range(len(groups_order)))\n if groups_order_subset != 'all':\n groups_ids = []\n for name in groups_order_subset:\n groups_ids.append(\n np.where(adata.obs[key].cat.categories.values == name)[0][0]\n )\n if len(groups_ids) == 0:\n # fallback to index retrieval\n groups_ids = np.where(\n np.in1d(\n np.arange(len(adata.obs[key].cat.categories)).astype(str),\n np.array(groups_order_subset),\n )\n )[0]\n if len(groups_ids) == 0:\n logg.debug(\n f'{np.array(groups_order_subset)} invalid! specify valid '\n f'groups_order (or indices) from {adata.obs[key].cat.categories}',\n )\n from sys import exit\n\n exit(0)\n groups_masks = groups_masks[groups_ids]\n groups_order_subset = adata.obs[key].cat.categories[groups_ids].values\n else:\n groups_order_subset = groups_order.values\n return groups_order_subset, groups_masks\n\n\ndef warn_with_traceback(message, category, filename, lineno, file=None, line=None):\n \"\"\"Get full tracebacks when warning is raised by setting\n\n warnings.showwarning = warn_with_traceback\n\n See also\n --------\n http://stackoverflow.com/questions/22373927/get-traceback-of-warnings\n \"\"\"\n import traceback\n\n traceback.print_stack()\n log = file if hasattr(file, 'write') else sys.stderr\n settings.write(warnings.formatwarning(message, category, filename, lineno, line))\n\n\ndef subsample(\n X: np.ndarray,\n subsample: int = 1,\n seed: int = 0,\n) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\\\n Subsample a fraction of 1/subsample samples from the rows of X.\n\n Parameters\n ----------\n X\n Data array.\n subsample\n 1/subsample is the fraction of data sampled, n = X.shape[0]/subsample.\n seed\n Seed for sampling.\n\n Returns\n -------\n Xsampled\n Subsampled X.\n rows\n Indices of rows that are stored in Xsampled.\n \"\"\"\n if subsample == 1 and seed == 0:\n return X, np.arange(X.shape[0], dtype=int)\n if seed == 0:\n # this sequence is defined simply by skipping rows\n # is faster than sampling\n rows = np.arange(0, X.shape[0], subsample, dtype=int)\n n = rows.size\n Xsampled = np.array(X[rows])\n else:\n if seed < 0:\n raise ValueError(f'Invalid seed value < 0: {seed}')\n n = int(X.shape[0] / subsample)\n np.random.seed(seed)\n Xsampled, rows = subsample_n(X, n=n)\n logg.debug(f'... subsampled to {n} of {X.shape[0]} data points')\n return Xsampled, rows\n\n\ndef subsample_n(\n X: np.ndarray, n: int = 0, seed: int = 0\n) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Subsample n samples from rows of array.\n\n Parameters\n ----------\n X\n Data array.\n n\n Sample size.\n seed\n Seed for sampling.\n\n Returns\n -------\n Xsampled\n Subsampled X.\n rows\n Indices of rows that are stored in Xsampled.\n \"\"\"\n if n < 0:\n raise ValueError('n must be greater 0')\n np.random.seed(seed)\n n = X.shape[0] if (n == 0 or n > X.shape[0]) else n\n rows = np.random.choice(X.shape[0], size=n, replace=False)\n Xsampled = X[rows]\n return Xsampled, rows\n\n\ndef check_presence_download(filename: Path, backup_url):\n \"\"\"Check if file is present otherwise download.\"\"\"\n if not filename.is_file():\n from .readwrite import _download\n\n _download(backup_url, filename)\n\n\ndef lazy_import(full_name):\n \"\"\"Imports a module in a way that it’s only executed on member access\"\"\"\n try:\n return sys.modules[full_name]\n except KeyError:\n spec = importlib.util.find_spec(full_name)\n module = importlib.util.module_from_spec(spec)\n loader = importlib.util.LazyLoader(spec.loader)\n # Make module with proper locking and get it inserted into sys.modules.\n loader.exec_module(module)\n return module\n\n\n# --------------------------------------------------------------------------------\n# Neighbors\n# --------------------------------------------------------------------------------\n\n\ndef _fallback_to_uns(dct, conns, dists, conns_key, dists_key):\n if conns is None and conns_key in dct:\n conns = dct[conns_key]\n if dists is None and dists_key in dct:\n dists = dct[dists_key]\n\n return conns, dists\n\n\nclass NeighborsView:\n \"\"\"Convenience class for accessing neighbors graph representations.\n\n Allows to access neighbors distances, connectivities and settings\n dictionary in a uniform manner.\n\n Parameters\n ----------\n\n adata\n AnnData object.\n key\n This defines where to look for neighbors dictionary,\n connectivities, distances.\n\n neigh = NeighborsView(adata, key)\n neigh['distances']\n neigh['connectivities']\n neigh['params']\n 'connectivities' in neigh\n 'params' in neigh\n\n is the same as\n\n adata.obsp[adata.uns[key]['distances_key']]\n adata.obsp[adata.uns[key]['connectivities_key']]\n adata.uns[key]['params']\n adata.uns[key]['connectivities_key'] in adata.obsp\n 'params' in adata.uns[key]\n \"\"\"\n\n def __init__(self, adata, key=None):\n self._connectivities = None\n self._distances = None\n\n if key is None or key == 'neighbors':\n if 'neighbors' not in adata.uns:\n raise KeyError('No \"neighbors\" in .uns')\n self._neighbors_dict = adata.uns['neighbors']\n self._conns_key = 'connectivities'\n self._dists_key = 'distances'\n else:\n if key not in adata.uns:\n raise KeyError(f'No \"{key}\" in .uns')\n self._neighbors_dict = adata.uns[key]\n self._conns_key = self._neighbors_dict['connectivities_key']\n self._dists_key = self._neighbors_dict['distances_key']\n\n if self._conns_key in adata.obsp:\n self._connectivities = adata.obsp[self._conns_key]\n if self._dists_key in adata.obsp:\n self._distances = adata.obsp[self._dists_key]\n\n # fallback to uns\n self._connectivities, self._distances = _fallback_to_uns(\n self._neighbors_dict,\n self._connectivities,\n self._distances,\n self._conns_key,\n self._dists_key,\n )\n\n def __getitem__(self, key):\n if key == 'distances':\n if 'distances' not in self:\n raise KeyError(f'No \"{self._dists_key}\" in .obsp')\n return self._distances\n elif key == 'connectivities':\n if 'connectivities' not in self:\n raise KeyError(f'No \"{self._conns_key}\" in .obsp')\n return self._connectivities\n else:\n return self._neighbors_dict[key]\n\n def __contains__(self, key):\n if key == 'distances':\n return self._distances is not None\n elif key == 'connectivities':\n return self._connectivities is not None\n else:\n return key in self._neighbors_dict\n\n\ndef _choose_graph(adata, obsp, neighbors_key):\n \"\"\"Choose connectivities from neighbbors or another obsp column\"\"\"\n if obsp is not None and neighbors_key is not None:\n raise ValueError(\n 'You can\\'t specify both obsp, neighbors_key. ' 'Please select only one.'\n )\n\n if obsp is not None:\n return adata.obsp[obsp]\n else:\n neighbors = NeighborsView(adata, neighbors_key)\n if 'connectivities' not in neighbors:\n raise ValueError(\n 'You need to run `pp.neighbors` first '\n 'to compute a neighborhood graph.'\n )\n return neighbors['connectivities']\n" ]
[ [ "numpy.signbit", "numpy.random.seed", "numpy.random.choice", "numpy.unique", "numpy.min", "numpy.arange", "numpy.cumsum", "scipy.sparse.csr_matrix", "numpy.mod", "numpy.argsort", "numpy.array", "numpy.where", "numpy.sum" ] ]
[ { "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": [] } ]
garrettkatz/rnn-fxpts
[ "0e4ea0fe89c51764f000610957d0382917fe227c" ]
[ "roundoff.py" ]
[ "\"\"\"\nMethods for assessing treatment of finite-precision issues\n\"\"\"\nimport os\nimport sys\nimport time\nimport multiprocessing as mp\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.markers as mrk\nimport plotter as ptr\nimport rnn_fxpts as rfx\nimport fxpt_experiments as fe\nimport pickle as pkl\n\ndef get_relative_errors(test_data_id):\n \"\"\"\n Compute and save the relative errors of every point found on every network in a testing set.\n Relative error is defined in (Katz and Reggia 2017).\n test_data_id should be as in fxpt_experiments.generate_test_data (without file extension).\n \"\"\"\n network_sizes, num_samples, _ = fe.load_test_data('%s.npz'%test_data_id)\n for alg in ['traverse','baseline']:\n for (N, S) in zip(network_sizes, num_samples):\n for samp in range(S):\n print('%s, alg %s, N %d,samp %d'%(test_data_id,alg,N,samp))\n npz = np.load('results/%s_%s_N_%d_s_%d.npz'%(alg,test_data_id,N,samp))\n W = npz['W']\n fxV = npz['fxV']\n fxV, converged = rfx.refine_fxpts_capped(W, fxV)\n margin = rfx.estimate_forward_error(W, fxV)\n f = np.tanh(W.dot(fxV))-fxV\n re = np.fabs(f/margin)\n re_fx, re_un = re[:,converged].max(axis=0), re[:,~converged].max(axis=0)\n re_fx = re_fx[re_fx > 0]\n f_fx, f_un = np.fabs(f[:,converged]).max(axis=0), np.fabs(f[:,~converged]).max(axis=0)\n f_fx = f_fx[f_fx > 0]\n re_npz = {}\n re_npz['f_fx'] = f_fx\n re_npz['f_un'] = f_un\n re_npz['re_fx'] = re_fx\n re_npz['re_un'] = re_un\n fe.save_npz_file('results/%s_re_%s_N_%d_s_%d.npz'%(alg,test_data_id,N,samp), **re_npz)\n\ndef show_traverse_re_fig(test_data_ids, Ns, samp_range):\n \"\"\"\n Plot relative errors from points found by fiber traversal.\n test_data_ids and Ns should be length-2 lists.\n Subplots in the first column will show errors networks of size Ns[0] from test_data_ids[0].\n Similarly the second column draws from Ns[1], test_data_ids[1].\n Each network sample within samp_range is shown on a separate row.\n \"\"\"\n log = True\n mpl.rcParams['mathtext.default'] = 'regular'\n sp = 1\n for samp in samp_range:\n for (test_data_id,N) in zip(test_data_ids, Ns):\n print('samp %d, N %d'%(samp,N))\n npz = np.load('results/traverse_re_%s_N_%d_s_%d.npz'%(test_data_id,N,samp))\n m_fx, m_un = npz['re_fx'], npz['re_un']\n ax = plt.subplot(len(samp_range),len(Ns),sp)\n sp += 1\n if m_un.shape[0] > 0: plt.hist(np.log2(m_un),bins=30,log=log,facecolor='k')\n plt.hist(np.log2(m_fx),bins=10,log=log,facecolor='w')\n lo = 10*(int(np.log2(m_fx).min()/10)-1)\n if m_un.shape[0] > 0: hi = 10*(int(np.log2(m_un).max()/10)+1)\n else: hi = 0\n plt.xticks(range(-10,1,2),['']+['$2^{%d}$'%yl for yl in range(-8,1,2)])\n if N == Ns[0]:\n plt.ylabel('# of points')\n if samp == samp_range[0]:\n ax.set_title('N = %d'%N)\n if samp == samp_range[-1]:\n plt.xlabel('Fiber Relative Error')\n plt.show()\n\ndef baseline_re_single_analysis(test_data_id, N, samp, cap=10):\n \"\"\"\n Analyze edge cases of relative errors on a single network\n Uses the samp^{th} sample network of size N in test data test_data_id.\n Relative errors in the range (0, 2^{cap}) are considered edge cases.\n Returns the number of edge cases divided by the difference |T-B| - |B-T| as a percent.\n T and B are as defined in (Katz and Reggia 2017).\n \"\"\"\n npz = fe.load_npz_file('results/baseline_re_%s_N_%d_s_%d.npz'%(test_data_id,N,samp))\n res = fe.load_pkl_file('results/TvB_%s_N_%d_s_%d.pkl'%(test_data_id, N, samp))\n re_un = npz['re_un']\n percent = 100.*(re_un < 2**cap).sum()/np.array(res['T-B']-res['B-T'])\n print('N=%d, samp %d: B-T = %d, T-B = %d, %d (%f%%) possibly unique slow RE(B) < 2**%d'%(N, samp, res['B-T'], res['T-B'],(re_un < 2**cap).sum(), percent, cap))\n return percent\n\ndef baseline_re_batch_analysis(test_data_id, Ns, cap=10):\n \"\"\"\n Runs baseline_re_single_analysis on all networks in test_data_id of size N.\n cap is as in baseline_re_single_analysis.\n returns numpy.array percents, where\n percents[i] is as in baseline_re_single_analysis for the i^{th} sample network.\n \"\"\"\n percents = []\n network_sizes, num_samples, _ = fe.load_test_data('%s.npz'%test_data_id)\n for (N, S) in zip(network_sizes, num_samples):\n if N not in Ns: continue\n for samp in range(S):\n percents.append(baseline_re_single_analysis(test_data_id,N,samp,cap=cap))\n percents = np.array(percents)\n print('mean %%: %f%%'%percents.mean())\n\ndef show_baseline_re_fig(test_data_ids, Ns, samp_range):\n \"\"\"\n Plot relative errors from points found by the baseline solver.\n test_data_ids and Ns should be length-2 lists.\n Subplots in the first column will show errors networks of size Ns[0] from test_data_ids[0].\n Similarly the second column draws from Ns[1], test_data_ids[1].\n Each network sample within samp_range is shown on a separate row.\n \"\"\"\n log = True\n mpl.rcParams['mathtext.default'] = 'regular'\n sp = 1\n for samp in samp_range:\n for (test_data_id,N) in zip(test_data_ids, Ns):\n print('samp %d, N %d'%(samp,N))\n npz = np.load('results/baseline_re_%s_N_%d_s_%d.npz'%(test_data_id,N,samp))\n m_fx, m_un = npz['re_fx'], npz['re_un']\n ax = plt.subplot(len(samp_range),len(Ns),sp)\n sp += 1\n if m_un.shape[0] > 0: plt.hist(np.log2(m_un),bins=30,log=log,facecolor='k')\n plt.hist(np.log2(m_fx),bins=10,log=log,facecolor='w')\n lo, hi = -20,50\n plt.xticks(range(lo,hi+1,10),[''] + ['$2^{%d}$'%yl for yl in range(lo+10,hi+1,10)])\n if N == Ns[0]:\n plt.ylabel('# of points')\n if samp == samp_range[0]:\n ax.set_title('N = %d'%N)\n if samp == samp_range[-1]:\n plt.xlabel('Baseline Relative Error')\n baseline_re_single_analysis(test_data_id, N, samp)\n plt.show()\n\ndef get_baseline_rd(test_data_id,N,samp,cap,logfilename=os.devnull):\n \"\"\"\n Compute and save relative distances between pairs of points found by the baseline solver.\n Relative distance is defined in (Katz and Reggia 2017).\n Computes for the samp^{th} sample network of size N in test_data_id.\n test_data_id should be as in fxpt_experiments.generate_test_data (without file extension).\n Only pairs within a random subset of points of size cap are inspected.\n logfilename is a file name at which progress updates are written.\n \"\"\"\n logfile = open(logfilename,'w')\n logfile.write('Running baseline rd (%s,%d,%d)...\\n'%(test_data_id,N,samp))\n npz = fe.load_npz_file('results/baseline_%s_N_%d_s_%d.npz'%(test_data_id,N,samp))\n fxV = npz['fxV_converged']\n fxV_unique = npz['fxV_unique']\n W = npz['W']\n if cap is not None and fxV.shape[1] > cap:\n logfile.write('capping...\\n')\n perm = np.random.permutation(fxV.shape[1])\n fxV = fxV[:,perm[:cap]]\n in_RR, out_RR = [],[]\n for j in range(fxV_unique.shape[1]):\n logfile.write('duping %d of %d...\\n'%(j,fxV_unique.shape[1]))\n dups, RR, R = rfx.identical_fixed_points(W, fxV, fxV_unique[:,[j]])\n in_RR.append(RR[dups])\n out_RR.append(RR[~dups])\n in_RR, out_RR = np.concatenate(in_RR), np.concatenate(out_RR)\n npz[\"in_RR\"], npz[\"out_RR\"] = in_RR, out_RR\n fe.save_npz_file('results/baseline_rd_%s_N_%d_s_%d.npz'%(test_data_id,N,samp), **npz)\n logfile.write('Done.\\n')\n logfile.close()\n print('Done %s %d %d'%(test_data_id,N,samp))\n\ndef pool_get_baseline_rd(args):\n \"\"\"\n Wrapper function passed to multiprocessing.Pool\n \"\"\"\n get_baseline_rd(*args)\n\ndef run_baseline_rd(test_data_id, Ns, num_procs):\n \"\"\"\n Run get_baseline_rd on all networks in test_data_id whose size is in the list Ns.\n Multiprocessing is used to run on multiple networks in parallel.\n num_procs is the number of processors to use.\n \"\"\"\n cpu_count = mp.cpu_count()\n print('%d cpus, using %d'%(cpu_count, num_procs))\n\n pool_args = []\n network_sizes, num_samples, _ = fe.load_test_data('%s.npz'%test_data_id)\n for (N, S) in zip(network_sizes, num_samples):\n if N not in Ns: continue\n cap = 20000\n for s in range(S):\n logfilename = 'logs/baseline_rd_%s_N_%d_s_%d.log'%(test_data_id,N,s)\n pool_args.append((test_data_id,N,s,cap,logfilename))\n start_time = time.time()\n test_fun = pool_get_baseline_rd\n if num_procs < 1: # don't multiprocess\n for args in pool_args: test_fun(args)\n else:\n pool = mp.Pool(processes=num_procs)\n pool.map(test_fun, pool_args)\n pool.close()\n pool.join()\n print('total time: %f'%(time.time()-start_time))\n\ndef get_traverse_rd(test_data_id,N,samp,cap,logfilename=os.devnull):\n \"\"\"\n Compute and save relative distances between pairs of points found by the baseline solver.\n Relative distance is defined in (Katz and Reggia 2017).\n Computes for the samp^{th} sample network of size N in test_data_id.\n test_data_id should be as in fxpt_experiments.generate_test_data (without file extension).\n Only pairs within a random subset of points of size cap are inspected.\n logfilename is a file name at which progress updates are written.\n \"\"\"\n logfile = open(logfilename,'w')\n logfile.write('Running traverse rd (%s,%d,%d)...\\n'%(test_data_id,N,samp))\n npz = fe.load_npz_file('results/traverse_%s_N_%d_s_%d.npz'%(test_data_id,N,samp))\n fxV = npz['fxV_converged']\n fxV_unique = npz['fxV_unique']\n W = npz['W']\n if cap is not None and fxV.shape[1] > cap:\n logfile.write('capping...\\n')\n perm = np.random.permutation(fxV.shape[1])\n fxV = fxV[:,perm[:cap]]\n in_RR, out_RR = [],[]\n for j in range(fxV_unique.shape[1]):\n logfile.write('duping %d of %d...\\n'%(j,fxV_unique.shape[1]))\n dups, RR, R = rfx.identical_fixed_points(W, fxV, fxV_unique[:,[j]])\n in_RR.append(RR[dups])\n out_RR.append(RR[~dups])\n in_RR, out_RR = np.concatenate(in_RR), np.concatenate(out_RR)\n npz[\"in_RR\"], npz[\"out_RR\"] = in_RR, out_RR\n fe.save_npz_file('results/traverse_rd_%s_N_%d_s_%d.npz'%(test_data_id,N,samp), **npz)\n logfile.write('Done.\\n')\n logfile.close()\n print('Done %s %d %d'%(test_data_id,N,samp))\n\ndef pool_get_traverse_rd(args):\n \"\"\"\n Wrapper function passed to multiprocessing.Pool\n \"\"\"\n get_traverse_rd(*args)\n\ndef run_traverse_rd(test_data_id, Ns, num_procs):\n \"\"\"\n Run get_traverse_rd on all networks in test_data_id whose size is in the list Ns.\n Multiprocessing is used to run on multiple networks in parallel.\n num_procs is the number of processors to use.\n \"\"\"\n\n cpu_count = mp.cpu_count()\n print('%d cpus, using %d'%(cpu_count, num_procs))\n\n pool_args = []\n network_sizes, num_samples, _ = fe.load_test_data('%s.npz'%test_data_id)\n for (N,S) in zip(network_sizes, num_samples):\n if N not in Ns: continue\n cap = 20000\n for s in range(S):\n logfilename = 'logs/traverse_rd_%s_N_%d_s_%d.log'%(test_data_id,N,s)\n pool_args.append((test_data_id,N,s,cap,logfilename))\n start_time = time.time()\n test_fun = pool_get_traverse_rd\n if num_procs < 1: # don't multiprocess\n for args in pool_args: test_fun(args)\n else:\n pool = mp.Pool(processes=num_procs)\n pool.map(test_fun, pool_args)\n pool.close()\n pool.join()\n print('total time: %f'%(time.time()-start_time))\n\ndef get_simple_rd(test_data_id,N,samp,cap,logfilename=os.devnull):\n \"\"\"\n Use simple unique test: if max absolute coordinate-wise difference < 2**-32\n Compute and save distances between pairs of points found by both solvers.\n Computes for the samp^{th} sample network of size N in test_data_id.\n test_data_id should be as in fxpt_experiments.generate_test_data (without file extension).\n Only pairs within a random subset of points of size cap are inspected.\n Saves pair-wise distance distribution in histogram with one bucket per integer power of 2\n logfilename is a file name at which progress updates are written.\n \"\"\"\n logfile = open(logfilename,'w')\n rfx.hardwrite(logfile,'Running simple rd (%s,%d,%d)...\\n'%(test_data_id,N,samp))\n buckets = {}\n bins = np.arange(-1025,3)\n for method_key in ['traverse','baseline']:\n npz = fe.load_npz_file('results/%s_%s_N_%d_s_%d.npz'%(method_key,test_data_id,N,samp))\n fxV = npz['fxV_converged']\n buckets[method_key] = np.zeros(len(bins)-1)\n if cap is not None and fxV.shape[1] > cap:\n rfx.hardwrite(logfile,'capping...\\n')\n perm = np.random.permutation(fxV.shape[1])\n fxV = fxV[:,perm[:cap]]\n for j in range(fxV.shape[1]):\n rfx.hardwrite(logfile,'disting %d of %d...\\n'%(j,fxV.shape[1]))\n dists = np.fabs(fxV-fxV[:,[j]]).max(axis=0)\n dists[dists == 0] = 2.0**bins[0]\n logdists = np.log2(dists)\n logdists[logdists < bins[0]] = bins[0]\n logdists[logdists > bins[-1]] = bins[-1]\n hist,_ = np.histogram(logdists,bins=bins)\n buckets[method_key] += hist\n npz = {'bins':bins,'traverse_buckets':buckets['traverse'],'baseline_buckets':buckets['baseline']} \n fe.save_npz_file('results/simple_rd_%s_N_%d_s_%d.npz'%(test_data_id,N,samp), **npz)\n rfx.hardwrite(logfile,'Done.\\n')\n logfile.close()\n print('Done %s %d %d'%(test_data_id,N,samp))\n\ndef pool_get_simple_rd(args):\n \"\"\"\n Wrapper function passed to multiprocessing.Pool\n \"\"\"\n get_simple_rd(*args)\n\ndef run_simple_rd(test_data_id, Ns, num_procs):\n \"\"\"\n Run get_simple_rd on all networks in test_data_id whose size is in the list Ns.\n Multiprocessing is used to run on multiple networks in parallel.\n num_procs is the number of processors to use.\n \"\"\"\n\n cpu_count = mp.cpu_count()\n print('%d cpus, using %d'%(cpu_count, num_procs))\n\n pool_args = []\n network_sizes, num_samples, _ = fe.load_test_data('%s.npz'%test_data_id)\n for (N,S) in zip(network_sizes, num_samples):\n if N not in Ns: continue\n cap = 1000\n for s in range(S):\n logfilename = 'logs/simple_rd_%s_N_%d_s_%d.log'%(test_data_id,N,s)\n pool_args.append((test_data_id,N,s,cap,logfilename))\n start_time = time.time()\n test_fun = pool_get_simple_rd\n if num_procs < 1: # don't multiprocess\n for args in pool_args: test_fun(args)\n else:\n pool = mp.Pool(processes=num_procs)\n pool.map(test_fun, pool_args)\n pool.close()\n pool.join()\n print('total time: %f'%(time.time()-start_time))\n\ndef show_traverse_rd_fig(test_data_ids, Ns, samp_range):\n \"\"\"\n Plot relative distances from points found by fiber traversal.\n test_ids, Ns, and samp_range should be as in show_traverse_re_fig.\n \"\"\"\n log = True\n mpl.rcParams['mathtext.default'] = 'regular'\n sp = 1\n for samp in samp_range:\n for (test_data_id,N) in zip(test_data_ids, Ns):\n print('samp %d, N %d'%(samp,N))\n npz = np.load('results/traverse_rd_%s_N_%d_s_%d.npz'%(test_data_id,N,samp))\n in_rr, out_rr = npz['in_RR'], npz['out_RR']\n if (in_rr > 0).any(): in_rr[in_rr == 0] = in_rr[in_rr > 0].min()\n else: in_rr[in_rr == 0] = 2**(-30)\n ax = plt.subplot(len(samp_range),len(Ns),sp)\n sp += 1\n if out_rr.shape[0] > 0: plt.hist(np.log2(out_rr),bins=30,log=log,facecolor='k')\n plt.hist(np.log2(in_rr),bins=10,log=log,facecolor='w')\n if N == Ns[0]:\n plt.ylabel('# of pairs')\n if samp == samp_range[0]:\n ax.set_title('N = %d'%N)\n if samp == samp_range[-1]:\n plt.xlabel('Fiber Relative Distance')\n plt.xlim([-30,50])\n plt.xticks(range(-30,51,10),['']+['$2^{%d}$'%xl for xl in range(-20,51,10)])\n plt.show()\n\ndef show_baseline_rd_fig(test_data_ids, Ns, samp_range):\n \"\"\"\n Plot relative distances from points found by the baseline solver.\n test_ids, Ns, and samp_range should be as in show_baseline_re_fig.\n \"\"\"\n log = True\n mpl.rcParams['mathtext.default'] = 'regular'\n sp = 1\n for samp in samp_range:\n for (test_data_id,N) in zip(test_data_ids, Ns):\n print('samp %d, N %d'%(samp,N))\n npz = np.load('results/baseline_rd_%s_N_%d_s_%d.npz'%(test_data_id,N,samp))\n in_rr, out_rr = npz['in_RR'], npz['out_RR']\n if (in_rr > 0).any(): in_rr[in_rr == 0] = in_rr[in_rr > 0].min()\n else: in_rr[in_rr == 0] = 2**(-30)\n ax = plt.subplot(len(samp_range),len(Ns),sp)\n sp += 1\n if np.isinf(out_rr).any():\n if np.isinf(out_rr).all(): out_rr[:] = 4*in_rr.max()\n else: out_rr[np.isinf(out_rr)] = 4*out_rr[~np.isinf(out_rr)].max()\n print('out_rr:')\n print(out_rr.shape)\n print((out_rr==0).sum())\n print(np.isinf(in_rr).sum())\n print(np.isinf(out_rr).sum())\n print(np.isnan(out_rr).sum())\n if out_rr.shape[0] > 0: plt.hist(np.log2(out_rr),bins=30,log=log,facecolor='k')\n # if out_rr.shape[0] > 0: plt.hist(out_rr,bins=30,facecolor='k')\n plt.hist(np.log2(in_rr),bins=10,log=log,facecolor='w')\n # plt.hist(in_rr,bins=10,facecolor='w')\n if N == Ns[0]:\n plt.ylabel('# of pairs')\n if samp == samp_range[0]:\n ax.set_title('N = %d'%N)\n if samp == samp_range[-1]:\n plt.xlabel('Baseline Relative Distance')\n plt.xlim([-30,50])\n plt.xticks(range(-30,51,10),['']+['$2^{%d}$'%xl for xl in range(-20,51,10)])\n plt.show()\n\ndef show_simple_rd_all_fig(test_data_ids, Ns, samp_range):\n \"\"\"\n Plot relative distances from points found by fiber traversal or baseline.\n test_ids, Ns, and samp_range should be as in show_traverse_re_fig.\n \"\"\"\n log = True\n mpl.rcParams['mathtext.default'] = 'regular'\n mpl.rcParams['pdf.fonttype'] = 42\n mpl.rcParams['ps.fonttype'] = 42\n buckets = None\n bins = None\n for samp in samp_range:\n for (test_data_id,N) in zip(test_data_ids, Ns):\n print('samp %d, N %d'%(samp,N))\n npz = np.load('results/simple_rd_%s_N_%d_s_%d.npz'%(test_data_id,N,samp))\n if buckets is None:\n buckets = np.zeros(npz['traverse_buckets'].shape)\n bins = npz['bins']\n buckets += npz['traverse_buckets']\n buckets += npz['baseline_buckets']\n plt.figure(figsize=(8,2.4))\n # plt.hist(buckets,bins=bins,log=log)\n if log:\n buckets[buckets > 0] = np.log2(buckets[buckets > 0])\n plt.bar(left=bins[:-1],height=buckets,width=bins[1:]-bins[:-1],facecolor='none')\n plt.ylabel('# of pairs')\n plt.xlabel('$max_i|v_i^{(1)}-v_i^{(2)}|$') #'Max Coordinate-wise Distance')\n xmin_idx = int(((bins[:-1] > -1000) & (buckets > 0)).argmax())\n xstep = int(np.ceil((bins[-1]-bins[xmin_idx])/10))\n plt.xticks(bins[xmin_idx::xstep],['$2^{%d}$'%xl for xl in bins[xmin_idx::xstep]])\n plt.xlim([bins[xmin_idx]-xstep,bins[-1]+xstep])\n if log:\n ymax = np.ceil(buckets.max())+1\n ystep = np.ceil(ymax/5)\n plt.yticks(np.arange(0,ymax+ystep,ystep),['$2^{%d}$'%yl for yl in np.arange(0,ymax+ystep,ystep)])\n plt.ylim([0,ymax+1])\n plt.tight_layout()\n plt.show()\n" ]
[ [ "numpy.concatenate", "numpy.histogram", "matplotlib.pyplot.tight_layout", "numpy.arange", "numpy.ceil", "numpy.load", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.isnan", "matplotlib.pyplot.ylim", "numpy.array", "matplotlib.pyplot.show", "matplotlib.pyplot.ylabel", "numpy.log2", "matplotlib.pyplot.xlim", "numpy.random.permutation", "matplotlib.pyplot.bar", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks", "numpy.isinf", "numpy.fabs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hishizuka/pyqtgraph
[ "4820625d93ffb41f324431d0d29b395cf91f339e", "4820625d93ffb41f324431d0d29b395cf91f339e", "4820625d93ffb41f324431d0d29b395cf91f339e" ]
[ "examples/Legend.py", "examples/GLshaders.py", "tests/image_testing.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nDemonstrates basic use of LegendItem\n\n\"\"\"\nimport initExample ## Add path to library (just for examples; you do not need this)\n\nimport pyqtgraph as pg\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport numpy as np\n\nwin = pg.plot()\nwin.setWindowTitle('pyqtgraph example: BarGraphItem')\n\n# # option1: only for .plot(), following c1,c2 for example-----------------------\n# win.addLegend(frame=False, colCount=2)\n\n# bar graph\nx = np.arange(10)\ny = np.sin(x+2) * 3\nbg1 = pg.BarGraphItem(x=x, height=y, width=0.3, brush='b', pen='w', name='bar')\nwin.addItem(bg1)\n\n# curve\nc1 = win.plot([np.random.randint(0,8) for i in range(10)], pen='r', symbol='t', symbolPen='r', symbolBrush='g', name='curve1')\nc2 = win.plot([2,1,4,3,1,3,2,4,3,2], pen='g', fillLevel=0, fillBrush=(255,255,255,30), name='curve2')\n\n# scatter plot\ns1 = pg.ScatterPlotItem(size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120), name='scatter')\nspots = [{'pos': [i, np.random.randint(-3, 3)], 'data': 1} for i in range(10)]\ns1.addPoints(spots)\nwin.addItem(s1)\n\n# # option2: generic method------------------------------------------------\nlegend = pg.LegendItem((80,60), offset=(70,20))\nlegend.setParentItem(win.graphicsItem())\nlegend.addItem(bg1, 'bar')\nlegend.addItem(c1, 'curve1')\nlegend.addItem(c2, 'curve2')\nlegend.addItem(s1, 'scatter')\n\nif __name__ == '__main__':\n pg.exec()\n", "# -*- coding: utf-8 -*-\n\"\"\"\nDemonstration of some of the shader programs included with pyqtgraph that can be \nused to affect the appearance of a surface.\n\"\"\"\n\n\n\n## Add path to library (just for examples; you do not need this)\nimport initExample\n\nimport numpy as np\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport pyqtgraph as pg\nimport pyqtgraph.opengl as gl\n\napp = pg.mkQApp(\"GLShaders Example\")\nw = gl.GLViewWidget()\nw.show()\nw.setWindowTitle('pyqtgraph example: GL Shaders')\nw.setCameraPosition(distance=15, azimuth=-90)\n\ng = gl.GLGridItem()\ng.scale(2,2,1)\nw.addItem(g)\n\nmd = gl.MeshData.sphere(rows=10, cols=20)\nx = np.linspace(-8, 8, 6)\n\nm1 = gl.GLMeshItem(meshdata=md, smooth=True, color=(1, 0, 0, 0.2), shader='balloon', glOptions='additive')\nm1.translate(x[0], 0, 0)\nm1.scale(1, 1, 2)\nw.addItem(m1)\n\nm2 = gl.GLMeshItem(meshdata=md, smooth=True, shader='normalColor', glOptions='opaque')\nm2.translate(x[1], 0, 0)\nm2.scale(1, 1, 2)\nw.addItem(m2)\n\nm3 = gl.GLMeshItem(meshdata=md, smooth=True, shader='viewNormalColor', glOptions='opaque')\nm3.translate(x[2], 0, 0)\nm3.scale(1, 1, 2)\nw.addItem(m3)\n\nm4 = gl.GLMeshItem(meshdata=md, smooth=True, shader='shaded', glOptions='opaque')\nm4.translate(x[3], 0, 0)\nm4.scale(1, 1, 2)\nw.addItem(m4)\n\nm5 = gl.GLMeshItem(meshdata=md, smooth=True, color=(1, 0, 0, 1), shader='edgeHilight', glOptions='opaque')\nm5.translate(x[4], 0, 0)\nm5.scale(1, 1, 2)\nw.addItem(m5)\n\nm6 = gl.GLMeshItem(meshdata=md, smooth=True, color=(1, 0, 0, 1), shader='heightColor', glOptions='opaque')\nm6.translate(x[5], 0, 0)\nm6.scale(1, 1, 2)\nw.addItem(m6)\n\n\n\n\n#def psi(i, j, k, offset=(25, 25, 50)):\n #x = i-offset[0]\n #y = j-offset[1]\n #z = k-offset[2]\n #th = np.arctan2(z, (x**2+y**2)**0.5)\n #phi = np.arctan2(y, x)\n #r = (x**2 + y**2 + z **2)**0.5\n #a0 = 1\n ##ps = (1./81.) * (2./np.pi)**0.5 * (1./a0)**(3/2) * (6 - r/a0) * (r/a0) * np.exp(-r/(3*a0)) * np.cos(th)\n #ps = (1./81.) * 1./(6.*np.pi)**0.5 * (1./a0)**(3/2) * (r/a0)**2 * np.exp(-r/(3*a0)) * (3 * np.cos(th)**2 - 1)\n \n #return ps\n \n ##return ((1./81.) * (1./np.pi)**0.5 * (1./a0)**(3/2) * (r/a0)**2 * (r/a0) * np.exp(-r/(3*a0)) * np.sin(th) * np.cos(th) * np.exp(2 * 1j * phi))**2 \n\n\n#print(\"Generating scalar field..\")\n#data = np.abs(np.fromfunction(psi, (50,50,100)))\n\n\n##data = np.fromfunction(lambda i,j,k: np.sin(0.2*((i-25)**2+(j-15)**2+k**2)**0.5), (50,50,50)); \n#print(\"Generating isosurface..\")\n#verts = pg.isosurface(data, data.max()/4.)\n\n#md = gl.MeshData.MeshData(vertexes=verts)\n\n#colors = np.ones((md.vertexes(indexed='faces').shape[0], 4), dtype=float)\n#colors[:,3] = 0.3\n#colors[:,2] = np.linspace(0, 1, colors.shape[0])\n#m1 = gl.GLMeshItem(meshdata=md, color=colors, smooth=False)\n\n#w.addItem(m1)\n#m1.translate(-25, -25, -20)\n\n#m2 = gl.GLMeshItem(vertexes=verts, color=colors, smooth=True)\n\n#w.addItem(m2)\n#m2.translate(-25, -25, -50)\n \nif __name__ == '__main__':\n pg.exec()\n", "# Image-based testing borrowed from vispy\n\n\"\"\"\nProcedure for unit-testing with images:\n\n Run individual test scripts with the PYQTGRAPH_AUDIT environment variable set:\n\n $ PYQTGRAPH_AUDIT=1 python pyqtgraph/graphicsItems/tests/test_PlotCurveItem.py\n\n Any failing tests will display the test results, standard image, and the\n differences between the two. If the test result is bad, then press (f)ail.\n If the test result is good, then press (p)ass and the new image will be\n saved to the test-data directory.\n\n To check all test results regardless of whether the test failed, set the\n environment variable PYQTGRAPH_AUDIT_ALL=1.\n\"\"\"\n\nimport time\nimport os\nimport sys\nimport inspect\nimport warnings\nimport numpy as np\n\nfrom pathlib import Path\n\nfrom pyqtgraph.Qt import QtGui, QtCore\nfrom pyqtgraph import functions as fn\nfrom pyqtgraph import GraphicsLayoutWidget\nfrom pyqtgraph import ImageItem, TextItem\n\n\ntester = None\n\n# Convenient stamp used for ensuring image orientation is correct\naxisImg = [\n \" 1 1 1 \",\n \" 1 1 1 1 1 1 \",\n \" 1 1 1 1 1 1 1 1 1 1\",\n \" 1 1 1 1 1 \",\n \" 1 1 1 1 1 1 \",\n \" 1 1 \",\n \" 1 1 \",\n \" 1 \",\n \" \",\n \" 1 \",\n \" 1 \",\n \" 1 \",\n \"1 1 1 1 1 \",\n \"1 1 1 1 1 \",\n \" 1 1 1 \",\n \" 1 1 1 \",\n \" 1 \",\n \" 1 \",\n]\naxisImg = np.array([map(int, row[::2].replace(' ', '0')) for row in axisImg])\n\n\n\ndef getTester():\n global tester\n if tester is None:\n tester = ImageTester()\n return tester\n\n\ndef getImageFromWidget(widget):\n\n # just to be sure the widget size is correct (new window may be resized):\n QtGui.QApplication.processEvents()\n\n qimg = QtGui.QImage(widget.size(), QtGui.QImage.Format.Format_ARGB32)\n qimg.fill(QtCore.Qt.GlobalColor.transparent)\n painter = QtGui.QPainter(qimg)\n widget.render(painter)\n painter.end()\n\n qimg = qimg.convertToFormat(QtGui.QImage.Format.Format_RGBA8888)\n return fn.ndarray_from_qimage(qimg).copy()\n\n\ndef assertImageApproved(image, standardFile, message=None, **kwargs):\n \"\"\"Check that an image test result matches a pre-approved standard.\n\n If the result does not match, then the user can optionally invoke a GUI\n to compare the images and decide whether to fail the test or save the new\n image as the standard.\n\n Run the test with the environment variable PYQTGRAPH_AUDIT=1 to bring up\n the auditing GUI.\n\n Parameters\n ----------\n image : (h, w, 4) ndarray\n standardFile : str\n The name of the approved test image to check against. This file name\n is relative to the root of the pyqtgraph test-data repository and will\n be automatically fetched.\n message : str\n A string description of the image. It is recommended to describe\n specific features that an auditor should look for when deciding whether\n to fail a test.\n\n Extra keyword arguments are used to set the thresholds for automatic image\n comparison (see ``assertImageMatch()``).\n \"\"\"\n if isinstance(image, QtGui.QWidget):\n # just to be sure the widget size is correct (new window may be resized):\n QtGui.QApplication.processEvents()\n\n graphstate = scenegraphState(image, standardFile)\n image = getImageFromWidget(image)\n\n if message is None:\n code = inspect.currentframe().f_back.f_code\n message = \"%s::%s\" % (code.co_filename, code.co_name)\n\n # Make sure we have a test data repo available\n dataPath = getTestDataDirectory()\n\n # Read the standard image if it exists\n stdFileName = os.path.join(dataPath, standardFile + '.png')\n if not os.path.isfile(stdFileName):\n stdImage = None\n else:\n qimg = QtGui.QImage(stdFileName)\n qimg = qimg.convertToFormat(QtGui.QImage.Format.Format_RGBA8888)\n stdImage = fn.ndarray_from_qimage(qimg).copy()\n del qimg\n\n # If the test image does not match, then we go to audit if requested.\n try:\n if stdImage is None:\n raise Exception(\"No reference image saved for this test.\")\n if image.shape[2] != stdImage.shape[2]:\n raise Exception(\"Test result has different channel count than standard image\"\n \"(%d vs %d)\" % (image.shape[2], stdImage.shape[2]))\n if image.shape != stdImage.shape:\n # Allow im1 to be an integer multiple larger than im2 to account\n # for high-resolution displays\n ims1 = np.array(image.shape).astype(float)\n ims2 = np.array(stdImage.shape).astype(float)\n sr = ims1 / ims2 if ims1[0] > ims2[0] else ims2 / ims1\n if (sr[0] != sr[1] or not np.allclose(sr, np.round(sr)) or\n sr[0] < 1):\n raise TypeError(\"Test result shape %s is not an integer factor\"\n \" different than standard image shape %s.\" %\n (ims1, ims2))\n sr = np.round(sr).astype(int)\n image = fn.downsample(image, sr[0], axis=(0, 1)).astype(image.dtype)\n\n assertImageMatch(image, stdImage, **kwargs)\n\n if bool(os.getenv('PYQTGRAPH_PRINT_TEST_STATE', False)):\n print(graphstate)\n\n if os.getenv('PYQTGRAPH_AUDIT_ALL') == '1':\n raise Exception(\"Image test passed, but auditing due to PYQTGRAPH_AUDIT_ALL evnironment variable.\")\n except Exception:\n if os.getenv('PYQTGRAPH_AUDIT') == '1' or os.getenv('PYQTGRAPH_AUDIT_ALL') == '1':\n sys.excepthook(*sys.exc_info())\n getTester().test(image, stdImage, message)\n stdPath = os.path.dirname(stdFileName)\n print('Saving new standard image to \"%s\"' % stdFileName)\n if not os.path.isdir(stdPath):\n os.makedirs(stdPath)\n qimg = fn.ndarray_to_qimage(image, QtGui.QImage.Format.Format_RGBA8888)\n qimg.save(stdFileName)\n del qimg\n else:\n if stdImage is None:\n raise Exception(\"Test standard %s does not exist. Set \"\n \"PYQTGRAPH_AUDIT=1 to add this image.\" % stdFileName)\n if os.getenv('CI') is not None:\n standardFile = os.path.join(os.getenv(\"SCREENSHOT_DIR\", \"screenshots\"), standardFile)\n saveFailedTest(image, stdImage, standardFile)\n print(graphstate)\n raise\n\n\ndef assertImageMatch(im1, im2, minCorr=None, pxThreshold=50.,\n pxCount=-1, maxPxDiff=None, avgPxDiff=None,\n imgDiff=None):\n \"\"\"Check that two images match.\n\n Images that differ in shape or dtype will fail unconditionally.\n Further tests for similarity depend on the arguments supplied.\n\n By default, images may have no pixels that gave a value difference greater\n than 50.\n\n Parameters\n ----------\n im1 : (h, w, 4) ndarray\n Test output image\n im2 : (h, w, 4) ndarray\n Test standard image\n minCorr : float or None\n Minimum allowed correlation coefficient between corresponding image\n values (see numpy.corrcoef)\n pxThreshold : float\n Minimum value difference at which two pixels are considered different\n pxCount : int or None\n Maximum number of pixels that may differ. Default is 0, on Windows some\n tests have a value of 2.\n maxPxDiff : float or None\n Maximum allowed difference between pixels\n avgPxDiff : float or None\n Average allowed difference between pixels\n imgDiff : float or None\n Maximum allowed summed difference between images\n\n \"\"\"\n assert im1.ndim == 3\n assert im1.shape[2] == 4\n assert im1.dtype == im2.dtype\n\n if pxCount == -1:\n pxCount = 0\n \n diff = im1.astype(float) - im2.astype(float)\n if imgDiff is not None:\n assert np.abs(diff).sum() <= imgDiff\n\n pxdiff = diff.max(axis=2) # largest value difference per pixel\n mask = np.abs(pxdiff) >= pxThreshold\n if pxCount is not None:\n assert mask.sum() <= pxCount\n\n maskedDiff = diff[mask]\n if maxPxDiff is not None and maskedDiff.size > 0:\n assert maskedDiff.max() <= maxPxDiff\n if avgPxDiff is not None and maskedDiff.size > 0:\n assert maskedDiff.mean() <= avgPxDiff\n\n if minCorr is not None:\n with np.errstate(invalid='ignore'):\n corr = np.corrcoef(im1.ravel(), im2.ravel())[0, 1]\n assert corr >= minCorr\n\n\ndef saveFailedTest(data, expect, filename):\n # concatenate data, expect, and diff into a single image\n ds = data.shape\n es = expect.shape\n\n shape = (max(ds[0], es[0]) + 4, ds[1] + es[1] + 8 + max(ds[1], es[1]), 4)\n img = np.empty(shape, dtype=np.ubyte)\n img[..., :3] = 100\n img[..., 3] = 255\n\n img[2:2+ds[0], 2:2+ds[1], :ds[2]] = data\n img[2:2+es[0], ds[1]+4:ds[1]+4+es[1], :es[2]] = expect\n\n diff = makeDiffImage(data, expect)\n img[2:2+diff.shape[0], -diff.shape[1]-2:-2] = diff\n\n png = makePng(data) # change `img` to `data` to save just the failed image\n directory = os.path.dirname(filename)\n if not os.path.isdir(directory):\n os.makedirs(directory)\n with open(filename + \".png\", \"wb\") as png_file:\n png_file.write(png)\n print(\"\\nImage comparison failed. Test result: %s %s Expected result: \"\n \"%s %s\" % (data.shape, data.dtype, expect.shape, expect.dtype))\n\n\ndef makePng(img):\n \"\"\"Given an array like (H, W, 4), return a PNG-encoded byte string.\n \"\"\"\n io = QtCore.QBuffer()\n qim = fn.ndarray_to_qimage(img, QtGui.QImage.Format.Format_RGBX8888)\n qim.save(io, 'PNG')\n return bytes(io.data().data())\n\n\ndef makeDiffImage(im1, im2):\n \"\"\"Return image array showing the differences between im1 and im2.\n\n Handles images of different shape. Alpha channels are not compared.\n \"\"\"\n ds = im1.shape\n es = im2.shape\n\n diff = np.empty((max(ds[0], es[0]), max(ds[1], es[1]), 4), dtype=int)\n diff[..., :3] = 128\n diff[..., 3] = 255\n diff[:ds[0], :ds[1], :min(ds[2], 3)] += im1[..., :3]\n diff[:es[0], :es[1], :min(es[2], 3)] -= im2[..., :3]\n diff = np.clip(diff, 0, 255).astype(np.ubyte)\n return diff\n\n\nclass ImageTester(QtGui.QWidget):\n \"\"\"Graphical interface for auditing image comparison tests.\n \"\"\"\n def __init__(self):\n self.lastKey = None\n \n QtGui.QWidget.__init__(self)\n self.resize(1200, 800)\n #self.showFullScreen()\n \n self.layout = QtGui.QGridLayout()\n self.setLayout(self.layout)\n \n self.view = GraphicsLayoutWidget()\n self.layout.addWidget(self.view, 0, 0, 1, 2)\n\n self.label = QtGui.QLabel()\n self.layout.addWidget(self.label, 1, 0, 1, 2)\n self.label.setWordWrap(True)\n font = QtGui.QFont(\"monospace\", 14, QtGui.QFont.Weight.Bold)\n self.label.setFont(font)\n\n self.passBtn = QtGui.QPushButton('Pass')\n self.failBtn = QtGui.QPushButton('Fail')\n self.layout.addWidget(self.passBtn, 2, 0)\n self.layout.addWidget(self.failBtn, 2, 1)\n self.passBtn.clicked.connect(self.passTest)\n self.failBtn.clicked.connect(self.failTest)\n\n self.views = (self.view.addViewBox(row=0, col=0),\n self.view.addViewBox(row=0, col=1),\n self.view.addViewBox(row=0, col=2))\n labelText = ['test output', 'standard', 'diff']\n for i, v in enumerate(self.views):\n v.setAspectLocked(1)\n v.invertY()\n v.image = ImageItem(axisOrder='row-major')\n v.image.setAutoDownsample(True)\n v.addItem(v.image)\n v.label = TextItem(labelText[i])\n v.setBackgroundColor(0.5)\n\n self.views[1].setXLink(self.views[0])\n self.views[1].setYLink(self.views[0])\n self.views[2].setXLink(self.views[0])\n self.views[2].setYLink(self.views[0])\n\n def test(self, im1, im2, message):\n \"\"\"Ask the user to decide whether an image test passes or fails.\n \n This method displays the test image, reference image, and the difference\n between the two. It then blocks until the user selects the test output\n by clicking a pass/fail button or typing p/f. If the user fails the test,\n then an exception is raised.\n \"\"\"\n self.show()\n if im2 is None:\n message += '\\nImage1: %s %s Image2: [no standard]' % (im1.shape, im1.dtype)\n im2 = np.zeros((1, 1, 3), dtype=np.ubyte)\n else:\n message += '\\nImage1: %s %s Image2: %s %s' % (im1.shape, im1.dtype, im2.shape, im2.dtype)\n self.label.setText(message)\n \n self.views[0].image.setImage(im1)\n self.views[1].image.setImage(im2)\n diff = makeDiffImage(im1, im2)\n\n self.views[2].image.setImage(diff)\n self.views[0].autoRange()\n\n while True:\n QtGui.QApplication.processEvents()\n lastKey = self.lastKey\n \n self.lastKey = None\n if lastKey in ('f', 'esc') or not self.isVisible():\n raise Exception(\"User rejected test result.\")\n elif lastKey == 'p':\n break\n time.sleep(0.03)\n\n for v in self.views:\n v.image.setImage(np.zeros((1, 1, 3), dtype=np.ubyte))\n\n def keyPressEvent(self, event):\n if event.key() == QtCore.Qt.Key.Key_Escape:\n self.lastKey = 'esc'\n else:\n self.lastKey = str(event.text()).lower()\n\n def passTest(self):\n self.lastKey = 'p'\n\n def failTest(self):\n self.lastKey = 'f'\n\n\ndef getTestDataRepo():\n warnings.warn(\n \"Test data data repo has been merged with the main repo\"\n \"use getTestDataDirectory() instead, this method will be removed\"\n \"in a future version of pyqtgraph\",\n DeprecationWarning, stacklevel=2\n )\n return getTestDataDirectory()\n\n\ndef getTestDataDirectory():\n dataPath = Path(__file__).absolute().parent / \"images\"\n return dataPath.as_posix()\n\n\ndef scenegraphState(view, name):\n \"\"\"Return information about the scenegraph for debugging test failures.\n \"\"\"\n state = \"====== Scenegraph state for %s ======\\n\" % name\n state += \"view size: %dx%d\\n\" % (view.width(), view.height())\n state += \"view transform:\\n\" + indent(transformStr(view.transform()), \" \")\n for item in view.scene().items():\n if item.parentItem() is None:\n state += itemState(item) + '\\n'\n return state\n\n \ndef itemState(root):\n state = str(root) + '\\n'\n from pyqtgraph import ViewBox\n state += 'bounding rect: ' + str(root.boundingRect()) + '\\n'\n if isinstance(root, ViewBox):\n state += \"view range: \" + str(root.viewRange()) + '\\n'\n state += \"transform:\\n\" + indent(transformStr(root.transform()).strip(), \" \") + '\\n'\n for item in root.childItems():\n state += indent(itemState(item).strip(), \" \") + '\\n'\n return state\n\n \ndef transformStr(t):\n return (\"[%0.2f %0.2f %0.2f]\\n\"*3) % (t.m11(), t.m12(), t.m13(), t.m21(), t.m22(), t.m23(), t.m31(), t.m32(), t.m33())\n\n\ndef indent(s, pfx):\n return '\\n'.join(pfx+line for line in s.split('\\n'))\n\n\nclass TransposedImageItem(ImageItem):\n # used for testing image axis order; we can test row-major and col-major using\n # the same test images\n def __init__(self, *args, **kwds):\n self.__transpose = kwds.pop('transpose', False)\n ImageItem.__init__(self, *args, **kwds)\n def setImage(self, image=None, **kwds):\n if image is not None and self.__transpose is True:\n image = np.swapaxes(image, 0, 1)\n return ImageItem.setImage(self, image, **kwds)\n" ]
[ [ "numpy.arange", "numpy.random.randint", "numpy.sin" ], [ "numpy.linspace" ], [ "numpy.swapaxes", "numpy.abs", "numpy.clip", "numpy.round", "numpy.errstate", "numpy.array", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ajkerr0/kappa
[ "7a74582596f96b6a9a1488df5a4777c7b723c919" ]
[ "kappa/lattice/ammonia.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: alex\n\"\"\"\n\nimport numpy as np\n\ndef main():\n \"\"\"Main program execution.\"\"\"\n \n n,h1,h2,h3 = generate_ammonia_sites()\n nList = [[1,2,3],[0],[0],[0]]\n \n return [n,h1,h2,h3], nList\n \ndef generate_ammonia_sites():\n \"\"\"Generate the locations for the atoms in the ammonia molecule\"\"\"\n \n x,y = np.array([1.,0.,0.]), np.array([0.,1.,0.])\n \n #atomic distance (angstroms)\n a = 1.40\n \n n = np.array([0.,0.,0.])\n \n h1 = n + a*y\n h2 = n - a*y/2. + a*x*(np.sqrt(3)/2)\n h3 = h2 - a*x*np.sqrt(3)\n \n return n,h1,h2,h3\n \n \n \n " ]
[ [ "numpy.array", "numpy.sqrt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
eamorgado/Car-Self-driving-Simulator
[ "498d54a30c665b38ae6e120d8ae8311e77ad61f2" ]
[ "CarlaDriving/server/lane_detection/utils.py" ]
[ "import numpy as np\nimport cv2 as cv\nimport math\nfrom server.cv_utils import * \n\ndef filterGaussian(img,size=(5,5),stdv=0):\n \"\"\"Summary of filterGaussian\n This will apply a noise reduction filter, we will use s 5x5 Gaussian filter to smooth\n the image to lower the sensitivity to noise. (The smaller the size the less visible the blur)\n\n To populate the Gaussian matrix we will use a kernel of normally distributed[stdv=1] numbers which will\n set each pixel value equal to the weighted average of its neighboor pixels\n\n The Gaussian distribution:\n Gd = (1/2pi*stdv^2)exp(-((i-(k+1)^2) + (j - (k+1)^2))/(2*stdv^2))\n\n i,j E [1,2k+1] for the kernel of size: (2k+1)x(2k+1) \n \"\"\"\n\n if not isCV(img):\n raise ValueError(\"Image not in np.array format\")\n\n if not isinstance(size,tuple):\n raise ValueError('filterGaussian: Size for Gaussian filter not tuple')\n return cv.GaussianBlur(img,size,stdv)\n\n\ndef filterCanny(img,min_val=50,max_val=150,size=(5,5),stdv=0):\n \"\"\"\n The Canny detector is a multi-stage algorithm optimized for fast real-time edge detection, \n which will reduce complexity of the image much further.\n\n The algorithm will detect sharp changes in luminosity and will define them as edges.\n\n The algorithm has the following stages:\n - Noise reduction\n - Intensity gradient - here it will apply a Sobel filter along the x and y axis to detect if edges are horizontal vertical or diagonal\n - Non-maximum suppression - this shortens the frequency bandwith of the signal to sharpen it\n - Hysteresis thresholding\n \"\"\"\n if not isCV(img):\n raise ValueError(\"Image not in np.array format\")\n \n if min_val >= max_val:\n raise ValueError('filterCanny: Value order incorrect')\n \n gray_scale = toGrayScale(img)\n #cv.imshow('Gray Scale image',gray_scale)\n\n gaussian = filterGaussian(gray_scale,size=size,stdv=stdv)\n #cv.imshow('Gaussian filter',gaussian)\n return cv.Canny(gaussian,min_val,max_val)\n\n\ndef segmentRegionOfInterest(img):\n height = img.shape[0]\n\n polygons = np.array([ \n [(200, height), (1100, height), (550, 250)] \n ]) \n mask = np.zeros_like(img) \n\n # Fill poly-function deals with multiple polygon \n cv.fillPoly(mask, polygons, 255)\n\n # Bitwise operation between canny image and mask image \n masked_image = cv.bitwise_and(img, mask) \n return masked_image \n\n\ndef houghFilter(frame,distance_resolution=2,angle_resolution=np.pi/180,min_n_intersections=50,min_line_size=30,max_line_gap=5):\n \"\"\"\n Params:\n frame\n distance_resolution: distance resolution of accumulator in pixels, larger ==> less precision\n angle_resolution: angle of accumulator in radians, larger ==> less precision\n min_n_intersections: minimum number of intersections\n min_line_size: minimum length of line in pixels\n max_line_gap: maximum distance in pixels between disconnected lines\n \"\"\"\n placeholder = np.array([])\n hough = cv.HoughLinesP(frame,distance_resolution,angle_resolution,min_n_intersections,placeholder,min_line_size,max_line_gap)\n return hough\n\n\ndef calculateLines(img,lines):\n \"\"\"\n Combines line segments into one or two lanes\n Note: By looking at the slop of a line we can see if it is on the left side (m<0) or right (m>0)\n \"\"\"\n def calculateCoordinates(img,line_params):\n \"\"\"\n Calculates the coordinates for a road lane\n \"\"\"\n #y = m*x +b, m= slope, b=intercept\n height, width, _ = img.shape\n m, b = line_params \n y1 = height\n y2 = int(y1 * (1/2)) # make points from middle of the frame down\n \n # bound the coordinates within the frame\n x1 = max(-width, min(2 * width, int((y1 - b) / m)))\n x2 = max(-width, min(2 * width, int((y2 - b) / m)))\n\n return np.array([x1,y1, x2,y2])\n\n lane_lines = []\n if lines is None:\n return np.array(lane_lines)\n \n height, width, _ = img.shape\n left_lines, right_lines = [], []\n\n boundary = 1/3\n left_region_boundary = width * (1 - boundary) # left lane line segment should be on left 2/3 of the screen\n right_region_boundary = width * boundary # right lane line segment should be on left 2/3 of the screen\n\n\n for line in lines:\n x1,y1, x2,y2 = line.reshape(4)\n\n if x1 == x2:\n #Vertical line\n continue\n\n #Fit a polynomial to the points to get the slope and intercept\n line_params = np.polyfit((x1,x2), (y1,y2), 1)\n slope,intercept = line_params[0], line_params[1]\n\n if slope < 0: #left side\n if x1 < left_region_boundary and x2 < left_region_boundary:\n left_lines.append((slope,intercept))\n else: #right\n if x1 > right_region_boundary and x2 > right_region_boundary:\n right_lines.append((slope,intercept))\n\n left_lines_avg = np.average(left_lines,axis=0)\n right_lines_avg = np.average(right_lines,axis=0)\n\n if len(left_lines) > 0:\n left_line = calculateCoordinates(img,left_lines_avg)\n lane_lines.append(left_line)\n \n if len(right_lines) > 0:\n right_line = calculateCoordinates(img,right_lines_avg)\n lane_lines.append(right_line)\n\n return np.array(lane_lines)\n\n\ndef showMidLine(img,steering_angle,color=(0, 255, 0),thickness=5):\n line_image = np.zeros_like(img)\n height, width, _ = img.shape\n\n # Note: the steering angle of:\n # 0-89 degree: turn left\n # 90 degree: going straight\n # 91-180 degree: turn right \n\n steering_angle_radian = steering_angle / 180.0 * math.pi\n x1 = int(width / 2)\n y1 = height\n x2 = int(x1 - height / 2 / math.tan(steering_angle_radian))\n y2 = int(height / 2)\n\n cv.line(line_image, (x1, y1), (x2, y2), color, thickness)\n\n return line_image\n\n\ndef showLines(img,lines,color=(255,0,0),thickness=5):\n line_img = np.zeros(img.shape, dtype=np.uint8)\n if lines is not None:\n for x1, y1, x2, y2 in lines:\n cv.line(line_img, (x1,y1), (x2,y2), color, thickness)\n return line_img\n \n\ndef calculateSteeringAngle(img,lines):\n if len(lines) == 0:\n return -90\n \n height, width, _ = img.shape\n if len(lines) == 1:\n x1, _, x2, _ = lines[0]\n x_offset = x2 - x1\n else: #2 lines\n _, _, left_x2, _ = lines[0]\n _, _, right_x2, _ = lines[1]\n camera_mid_offset_percent = 0.0 # 0.0 means car pointing to center, -0.03: car is centered to left, +0.03 means car pointing to right\n mid = int(width / 2 * (1 + camera_mid_offset_percent))\n x_offset = (left_x2 + right_x2) / 2 - mid\n\n # find the steering angle, which is angle between navigation direction to end of center line\n y_offset = int(height / 2)\n\n angle_to_mid_radian = math.atan(x_offset / y_offset) # angle (in radian) to center vertical line\n angle_to_mid_deg = int(angle_to_mid_radian * 180.0 / math.pi) # angle (in degrees) to center vertical line\n steering_angle = angle_to_mid_deg + 90 # this is the steering angle needed by picar front wheel\n\n return steering_angle\n\n\ndef stabilizeSteeringAngle(curr_steering_angle, new_steering_angle, num_of_lane_lines, max_angle_deviation_two_lines=2, max_angle_deviation_one_lane=1):\n \"\"\"\n Using last steering angle to stabilize the steering angle\n This can be improved to use last N angles, etc\n if new angle is too different from current angle, only turn by max_angle_deviation degrees\n \"\"\"\n\n if num_of_lane_lines == 1:\n # if only one lane detected, don't deviate too much\n max_angle_deviation = max_angle_deviation_one_lane\n else:\n # if both lane lines detected, then we can deviate more\n max_angle_deviation = max_angle_deviation_two_lines\n \n angle_deviation = new_steering_angle - curr_steering_angle\n if abs(angle_deviation) > max_angle_deviation:\n stabilized_steering_angle = int(curr_steering_angle\n + max_angle_deviation * angle_deviation / abs(angle_deviation))\n else:\n stabilized_steering_angle = new_steering_angle\n\n return stabilized_steering_angle\n\n\n" ]
[ [ "numpy.polyfit", "numpy.zeros_like", "numpy.average", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rovo98/model-unkown-dfa-diagnosis-based-on-running-logs
[ "f80c838dea6a8313165fbf10d64d5dc935cc036c" ]
[ "models/fdconv1d_lstm/train.py" ]
[ "# author rovo98\n\nimport os\n\nimport tensorflow as tf\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.callbacks import EarlyStopping\n\nfrom model_data_input import load_processed_dataset\nfrom models.fdconv1d_lstm.model import build_fdconv1d_lstm\nfrom models.utils.misc import running_timer\nfrom models.utils.misc import plot_training_history\n\n# filter warning logs of tf\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n# enable memory growth for every GPU.\n# Using GPU devices to train the models is recommended.\n# uncomment the following several lines of code to disable forcing using GPU.\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\nassert len(physical_devices) > 0, 'Not enough GPU hardware available'\nfor gpu in physical_devices:\n tf.config.experimental.set_memory_growth(gpu, True)\n\n\n# noinspection DuplicatedCode\n@running_timer\ndef train_model(epochs=10,\n batch_size=32,\n training_verbose=1,\n print_model_summary=False,\n using_validation=False,\n validation_split=0.2,\n plot_history_data=False,\n history_fig_name='default',\n plot_model_arch=False,\n plot_model_name='default',\n save_model=False,\n save_model_name='default'):\n # num_of_faulty_type = 3\n # train_x, train_y, test_x, test_y = load_processed_dataset(\n # '2020-02-22 20:34:10_czE4OmZzNDphczE2OmZlczI=_processed_logs_rnn', num_of_faulty_type,\n # location='../../dataset', for_rnn=True)\n #\n # num_of_faulty_type = 5\n # train_x, train_y, test_x, test_y = load_processed_dataset(\n # '2019-12-28 00:46:37_czc1OmZzNzphczE1OmZlczQ=_processed_logs', num_of_faulty_type,\n # location='../../dataset')\n\n # 1. single faulty mode(small state size): short logs (10 - 50)\n num_of_faulty_type = 3\n train_x, train_y, test_x, test_y = load_processed_dataset(\n '2020-03-17 15:55:22_czE4OmZzNDphczE2OmZlczI=_processed_logs', num_of_faulty_type,\n location='../../dataset')\n # 2. single faulty mode(small state size): long logs (60 - 100)\n # num_of_faulty_type = 3\n # train_x, train_y, test_x, test_y = load_processed_dataset(\n # '2020-03-17 16:00:22_czE4OmZzNDphczE2OmZlczI=_processed_logs_b', num_of_faulty_type,\n # location='../../dataset')\n\n # 3. single faulty mode(big state size): short logs (10 - 50)\n # num_of_faulty_type = 5\n # train_x, train_y, test_x, test_y = load_processed_dataset(\n # '2020-03-17 16:16:04_czgwOmZzODphczE4OmZlczQ=_processed_logs', num_of_faulty_type,\n # location='../../dataset')\n # 4. single faulty mode(big state size): long logs (60 - 100)\n # num_of_faulty_type = 5\n # train_x, train_y, test_x, test_y = load_processed_dataset(\n # '2020-03-19 17:09:05_czgwOmZzODphczE4OmZlczQ=_processed_logs_b_rg', num_of_faulty_type,\n # location='../../dataset')\n\n # 5. multi faulty mode (small state size): short logs\n # num_of_faulty_type = 4\n # train_x, train_y, test_x, test_y = load_processed_dataset(\n # '2020-03-17 16:34:50_czE3OmZzNDphczE0OmZlczI=_processed_logs', num_of_faulty_type,\n # location='../../dataset')\n\n # 6. multi faulty mode (small state size): long logs\n # num_of_faulty_type = 4\n # train_x, train_y, test_x, test_y = load_processed_dataset(\n # '2020-03-17 16:36:40_czE3OmZzNDphczE0OmZlczI=_processed_logs_b', num_of_faulty_type,\n # location='../../dataset')\n\n # 7. multi faulty mode (big state size): short logs\n # num_of_faulty_type = 16\n # train_x, train_y, test_x, test_y = load_processed_dataset(\n # '2020-03-17 16:40:03_czgwOmZzODphczIwOmZlczQ=_processed_logs', num_of_faulty_type,\n # location='../../dataset')\n # 8. multi faulty mode (big state size): long logs\n # num_of_faulty_type = 16\n # train_x, train_y, test_x, test_y = load_processed_dataset(\n # '2020-03-17 16:41:29_czgwOmZzODphczIwOmZlczQ=_processed_logs_b', num_of_faulty_type,\n # location='../../dataset')\n\n n_timesteps, n_features = train_x.shape[1], train_x.shape[2]\n\n # building the model.\n model = build_fdconv1d_lstm((n_timesteps, n_features), num_of_faulty_type, kernel_size=31)\n\n # print out the model summary\n if print_model_summary:\n model.summary()\n\n # plot and save the model architecture.\n if plot_model_arch:\n plot_model(model, to_file=plot_model_name, show_shapes=True)\n\n # fit network\n if plot_history_data:\n history = model.fit(x=[train_x, train_x], y=train_y, epochs=epochs, batch_size=batch_size,\n verbose=training_verbose, validation_split=validation_split)\n plot_training_history(history, 'fdconv1d-lstm', history_fig_name, '../exper_imgs')\n elif using_validation:\n es = EarlyStopping('val_categorical_accuracy', 1e-4, 3, 1, 'max')\n history = model.fit(x=[train_x, train_x], y=train_y, epochs=epochs, batch_size=batch_size,\n verbose=training_verbose, validation_split=validation_split, callbacks=[es])\n plot_training_history(history, 'fdconv1d-lstm', history_fig_name, '../exper_imgs')\n else:\n model.fit(x=[train_x, train_x], y=train_y, epochs=epochs, batch_size=batch_size, verbose=training_verbose)\n\n _, accuracy = model.evaluate(x=[test_x, test_x], y=test_y, batch_size=batch_size, verbose=0)\n\n # saving the model\n if save_model:\n model.save(save_model_name)\n print('>>> model saved: {}'.format(save_model_name))\n\n print('\\n>>> Accuracy on testing given testing dataset: {}'.format(accuracy * 100))\n\n\n# Driver the program to test the methods above.\nif __name__ == '__main__':\n train_model(50,\n print_model_summary=True,\n using_validation=True,\n history_fig_name='fdConv1d-lstm_czE4OmZzNDphczE2OmZlczI=_small.png',\n save_model=True,\n save_model_name='../trained_saved/fdConv1d-lstm_czE4OmZzNDphczE2OmZlczI=_small.h5')\n" ]
[ [ "tensorflow.config.experimental.list_physical_devices", "tensorflow.keras.utils.plot_model", "tensorflow.keras.callbacks.EarlyStopping", "tensorflow.config.experimental.set_memory_growth" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
trsvchn/Ax
[ "0b430641c6b33920757dd09ae4318ea487fb4136", "0b430641c6b33920757dd09ae4318ea487fb4136", "0b430641c6b33920757dd09ae4318ea487fb4136" ]
[ "ax/models/tests/test_torch_model_utils.py", "ax/core/generator_run.py", "ax/models/torch/botorch_modular/utils.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport numpy as np\nimport torch\nfrom ax.exceptions.model import ModelError\nfrom ax.models.torch.utils import (\n _generate_sobol_points,\n is_noiseless,\n normalize_indices,\n subset_model,\n tensor_callable_to_array_callable,\n)\nfrom ax.utils.common.testutils import TestCase\nfrom botorch.models import HeteroskedasticSingleTaskGP, ModelListGP, SingleTaskGP\nfrom torch import Tensor\n\n\nclass TorchUtilsTest(TestCase):\n def test_is_noiseless(self):\n x = torch.zeros(1, 1)\n y = torch.zeros(1, 1)\n se = torch.zeros(1, 1)\n model = SingleTaskGP(x, y)\n self.assertTrue(is_noiseless(model))\n model = HeteroskedasticSingleTaskGP(x, y, se)\n self.assertFalse(is_noiseless(model))\n with self.assertRaises(ModelError):\n is_noiseless(ModelListGP())\n\n def testNormalizeIndices(self):\n indices = [0, 2]\n nlzd_indices = normalize_indices(indices, 3)\n self.assertEqual(nlzd_indices, indices)\n nlzd_indices = normalize_indices(indices, 4)\n self.assertEqual(nlzd_indices, indices)\n indices = [0, -1]\n nlzd_indices = normalize_indices(indices, 3)\n self.assertEqual(nlzd_indices, [0, 2])\n with self.assertRaises(ValueError):\n nlzd_indices = normalize_indices([3], 3)\n with self.assertRaises(ValueError):\n nlzd_indices = normalize_indices([-4], 3)\n\n def testSubsetModel(self):\n x = torch.zeros(1, 1)\n y = torch.rand(1, 2)\n obj_t = torch.rand(2)\n model = SingleTaskGP(x, y)\n self.assertEqual(model.num_outputs, 2)\n # basic test, can subset\n obj_weights = torch.tensor([1.0, 0.0])\n subset_model_results = subset_model(model, obj_weights)\n model_sub = subset_model_results.model\n obj_weights_sub = subset_model_results.objective_weights\n ocs_sub = subset_model_results.outcome_constraints\n obj_t_sub = subset_model_results.objective_thresholds\n self.assertIsNone(ocs_sub)\n self.assertIsNone(obj_t_sub)\n self.assertEqual(model_sub.num_outputs, 1)\n self.assertTrue(torch.equal(obj_weights_sub, torch.tensor([1.0])))\n # basic test, cannot subset\n obj_weights = torch.tensor([1.0, 2.0])\n subset_model_results = subset_model(model, obj_weights)\n model_sub = subset_model_results.model\n obj_weights_sub = subset_model_results.objective_weights\n ocs_sub = subset_model_results.outcome_constraints\n obj_t_sub = subset_model_results.objective_thresholds\n self.assertIsNone(ocs_sub)\n self.assertIsNone(obj_t_sub)\n self.assertIs(model_sub, model) # check identity\n self.assertIs(obj_weights_sub, obj_weights) # check identity\n self.assertTrue(torch.equal(subset_model_results.indices, torch.tensor([0, 1])))\n # test w/ outcome constraints, can subset\n obj_weights = torch.tensor([1.0, 0.0])\n ocs = (torch.tensor([[1.0, 0.0]]), torch.tensor([1.0]))\n subset_model_results = subset_model(model, obj_weights, ocs)\n model_sub = subset_model_results.model\n obj_weights_sub = subset_model_results.objective_weights\n ocs_sub = subset_model_results.outcome_constraints\n obj_t_sub = subset_model_results.objective_thresholds\n self.assertEqual(model_sub.num_outputs, 1)\n self.assertIsNone(obj_t_sub)\n self.assertTrue(torch.equal(obj_weights_sub, torch.tensor([1.0])))\n self.assertTrue(torch.equal(ocs_sub[0], torch.tensor([[1.0]])))\n self.assertTrue(torch.equal(ocs_sub[1], torch.tensor([1.0])))\n self.assertTrue(torch.equal(subset_model_results.indices, torch.tensor([0])))\n # test w/ outcome constraints, cannot subset\n obj_weights = torch.tensor([1.0, 0.0])\n ocs = (torch.tensor([[0.0, 1.0]]), torch.tensor([1.0]))\n subset_model_results = subset_model(model, obj_weights, ocs)\n model_sub = subset_model_results.model\n obj_weights_sub = subset_model_results.objective_weights\n ocs_sub = subset_model_results.outcome_constraints\n obj_t_sub = subset_model_results.objective_thresholds\n self.assertIs(model_sub, model) # check identity\n self.assertIsNone(obj_t_sub)\n self.assertIs(obj_weights_sub, obj_weights) # check identity\n self.assertIs(ocs_sub, ocs) # check identity\n self.assertTrue(torch.equal(subset_model_results.indices, torch.tensor([0, 1])))\n # test w/ objective thresholds, cannot subset\n obj_weights = torch.tensor([1.0, 0.0])\n ocs = (torch.tensor([[0.0, 1.0]]), torch.tensor([1.0]))\n subset_model_results = subset_model(model, obj_weights, ocs, obj_t)\n model_sub = subset_model_results.model\n obj_weights_sub = subset_model_results.objective_weights\n ocs_sub = subset_model_results.outcome_constraints\n obj_t_sub = subset_model_results.objective_thresholds\n self.assertIs(model_sub, model) # check identity\n self.assertIs(obj_t, obj_t_sub)\n self.assertIs(obj_weights_sub, obj_weights) # check identity\n self.assertTrue(torch.equal(subset_model_results.indices, torch.tensor([0, 1])))\n self.assertIs(ocs_sub, ocs) # check identity\n # test w/ objective thresholds, can subset\n obj_weights = torch.tensor([1.0, 0.0])\n ocs = (torch.tensor([[1.0, 0.0]]), torch.tensor([1.0]))\n subset_model_results = subset_model(model, obj_weights, ocs, obj_t)\n model_sub = subset_model_results.model\n obj_weights_sub = subset_model_results.objective_weights\n ocs_sub = subset_model_results.outcome_constraints\n obj_t_sub = subset_model_results.objective_thresholds\n self.assertTrue(torch.equal(subset_model_results.indices, torch.tensor([0])))\n self.assertEqual(model_sub.num_outputs, 1)\n self.assertTrue(torch.equal(obj_weights_sub, torch.tensor([1.0])))\n self.assertTrue(torch.equal(obj_t_sub, obj_t[:1]))\n self.assertTrue(torch.equal(ocs_sub[0], torch.tensor([[1.0]])))\n self.assertTrue(torch.equal(ocs_sub[1], torch.tensor([1.0])))\n # test unsupported\n yvar = torch.ones(1, 2)\n model = HeteroskedasticSingleTaskGP(x, y, yvar)\n subset_model_results = subset_model(model, obj_weights)\n model_sub = subset_model_results.model\n obj_weights_sub = subset_model_results.objective_weights\n ocs_sub = subset_model_results.outcome_constraints\n obj_t_sub = subset_model_results.objective_thresholds\n self.assertIsNone(ocs_sub)\n self.assertIs(model_sub, model) # check identity\n self.assertIs(obj_weights_sub, obj_weights) # check identity\n self.assertTrue(torch.equal(subset_model_results.indices, torch.tensor([0, 1])))\n # test error on size inconsistency\n obj_weights = torch.ones(3)\n with self.assertRaises(RuntimeError):\n subset_model(model, obj_weights)\n\n def testGenerateSobolPoints(self):\n bounds = [(0.0, 1.0) for _ in range(3)]\n linear_constraints = (\n torch.tensor([[1, -1, 0]], dtype=torch.double),\n torch.tensor([[0]], dtype=torch.double),\n )\n\n def test_rounding_func(x: Tensor) -> Tensor:\n return x\n\n gen_sobol = _generate_sobol_points(\n n_sobol=100,\n bounds=bounds,\n device=torch.device(\"cpu\"),\n linear_constraints=linear_constraints,\n rounding_func=test_rounding_func,\n )\n self.assertEqual(len(gen_sobol), 100)\n self.assertIsInstance(gen_sobol, Tensor)\n\n def testTensorCallableToArrayCallable(self):\n def tensor_func(x: Tensor) -> Tensor:\n return np.exp(x)\n\n new_func = tensor_callable_to_array_callable(\n tensor_func=tensor_func, device=torch.device(\"cpu\")\n )\n self.assertTrue(callable(new_func))\n self.assertIsInstance(new_func(np.array([1.0, 2.0])), np.ndarray)\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom __future__ import annotations\n\nimport copy\nfrom collections import OrderedDict\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom enum import Enum\nfrom typing import Any, Dict, List, MutableMapping, Optional, Set, Tuple\n\nimport pandas as pd\nfrom ax.core.arm import Arm\nfrom ax.core.optimization_config import OptimizationConfig\nfrom ax.core.search_space import SearchSpace\nfrom ax.core.types import (\n TCandidateMetadata,\n TGenMetadata,\n TModelPredict,\n TModelPredictArm,\n)\nfrom ax.utils.common.base import Base, SortableBase\nfrom ax.utils.common.typeutils import not_none\n\n\nclass GeneratorRunType(Enum):\n \"\"\"Class for enumerating generator run types.\"\"\"\n\n STATUS_QUO = 0\n MANUAL = 1\n\n\n@dataclass\nclass ArmWeight(Base):\n \"\"\"NamedTuple for tying together arms and weights.\"\"\"\n\n arm: Arm\n weight: float\n\n\ndef extract_arm_predictions(\n model_predictions: TModelPredict, arm_idx: int\n) -> TModelPredictArm:\n \"\"\"Extract a particular arm from model_predictions.\n\n Args:\n model_predictions: Mean and Cov for all arms.\n arm_idx: Index of arm in prediction list.\n\n Returns:\n (mean, cov) for specified arm.\n \"\"\"\n\n means = model_predictions[0]\n covariances = model_predictions[1]\n means_per_arm = {metric: means[metric][arm_idx] for metric in means.keys()}\n covar_per_arm = {\n metric: {\n other_metric: covariances[metric][other_metric][arm_idx]\n for other_metric in covariances[metric].keys()\n }\n for metric in covariances.keys()\n }\n return (means_per_arm, covar_per_arm)\n\n\nclass GeneratorRun(SortableBase):\n \"\"\"An object that represents a single run of a generator.\n\n This object is created each time the ``gen`` method of a generator is\n called. It stores the arms and (optionally) weights that were\n generated by the run. When we add a generator run to a trial, its\n arms and weights will be merged with those from previous generator\n runs that were already attached to the trial.\n \"\"\"\n\n def __init__(\n self,\n arms: List[Arm],\n weights: Optional[List[float]] = None,\n optimization_config: Optional[OptimizationConfig] = None,\n search_space: Optional[SearchSpace] = None,\n model_predictions: Optional[TModelPredict] = None,\n best_arm_predictions: Optional[Tuple[Arm, Optional[TModelPredictArm]]] = None,\n type: Optional[str] = None,\n fit_time: Optional[float] = None,\n gen_time: Optional[float] = None,\n model_key: Optional[str] = None,\n model_kwargs: Optional[Dict[str, Any]] = None,\n bridge_kwargs: Optional[Dict[str, Any]] = None,\n gen_metadata: Optional[TGenMetadata] = None,\n model_state_after_gen: Optional[Dict[str, Any]] = None,\n generation_step_index: Optional[int] = None,\n candidate_metadata_by_arm_signature: Optional[\n Dict[str, TCandidateMetadata]\n ] = None,\n ) -> None:\n \"\"\"\n Inits GeneratorRun.\n\n Args:\n arms: The list of arms generated by this run.\n weights: An optional list of weights to associate with the arms.\n optimization_config: The optimization config used during generation\n of this run.\n search_space: The search used during generation of this run.\n model_predictions: Means and covariances for the arms in this\n run recorded at the time the run was executed.\n best_arm_predictions: Optional tuple of best arm in this run\n (according to the optimization config) and its optional respective\n model predictions.\n type: Optional type of the run.\n fit_time: Optional number of seconds it took to fit the model that produced\n this generator run. For models with multiple invocations of gen, this is\n typically the fitting time since the last call to gen.\n gen_time: Optional number of seconds generation took.\n model_key: Optional name of the model that was used to produce this\n generator run.\n model_kwargs: Optional dictionary of keyword arguments to the model\n that was used to produce this generator run.\n bridge_kwargs: Optional dictionary of keyword arguments to the model\n bridge that was used to produce this generator run.\n gen_metadata: Optional dictionary of metadata generated by alongside\n the generator_run.\n model_state_after_gen: Optional dictionary of model state attributes\n to those attributes' values, to use when reinstantiating the model\n from the generator run. Note that this is the state of the model\n after generation, so these settings should only be applied to the\n model when reinstantiating it to continue generation from it,\n rather than to reproduce the conditions, in which this generator\n run was created.\n generation_step_index: Optional index of the generation step that produced\n this generator run. Applicable only if the genetator run was created\n via a generation strategy.\n candidate_metadata_by_arm_signature: Optional dictionary of arm signatures\n to model-produced candidate metadata that corresponds to that arm in\n this generator run.\n \"\"\"\n self._arm_weight_table: OrderedDict[str, ArmWeight] = OrderedDict()\n if weights is None:\n weights = [1.0 for i in range(len(arms))]\n if len(arms) != len(weights):\n raise ValueError(\"Weights and arms must have the same length.\")\n if bridge_kwargs is not None or model_kwargs is not None:\n if model_key is None:\n raise ValueError(\n \"Model key is required if model or bridge kwargs are provided.\"\n )\n if bridge_kwargs is None or model_kwargs is None:\n raise ValueError(\n \"Both model kwargs and bridge kwargs are required if either \"\n \"one is provided.\"\n )\n for arm, weight in zip(arms, weights):\n existing_cw = self._arm_weight_table.get(arm.signature)\n if existing_cw:\n self._arm_weight_table[arm.signature] = ArmWeight(\n arm=arm, weight=existing_cw.weight + weight\n )\n else:\n self._arm_weight_table[arm.signature] = ArmWeight(\n arm=arm, weight=weight\n )\n\n self._generator_run_type: Optional[str] = type\n self._time_created: datetime = datetime.now()\n self._optimization_config = optimization_config\n self._search_space = search_space\n self._model_predictions = model_predictions\n self._best_arm_predictions = best_arm_predictions\n self._index: Optional[int] = None\n self._fit_time = fit_time\n self._gen_time = gen_time\n self._model_key = model_key\n self._model_kwargs = model_kwargs\n self._bridge_kwargs = bridge_kwargs\n self._gen_metadata = gen_metadata\n self._model_state_after_gen = model_state_after_gen\n # If candidate metadata is not None and not empty, check that all arm\n # signatures in it correspond to arms in this generator run.\n if candidate_metadata_by_arm_signature:\n unknown_arms_in_cand_metadata = (\n set(candidate_metadata_by_arm_signature.keys()) - self.arm_signatures\n )\n if unknown_arms_in_cand_metadata:\n raise ValueError(\n f\"Arms with signatures {unknown_arms_in_cand_metadata} appear in \"\n \"candidate metadata, but not among the arms on this GeneratorRun.\"\n )\n self._candidate_metadata_by_arm_signature = candidate_metadata_by_arm_signature\n\n # Validate that generation step index is non-negative.\n assert generation_step_index is None or generation_step_index >= 0\n self._generation_step_index = generation_step_index\n\n @property\n def arms(self) -> List[Arm]:\n \"\"\"Returns arms generated by this run.\"\"\"\n return [cw.arm for cw in self._arm_weight_table.values()]\n\n @property\n def arm_signatures(self) -> Set[str]:\n \"\"\"Returns signatures of arms generated by this run.\"\"\"\n return {cw.arm.signature for cw in self._arm_weight_table.values()}\n\n @property\n def weights(self) -> List[float]:\n \"\"\"Returns weights associated with arms generated by this run.\"\"\"\n return [cw.weight for cw in self._arm_weight_table.values()]\n\n @property\n def arm_weights(self) -> MutableMapping[Arm, float]:\n \"\"\"Mapping from arms to weights (order matches order in\n `arms` property).\n \"\"\"\n return OrderedDict(zip(self.arms, self.weights))\n\n @property\n def generator_run_type(self) -> Optional[str]:\n \"\"\"The type of the generator run.\"\"\"\n return self._generator_run_type\n\n @property\n def time_created(self) -> datetime:\n \"\"\"Creation time of the batch.\"\"\"\n return self._time_created\n\n @property\n def index(self) -> Optional[int]:\n \"\"\"The index of this generator run within a trial's list of generator run structs.\n This field is set when the generator run is added to a trial.\n \"\"\"\n return self._index\n\n @index.setter\n def index(self, index: int) -> None:\n if self._index is not None and self._index != index:\n raise ValueError(\"Cannot change the index of a generator run once set.\")\n self._index = index\n\n @property\n def optimization_config(self) -> Optional[OptimizationConfig]:\n \"\"\"The optimization config used during generation of this run.\"\"\"\n return self._optimization_config\n\n @property\n def search_space(self) -> Optional[SearchSpace]:\n \"\"\"The search used during generation of this run.\"\"\"\n return self._search_space\n\n @property\n def model_predictions(self) -> Optional[TModelPredict]:\n return self._model_predictions\n\n @property\n def fit_time(self) -> Optional[float]:\n return self._fit_time\n\n @property\n def gen_time(self) -> Optional[float]:\n return self._gen_time\n\n @property\n def model_predictions_by_arm(self) -> Optional[Dict[str, TModelPredictArm]]:\n if self._model_predictions is None:\n return None\n\n predictions: Dict[str, TModelPredictArm] = {}\n for idx, cond in enumerate(self.arms):\n predictions[cond.signature] = extract_arm_predictions(\n model_predictions=not_none(self._model_predictions), arm_idx=idx\n )\n return predictions\n\n @property\n def best_arm_predictions(self) -> Optional[Tuple[Arm, Optional[TModelPredictArm]]]:\n return self._best_arm_predictions\n\n @property\n def gen_metadata(self) -> Optional[TGenMetadata]:\n \"\"\"Returns metadata generated by this run.\"\"\"\n return self._gen_metadata\n\n @property\n def candidate_metadata_by_arm_signature(\n self,\n ) -> Optional[Dict[str, TCandidateMetadata]]:\n \"\"\"Retrieves model-produced candidate metadata as a mapping from arm name (for\n the arm the candidate became when added to experiment) to the metadata dict.\n \"\"\"\n return self._candidate_metadata_by_arm_signature\n\n @property\n def param_df(self) -> pd.DataFrame:\n \"\"\"\n Constructs a Pandas dataframe with the parameter values for each arm.\n\n Useful for inspecting the contents of a generator run.\n\n Returns:\n pd.DataFrame: a dataframe with the generator run's arms.\n \"\"\"\n return pd.DataFrame.from_dict(\n {a.name_or_short_signature: a.parameters for a in self.arms}, orient=\"index\"\n )\n\n def clone(self) -> GeneratorRun:\n \"\"\"Return a deep copy of a GeneratorRun.\"\"\"\n cand_metadata = self.candidate_metadata_by_arm_signature\n generator_run = GeneratorRun(\n arms=[a.clone() for a in self.arms],\n weights=self.weights[:] if self.weights is not None else None,\n optimization_config=self.optimization_config.clone()\n if self.optimization_config is not None\n else None,\n search_space=self.search_space.clone()\n if self.search_space is not None\n else None,\n model_predictions=copy.deepcopy(self.model_predictions),\n best_arm_predictions=copy.deepcopy(self.best_arm_predictions),\n type=self.generator_run_type,\n fit_time=self.fit_time,\n gen_time=self.gen_time,\n model_key=self._model_key,\n model_kwargs=self._model_kwargs,\n bridge_kwargs=self._bridge_kwargs,\n gen_metadata=self._gen_metadata,\n model_state_after_gen=self._model_state_after_gen,\n generation_step_index=self._generation_step_index,\n candidate_metadata_by_arm_signature=cand_metadata,\n )\n generator_run._time_created = self._time_created\n generator_run._index = self._index\n generator_run._model_key = self._model_key\n generator_run._model_kwargs = (\n self._model_kwargs.copy() if self._model_kwargs is not None else None\n )\n generator_run._bridge_kwargs = (\n self._bridge_kwargs.copy() if self._bridge_kwargs is not None else None\n )\n generator_run._model_state_after_gen = (\n self._model_state_after_gen.copy()\n if self._model_state_after_gen is not None\n else None\n )\n return generator_run\n\n def __repr__(self) -> str:\n class_name = self.__class__.__name__\n num_arms = len(self.arms)\n total_weight = sum(self.weights)\n return f\"{class_name}({num_arms} arms, total weight {total_weight})\"\n\n @property\n def _unique_id(self) -> str:\n if self.index is not None:\n return str(self.index)\n elif self._generation_step_index is not None:\n return str(self._generation_step_index)\n else:\n raise ValueError(\n \"GeneratorRuns only have a unique id if attached \"\n \"to a Trial or GenerationStrategy.\"\n )\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom typing import List, Dict, Optional, Tuple, Type\n\nimport torch\nfrom ax.core.search_space import SearchSpaceDigest\nfrom ax.core.types import TConfig\nfrom ax.utils.common.constants import Keys\nfrom ax.utils.common.logger import get_logger\nfrom ax.utils.common.typeutils import checked_cast\nfrom botorch.acquisition.acquisition import AcquisitionFunction\nfrom botorch.acquisition.monte_carlo import qNoisyExpectedImprovement\nfrom botorch.acquisition.multi_objective.monte_carlo import (\n qNoisyExpectedHypervolumeImprovement,\n)\nfrom botorch.models.gp_regression import FixedNoiseGP, SingleTaskGP\nfrom botorch.models.gp_regression_fidelity import (\n FixedNoiseMultiFidelityGP,\n SingleTaskMultiFidelityGP,\n)\nfrom botorch.models.gp_regression_mixed import MixedSingleTaskGP\nfrom botorch.models.gpytorch import BatchedMultiOutputGPyTorchModel\nfrom botorch.models.model import Model\nfrom botorch.models.multitask import FixedNoiseMultiTaskGP, MultiTaskGP\nfrom torch import Tensor\n\n\nMIN_OBSERVED_NOISE_LEVEL = 1e-7\nlogger = get_logger(__name__)\n\n\ndef use_model_list(Xs: List[Tensor], botorch_model_class: Type[Model]) -> bool:\n if issubclass(botorch_model_class, MultiTaskGP):\n # We currently always wrap multi-task models into `ModelListGP`.\n return True\n if len(Xs) == 1:\n # Just one outcome, can use single model.\n return False\n if issubclass(botorch_model_class, BatchedMultiOutputGPyTorchModel) and all(\n torch.equal(Xs[0], X) for X in Xs[1:]\n ):\n # Single model, batched multi-output case.\n return False\n # If there are multiple Xs and they are not all equal, we\n # use `ListSurrogate` and `ModelListGP`.\n return True\n\n\ndef choose_model_class(\n Yvars: List[Tensor],\n search_space_digest: SearchSpaceDigest,\n) -> Type[Model]:\n \"\"\"Chooses a BoTorch `Model` using the given data (currently just Yvars)\n and its properties (information about task and fidelity features).\n\n Args:\n Yvars: List of tensors, each representing observation noise for a\n given outcome, where outcomes are in the same order as in Xs.\n task_features: List of columns of X that are tasks.\n fidelity_features: List of columns of X that are fidelity parameters.\n\n Returns:\n A BoTorch `Model` class.\n \"\"\"\n if len(search_space_digest.fidelity_features) > 1:\n raise NotImplementedError(\n \"Only a single fidelity feature supported \"\n f\"(got: {search_space_digest.fidelity_features}).\"\n )\n if len(search_space_digest.task_features) > 1:\n raise NotImplementedError(\n f\"Only a single task feature supported \"\n f\"(got: {search_space_digest.task_features}).\"\n )\n if search_space_digest.task_features and search_space_digest.fidelity_features:\n raise NotImplementedError(\n \"Multi-task multi-fidelity optimization not yet supported.\"\n )\n\n Yvars_cat = torch.cat(Yvars).clamp_min_(MIN_OBSERVED_NOISE_LEVEL)\n is_nan = torch.isnan(Yvars_cat)\n all_nan_Yvar = torch.all(is_nan)\n if torch.any(is_nan) and not all_nan_Yvar:\n raise ValueError(\n \"Mix of known and unknown variances indicates valuation function \"\n \"errors. Variances should all be specified, or none should be.\"\n )\n\n # Multi-task cases (when `task_features` specified).\n if search_space_digest.task_features and all_nan_Yvar:\n model_class = MultiTaskGP # Unknown observation noise.\n elif search_space_digest.task_features:\n model_class = FixedNoiseMultiTaskGP # Known observation noise.\n\n # Single-task multi-fidelity cases.\n elif search_space_digest.fidelity_features and all_nan_Yvar:\n model_class = SingleTaskMultiFidelityGP # Unknown observation noise.\n elif search_space_digest.fidelity_features:\n model_class = FixedNoiseMultiFidelityGP # Known observation noise.\n\n # Mixed optimization case. Note that presence of categorical\n # features in search space digest indicates that downstream in the\n # stack we chose not to perform continuous relaxation on those\n # features.\n elif search_space_digest.categorical_features:\n if not all_nan_Yvar:\n logger.warning(\n \"Using `MixedSingleTaskGP` despire the known `Yvar` values. This \"\n \"is a temporary measure while fixed-noise mixed BO is in the works.\"\n )\n model_class = MixedSingleTaskGP\n\n # Single-task single-fidelity cases.\n elif all_nan_Yvar: # Unknown observation noise.\n model_class = SingleTaskGP\n else:\n model_class = FixedNoiseGP # Known observation noise.\n\n logger.debug(f\"Chose BoTorch model class: {model_class}.\")\n return model_class\n\n\ndef choose_botorch_acqf_class(\n pending_observations: Optional[List[Tensor]] = None,\n outcome_constraints: Optional[Tuple[Tensor, Tensor]] = None,\n linear_constraints: Optional[Tuple[Tensor, Tensor]] = None,\n fixed_features: Optional[Dict[int, float]] = None,\n objective_thresholds: Optional[Tensor] = None,\n) -> Type[AcquisitionFunction]:\n \"\"\"Chooses a BoTorch `AcquisitionFunction` class.\"\"\"\n if objective_thresholds is not None:\n acqf_class = qNoisyExpectedHypervolumeImprovement\n else:\n acqf_class = qNoisyExpectedImprovement\n\n logger.debug(f\"Chose BoTorch acquisition function class: {acqf_class}.\")\n return acqf_class\n\n\ndef validate_data_format(\n Xs: List[Tensor], Ys: List[Tensor], Yvars: List[Tensor], metric_names: List[str]\n) -> None:\n \"\"\"Validates that Xs, Ys, Yvars, and metric names all have equal lengths.\"\"\"\n if len({len(Xs), len(Ys), len(Yvars), len(metric_names)}) > 1:\n raise ValueError( # pragma: no cover\n \"Lengths of Xs, Ys, Yvars, and metric_names must match. Your \"\n f\"inputs have lengths {len(Xs)}, {len(Ys)}, {len(Yvars)}, and \"\n f\"{len(metric_names)}, respectively.\"\n )\n\n\ndef construct_acquisition_and_optimizer_options(\n acqf_options: TConfig, model_gen_options: Optional[TConfig] = None\n) -> Tuple[TConfig, TConfig]:\n \"\"\"Extract acquisition and optimizer options from `model_gen_options`.\"\"\"\n acq_options = acqf_options.copy()\n opt_options = {}\n\n if model_gen_options:\n acq_options.update(\n checked_cast(dict, model_gen_options.get(Keys.ACQF_KWARGS, {}))\n )\n # TODO: Add this if all acq. functions accept the `subset_model`\n # kwarg or opt for kwarg filtering.\n # acq_options[SUBSET_MODEL] = model_gen_options.get(SUBSET_MODEL)\n opt_options = checked_cast(\n dict, model_gen_options.get(Keys.OPTIMIZER_KWARGS, {})\n ).copy()\n return acq_options, opt_options\n" ]
[ [ "torch.ones", "torch.zeros", "torch.equal", "torch.tensor", "torch.rand", "torch.device", "numpy.array", "numpy.exp" ], [ "pandas.DataFrame.from_dict" ], [ "torch.all", "torch.isnan", "torch.cat", "torch.equal", "torch.any" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
daniloorozco/ufc-predictions
[ "0dbf91936587bc9acfea15151ab6845c77483124" ]
[ "models/model_NN.py" ]
[ "#Neural Networks\n#MLP classifier is optimal algorithm for classifications\n\nfrom sklearn.neural_network import MLPClassifier\n\nclf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1)\nclf.fit(X_train_clean, y_train)\n\nclf.predict(X_test_clean)\nscoreN = clf.score(X_test_clean, y_test)\nprint(scoreN)" ]
[ [ "sklearn.neural_network.MLPClassifier" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
YuGong123/ID-disentanglement-Pytorch
[ "1b110f653a1945ea498b21cd6ed7d7e4fee0f74b" ]
[ "Models/Encoders/ID_Encoder.py" ]
[ "import torch\nfrom facenet_pytorch import MTCNN, InceptionResnetV1\nfrom torchvision import transforms\nfrom Configs import Global_Config\n\nIMAGE_SIZE = 220\nmtcnn = MTCNN(\n image_size=IMAGE_SIZE, margin=0, min_face_size=20,\n thresholds=[0.6, 0.7, 0.7], factor=0.709, post_process=True,\n device=Global_Config.device\n)\nto_pil = transforms.ToPILImage(mode='RGB')\ncrop_transform = transforms.Compose([transforms.Resize(IMAGE_SIZE),\n transforms.CenterCrop(IMAGE_SIZE)])\n\nresnet = InceptionResnetV1(pretrained='vggface2', classify=False).eval().to(Global_Config.device)\n\nclass ID_Encoder(torch.nn.Module):\n\n def __init__(self):\n super(ID_Encoder, self).__init__()\n\n def crop_tensor_according_to_bboxes(self, images, bboxes):\n cropped_batch = []\n for idx, image in enumerate(images):\n try:\n cropped_image = crop_transform(image[:, int(bboxes[idx][0][1]):int(bboxes[idx][0][3]),\n int(bboxes[idx][0][0]):int(bboxes[idx][0][2])].unsqueeze(0))\n except:\n cropped_image = crop_transform(image.unsqueeze(0))\n cropped_batch.append(cropped_image)\n\n return torch.cat(cropped_batch, dim=0)\n\n def preprocess_images_to_id_encoder(self, images):\n bboxes = [mtcnn.detect(to_pil(image))[0] for image in images]\n cropped_images = self.crop_tensor_according_to_bboxes(images, bboxes)\n return cropped_images\n\n def forward(self, images):\n cropped_images = self.preprocess_images_to_id_encoder(images)\n img_embeddings = resnet(cropped_images)\n return img_embeddings" ]
[ [ "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hadleyhzy34/reinforcement_learning
[ "14371756c2ff8225dc800d146452b7956875410c", "14371756c2ff8225dc800d146452b7956875410c" ]
[ "TD/double_q_learning.py", "dqn/dqn_torch/networks.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nimport gym\nimport random\n\n# hyper parameters\n# test 1\n# alpha = 0.5\n# gamma = 0.95\n# epsilon = 0.1\n\nepsilon = 0.1\nalpha = 0.1\ngamma = 0.1\n\ndef update_sarsa_table(sarsa, state, action, reward, next_state, next_action, alpha, gamma):\n '''\n update sarsa state-action pair value, main difference from q learning is that it uses epsilon greedy policy\n return action\n '''\n next_max = sarsa[next_state,next_action] # corresponding action-state value to current action\n\n # print(f'current status is: {type(q[pre_state,action])},{type(alpha)},{type(reward)},{type(gamma)},{type(next_max)}')\n sarsa[state,action] = sarsa[state,action] + alpha * (reward + gamma * next_max - sarsa[state,action])\n\ndef epsilon_greedy_policy_sarsa(env, state, sarsa, epsilon):\n '''\n epsilon greedy policy for q learning to generate actions\n '''\n if random.uniform(0,1) < epsilon:\n return env.action_space.sample()\n else:\n return np.argmax(sarsa[state])\n\ndef epsilon_greedy_policy(env, state, q, epsilon):\n '''\n epsilon greedy policy for q learning to generate actions\n '''\n if random.uniform(0,1) < epsilon:\n return env.action_space.sample()\n else:\n return np.argmax(q[state])\n\ndef update_q_table(q, pre_state, action, reward, next_state, alpha, gamma):\n '''\n\n '''\n next_max = np.max(q[next_state]) # max state-action value for next state\n # print(f'current status is: {type(q[pre_state,action])},{type(alpha)},{type(reward)},{type(gamma)},{type(next_max)}')\n q[pre_state,action] = q[pre_state,action] + alpha * (reward + gamma * next_max - q[pre_state,action])\n\n\n#-----------------------q learning-------------------------------------------\nenv = gym.make(\"Taxi-v3\")\n\n# initialize q table\nq = np.zeros((env.observation_space.n, env.action_space.n))\nq_pre = np.zeros((env.observation_space.n, env.action_space.n)) # to check convergence when training\nreward_record = []\nerror_record = []\n# loop for each episode:\nfor episode in range(5000):\n r = 0\n state = env.reset()\n while True:# loop for each step of episode\n # choose A from S using policy derived from Q(e.g, epsilon greedy policy)\n action = epsilon_greedy_policy(env,state,q,epsilon)\n # take action A, observe R, S'\n next_state, reward, done, _ = env.step(action)\n # update Q(S,A)\n update_q_table(q,state,action,reward,next_state,alpha,gamma)\n # S<--S'\n state = next_state\n r += reward\n if done:\n break\n \n reward_record.append(r)\n error = 0\n for i in range(q.shape[0]):\n error = error + np.sum(np.abs(q[i]-q_pre[i]))\n # print(f'{np.abs(q[i]-q_pre[i])},{np.sum(np.abs(q[i]-q_pre[i]))}')\n error_record.append(error)\n q_pre = np.copy(q)\n\n if episode%100 == 0:\n print(f'{episode}th episode: {r}, {error}')\n\n#close game env\nenv.close()\n\n#plot diagram\n# plt.plot(list(range(5000)),reward_record)\n# plt.show()\n\n# plt.plot(list(range(5000)),error_record)\n# plt.show()\n\n#double q learning\nenv = gym.make(\"Taxi-v3\")\n\n# initialize q table\nq1 = np.zeros((env.observation_space.n, env.action_space.n))\nq2 = np.zeros((env.observation_space.n, env.action_space.n))\nq1_pre = np.zeros((env.observation_space.n, env.action_space.n)) # to check convergence when training\nq2_pre = np.zeros((env.observation_space.n, env.action_space.n)) # to check convergence when training\n\n# reward and error record\nd_reward_record = []\nd_error_record = []\n\n# loop for each episode:\nfor episode in range(5000):\n r = 0\n state = env.reset()\n while True:# loop for each step of episode\n # choose A from S using policy derived from Q1+Q2(e.g, epsilon greedy policy)\n action = epsilon_greedy_policy(env,state,q1+q2,epsilon)\n # take action A, observe R, S'\n next_state, reward, done, _ = env.step(action)\n # with 0.5 probability:\n if random.uniform(0,1) < 0.5:\n update_q_table(q1,state,action,reward,next_state,alpha,gamma)\n else:\n update_q_table(q2,state,action,reward,next_state,alpha,gamma)\n # S<--S'\n state = next_state\n r += reward\n if done:\n break\n \n d_reward_record.append(r)\n error = 0\n for i in range(q.shape[0]):\n error = error + 0.5 * np.sum(np.abs(q1[i]-q1_pre[i])) + 0.5 * np.sum(np.abs(q2[i]-q2_pre[i]))\n # print(f'{np.abs(q[i]-q_pre[i])},{np.sum(np.abs(q[i]-q_pre[i]))}')\n d_error_record.append(error)\n q1_pre = np.copy(q1)\n q2_pre = np.copy(q2)\n\n if episode%100 == 0:\n print(f'{episode}th episode: {r}, {error}')\n\n#close game env\nenv.close()\n\n#plot diagram\nplt.plot(list(range(5000)),reward_record,label='q learning')\nplt.plot(list(range(5000)),d_reward_record,label='double q learning')\nplt.legend()\nplt.show()\n\nplt.plot(list(range(5000)),error_record,label='q learning')\nplt.plot(list(range(5000)),d_error_record, label='double q learning')\nplt.legend()\nplt.show()\n", "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Q_Network(nn.Module):\n def __init__(self, states, actions, hidden=[64,64]):\n super(Q_Network, self).__init__()\n self.fc1 = nn.Linear(states, hidden[0])\n self.fc2 = nn.Linear(hidden[0], hidden[1])\n self.fc3 = nn.Linear(hidden[1], actions)\n\n def forward(self,state):\n x = state\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.abs", "numpy.max", "numpy.copy", "numpy.argmax", "matplotlib.pyplot.show", "numpy.zeros" ], [ "torch.nn.Linear" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
viper7882/mxnet_win32
[ "102f8d0ed59529bbd162c37bf07ae58ad6c4caa1", "102f8d0ed59529bbd162c37bf07ae58ad6c4caa1", "102f8d0ed59529bbd162c37bf07ae58ad6c4caa1" ]
[ "example/gluon/tree_lstm/main.py", "example/gluon/actor_critic.py", "example/speech_recognition/stt_metric.py" ]
[ "# This example is inspired by https://github.com/dasguptar/treelstm.pytorch\nimport argparse, cPickle, math, os, random\nimport logging\nlogging.basicConfig(level=logging.INFO)\nimport numpy as np\nfrom tqdm import tqdm\n\nimport mxnet as mx\nfrom mxnet import gluon\nfrom mxnet.gluon import nn\nfrom mxnet import autograd as ag\n\nfrom tree_lstm import SimilarityTreeLSTM\nfrom dataset import Vocab, SICKDataIter\n\nparser = argparse.ArgumentParser(description='TreeLSTM for Sentence Similarity on Dependency Trees')\nparser.add_argument('--data', default='data/sick/',\n help='path to raw dataset. required when preprocessed dataset is not available.')\nparser.add_argument('--word_embed', default='data/glove/glove.840B.300d.txt',\n help='directory with word embeddings. required when preprocessed dataset is not available.')\nparser.add_argument('--batch_size', type=int, default=25,\n help='training batch size per device (CPU/GPU).')\nparser.add_argument('--epochs', default=50, type=int,\n help='number of total epochs to run')\nparser.add_argument('--lr', default=0.02, type=float,\n help='initial learning rate')\nparser.add_argument('--wd', default=0.0001, type=float,\n help='weight decay factor')\nparser.add_argument('--optimizer', default='adagrad',\n help='optimizer (default: adagrad)')\nparser.add_argument('--seed', default=123, type=int,\n help='random seed (default: 123)')\nparser.add_argument('--use-gpu', action='store_true',\n help='whether to use GPU.')\n\nopt = parser.parse_args()\n\nlogging.info(opt)\n\ncontext = [mx.gpu(0) if opt.use_gpu else mx.cpu()]\n\nrnn_hidden_size, sim_hidden_size, num_classes = 150, 50, 5\noptimizer = opt.optimizer.lower()\n\nmx.random.seed(opt.seed)\nnp.random.seed(opt.seed)\nrandom.seed(opt.seed)\n\nbatch_size = opt.batch_size\n\n# read dataset\nif os.path.exists('dataset.cPickle'):\n with open('dataset.cPickle', 'rb') as f:\n train_iter, dev_iter, test_iter, vocab = cPickle.load(f)\nelse:\n root_dir = opt.data\n segments = ['train', 'dev', 'test']\n token_files = [os.path.join(root_dir, seg, '%s.toks'%tok)\n for tok in ['a', 'b']\n for seg in segments]\n\n vocab = Vocab(filepaths=token_files, embedpath=opt.word_embed)\n\n train_iter, dev_iter, test_iter = [SICKDataIter(os.path.join(root_dir, segment), vocab, num_classes)\n for segment in segments]\n with open('dataset.cPickle', 'wb') as f:\n cPickle.dump([train_iter, dev_iter, test_iter, vocab], f)\n\nlogging.info('==> SICK vocabulary size : %d ' % vocab.size)\nlogging.info('==> Size of train data : %d ' % len(train_iter))\nlogging.info('==> Size of dev data : %d ' % len(dev_iter))\nlogging.info('==> Size of test data : %d ' % len(test_iter))\n\n# get network\nnet = SimilarityTreeLSTM(sim_hidden_size, rnn_hidden_size, vocab.size, vocab.embed.shape[1], num_classes)\n\n# use pearson correlation and mean-square error for evaluation\nmetric = mx.metric.create(['pearsonr', 'mse'])\n\ndef to_target(x):\n target = np.zeros((1, num_classes))\n ceil = int(math.ceil(x))\n floor = int(math.floor(x))\n if ceil==floor:\n target[0][floor-1] = 1\n else:\n target[0][floor-1] = ceil - x\n target[0][ceil-1] = x - floor\n return mx.nd.array(target)\n\ndef to_score(x):\n levels = mx.nd.arange(1, 6, ctx=x.context)\n return [mx.nd.sum(levels*mx.nd.exp(x), axis=1).reshape((-1,1))]\n\n# when evaluating in validation mode, check and see if pearson-r is improved\n# if so, checkpoint and run evaluation on test dataset\ndef test(ctx, data_iter, best, mode='validation', num_iter=-1):\n data_iter.reset()\n batches = len(data_iter)\n data_iter.set_context(ctx[0])\n preds = []\n labels = [mx.nd.array(data_iter.labels, ctx=ctx[0]).reshape((-1,1))]\n for _ in tqdm(range(batches), desc='Testing in {} mode'.format(mode)):\n l_tree, l_sent, r_tree, r_sent, label = data_iter.next()\n z = net(mx.nd, l_sent, r_sent, l_tree, r_tree)\n preds.append(z)\n\n preds = to_score(mx.nd.concat(*preds, dim=0))\n metric.update(preds, labels)\n names, values = metric.get()\n metric.reset()\n for name, acc in zip(names, values):\n logging.info(mode+' acc: %s=%f'%(name, acc))\n if name == 'pearsonr':\n test_r = acc\n if mode == 'validation' and num_iter >= 0:\n if test_r >= best:\n best = test_r\n logging.info('New optimum found: {}. Checkpointing.'.format(best))\n net.collect_params().save('childsum_tree_lstm_{}.params'.format(num_iter))\n test(ctx, test_iter, -1, 'test')\n return best\n\n\ndef train(epoch, ctx, train_data, dev_data):\n\n # initialization with context\n if isinstance(ctx, mx.Context):\n ctx = [ctx]\n net.collect_params().initialize(mx.init.Xavier(magnitude=2.24), ctx=ctx[0])\n net.embed.weight.set_data(vocab.embed.as_in_context(ctx[0]))\n train_data.set_context(ctx[0])\n dev_data.set_context(ctx[0])\n\n # set up trainer for optimizing the network.\n trainer = gluon.Trainer(net.collect_params(), optimizer, {'learning_rate': opt.lr, 'wd': opt.wd})\n\n best_r = -1\n Loss = gluon.loss.KLDivLoss()\n for i in range(epoch):\n train_data.reset()\n num_batches = len(train_data)\n # collect predictions and labels for evaluation metrics\n preds = []\n labels = [mx.nd.array(train_data.labels, ctx=ctx[0]).reshape((-1,1))]\n for j in tqdm(range(num_batches), desc='Training epoch {}'.format(i)):\n # get next batch\n l_tree, l_sent, r_tree, r_sent, label = train_data.next()\n # use autograd to record the forward calculation\n with ag.record():\n # forward calculation. the output is log probability\n z = net(mx.nd, l_sent, r_sent, l_tree, r_tree)\n # calculate loss\n loss = Loss(z, to_target(label).as_in_context(ctx[0]))\n # backward calculation for gradients.\n loss.backward()\n preds.append(z)\n # update weight after every batch_size samples\n if (j+1) % batch_size == 0:\n trainer.step(batch_size)\n\n # translate log-probability to scores, and evaluate\n preds = to_score(mx.nd.concat(*preds, dim=0))\n metric.update(preds, labels)\n names, values = metric.get()\n metric.reset()\n for name, acc in zip(names, values):\n logging.info('training acc at epoch %d: %s=%f'%(i, name, acc))\n best_r = test(ctx, dev_data, best_r, num_iter=i)\n\ntrain(opt.epochs, context, train_iter, dev_iter)\n", "from __future__ import print_function\n\nimport argparse\nimport gym\nfrom itertools import count\nimport numpy as np\n\nimport mxnet as mx\nimport mxnet.ndarray as F\nfrom mxnet import gluon\nfrom mxnet.gluon import nn\nfrom mxnet import autograd\n\n\nparser = argparse.ArgumentParser(description='MXNet actor-critic example')\nparser.add_argument('--gamma', type=float, default=0.99, metavar='G',\n help='discount factor (default: 0.99)')\nparser.add_argument('--seed', type=int, default=543, metavar='N',\n help='random seed (default: 1)')\nparser.add_argument('--render', action='store_true',\n help='render the environment')\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='interval between training status logs (default: 10)')\nargs = parser.parse_args()\n\n\nenv = gym.make('CartPole-v0')\nenv.seed(args.seed)\n\n\nclass Policy(gluon.Block):\n def __init__(self, **kwargs):\n super(Policy, self).__init__(**kwargs)\n with self.name_scope():\n self.dense = nn.Dense(16, in_units=4, activation='relu')\n self.action_pred = nn.Dense(2, in_units=16)\n self.value_pred = nn.Dense(1, in_units=16)\n\n def forward(self, x):\n x = self.dense(x)\n probs = self.action_pred(x)\n values = self.value_pred(x)\n return F.softmax(probs), values\n\nnet = Policy()\nnet.collect_params().initialize(mx.init.Uniform(0.02))\ntrainer = gluon.Trainer(net.collect_params(), 'adam', {'learning_rate': 3e-2})\nloss = gluon.loss.L1Loss()\n\nrunning_reward = 10\nfor epoch in count(1):\n state = env.reset()\n rewards = []\n values = []\n heads = []\n actions = []\n with autograd.record():\n # Sample a sequence of actions\n for t in range(10000):\n state = mx.nd.array(np.expand_dims(state, 0))\n prob, value = net(state)\n action, logp = mx.nd.sample_multinomial(prob, get_prob=True)\n state, reward, done, _ = env.step(action.asnumpy()[0])\n if args.render:\n env.render()\n rewards.append(reward)\n values.append(value)\n actions.append(action.asnumpy()[0])\n heads.append(logp)\n if done:\n break\n\n # reverse accumulate and normalize rewards\n running_reward = running_reward * 0.99 + t * 0.01\n R = 0\n for i in range(len(rewards)-1, -1, -1):\n R = rewards[i] + args.gamma * R\n rewards[i] = R\n rewards = np.array(rewards)\n rewards -= rewards.mean()\n rewards /= rewards.std() + np.finfo(rewards.dtype).eps\n\n # compute loss and gradient\n L = sum([loss(value, mx.nd.array([r])) for r, value in zip(rewards, values)])\n final_nodes = [L]\n for logp, r, v in zip(heads, rewards, values):\n reward = r - v.asnumpy()[0,0]\n # Here we differentiate the stochastic graph, corresponds to the\n # first term of equation (6) in https://arxiv.org/pdf/1506.05254.pdf\n # Optimizer minimizes the loss but we want to maximizing the reward,\n # so use we use -reward here.\n final_nodes.append(logp*(-reward))\n autograd.backward(final_nodes)\n\n trainer.step(t)\n\n if epoch % args.log_interval == 0:\n print('Episode {}\\tLast length: {:5d}\\tAverage length: {:.2f}'.format(\n epoch, t, running_reward))\n if running_reward > 200:\n print(\"Solved! Running reward is now {} and \"\n \"the last episode runs to {} time steps!\".format(running_reward, t))\n break\n", "import mxnet as mx\nimport numpy as np\n\nfrom label_util import LabelUtil\nfrom log_util import LogUtil\n\n\ndef check_label_shapes(labels, preds, shape=0):\n \"\"\"Check to see if the two arrays are the same size.\"\"\"\n\n if shape == 0:\n label_shape, pred_shape = len(labels), len(preds)\n else:\n label_shape, pred_shape = labels.shape, preds.shape\n\n if label_shape != pred_shape:\n raise ValueError(\"Shape of labels {} does not match shape of \"\n \"predictions {}\".format(label_shape, pred_shape))\n\n\nclass STTMetric(mx.metric.EvalMetric):\n def __init__(self, batch_size, num_gpu, is_epoch_end=False, is_logging=True):\n super(STTMetric, self).__init__('STTMetric')\n\n self.batch_size = batch_size\n self.num_gpu = num_gpu\n self.total_n_label = 0\n self.total_l_dist = 0\n self.is_epoch_end = is_epoch_end\n self.total_ctc_loss = 0.\n self.batch_loss = 0.\n self.is_logging = is_logging\n def update(self, labels, preds):\n check_label_shapes(labels, preds)\n if self.is_logging:\n log = LogUtil().getlogger()\n labelUtil = LabelUtil.getInstance()\n self.batch_loss = 0.\n\n for label, pred in zip(labels, preds):\n label = label.asnumpy()\n pred = pred.asnumpy()\n\n seq_length = len(pred) / int(int(self.batch_size) / int(self.num_gpu))\n\n for i in range(int(int(self.batch_size) / int(self.num_gpu))):\n l = remove_blank(label[i])\n p = []\n for k in range(int(seq_length)):\n p.append(np.argmax(pred[k * int(int(self.batch_size) / int(self.num_gpu)) + i]))\n p = pred_best(p)\n\n l_distance = levenshtein_distance(l, p)\n self.total_n_label += len(l)\n self.total_l_dist += l_distance\n this_cer = float(l_distance) / float(len(l))\n if self.is_logging:\n log.info(\"label: %s \" % (labelUtil.convert_num_to_word(l)))\n log.info(\"pred : %s , cer: %f (distance: %d/ label length: %d)\" % (\n labelUtil.convert_num_to_word(p), this_cer, l_distance, len(l)))\n self.num_inst += 1\n self.sum_metric += this_cer\n if self.is_epoch_end:\n loss = ctc_loss(l, pred, i, int(seq_length), int(self.batch_size), int(self.num_gpu))\n self.batch_loss += loss\n if self.is_logging:\n log.info(\"loss: %f \" % loss)\n self.total_ctc_loss += self.batch_loss\n def get_batch_loss(self):\n return self.batch_loss\n def get_name_value(self):\n total_cer = float(self.total_l_dist) / float(self.total_n_label)\n\n return total_cer, self.total_n_label, self.total_l_dist, self.total_ctc_loss\n\n def reset(self):\n self.total_n_label = 0\n self.total_l_dist = 0\n self.num_inst = 0\n self.sum_metric = 0.0\n self.total_ctc_loss = 0.0\n\n\ndef pred_best(p):\n ret = []\n p1 = [0] + p\n for i in range(len(p)):\n c1 = p1[i]\n c2 = p1[i + 1]\n if c2 == 0 or c2 == c1:\n continue\n ret.append(c2)\n return ret\n\n\ndef remove_blank(l):\n ret = []\n for i in range(l.size):\n if l[i] == 0:\n break\n ret.append(l[i])\n return ret\n\n\ndef remove_space(l):\n labelUtil = LabelUtil.getInstance()\n ret = []\n for i in range(len(l)):\n if l[i] != labelUtil.get_space_index():\n ret.append(l[i])\n return ret\n\n\ndef ctc_loss(label, prob, remainder, seq_length, batch_size, num_gpu=1, big_num=1e10):\n label_ = [0, 0]\n prob[prob < 1 / big_num] = 1 / big_num\n log_prob = np.log(prob)\n\n l = len(label)\n for i in range(l):\n label_.append(int(label[i]))\n label_.append(0)\n\n l_ = 2 * l + 1\n a = np.full((seq_length, l_ + 1), -big_num)\n a[0][1] = log_prob[remainder][0]\n a[0][2] = log_prob[remainder][label_[2]]\n for i in range(1, seq_length):\n row = i * int(batch_size / num_gpu) + remainder\n a[i][1] = a[i - 1][1] + log_prob[row][0]\n a[i][2] = np.logaddexp(a[i - 1][2], a[i - 1][1]) + log_prob[row][label_[2]]\n for j in range(3, l_ + 1):\n a[i][j] = np.logaddexp(a[i - 1][j], a[i - 1][j - 1])\n if label_[j] != 0 and label_[j] != label_[j - 2]:\n a[i][j] = np.logaddexp(a[i][j], a[i - 1][j - 2])\n a[i][j] += log_prob[row][label_[j]]\n\n return -np.logaddexp(a[seq_length - 1][l_], a[seq_length - 1][l_ - 1])\n\n\n# label is done with remove_blank\n# pred is got from pred_best\ndef levenshtein_distance(label, pred):\n n_label = len(label) + 1\n n_pred = len(pred) + 1\n if (label == pred):\n return 0\n if (len(label) == 0):\n return len(pred)\n if (len(pred) == 0):\n return len(label)\n\n v0 = [i for i in range(n_label)]\n v1 = [0 for i in range(n_label)]\n\n for i in range(len(pred)):\n v1[0] = i + 1\n\n for j in range(len(label)):\n cost = 0 if label[j] == pred[i] else 1\n v1[j + 1] = min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost)\n\n for j in range(n_label):\n v0[j] = v1[j]\n\n return v1[len(label)]\n\n\ndef char_match_1way(char_label, char_pred, criteria, n_whole_label):\n n_label = len(char_label)\n n_pred = len(char_pred)\n\n pred_pos = 0\n accuracy = 0.\n next_accu = 0.\n n_matched = 0.\n next_n_matched = 0.\n\n for i_index in range(n_label):\n tail_label = n_label - 1 - i_index\n c_label = char_label[i_index]\n\n for j_index in range(pred_pos, n_pred):\n tail_pred = n_pred - 1 - j_index\n c_pred = char_pred[j_index]\n\n if tail_label < tail_pred * criteria or tail_pred < tail_label * criteria:\n break\n if c_label == c_pred:\n n_matched += 1.0\n pred_pos = j_index + 1\n break\n\n accuracy = n_matched / n_whole_label\n\n if n_label > 0.7 * n_whole_label:\n next_label = char_label[1:]\n next_accu, next_n_matched = char_match_1way(next_label, char_pred, criteria, n_whole_label)\n\n if next_accu > accuracy:\n accuracy = next_accu\n n_matched = next_n_matched\n return accuracy, n_matched\n\n\ndef char_match_2way(label, pred):\n criterias = [0.98, 0.96, 0.93, 0.9, 0.85, 0.8, 0.7]\n r_pred = pred[::-1]\n r_label = label[::-1]\n n_whole_label = len(remove_space(label))\n\n val1_max = 0.\n val2_max = 0.\n val1_max_matched = 0.\n val2_max_matched = 0.\n for criteria in criterias:\n val1, val1_matched = char_match_1way(label, pred, criteria, n_whole_label)\n val2, val2_matched = char_match_1way(r_label, r_pred, criteria, n_whole_label)\n\n if val1 > val1_max:\n val1_max = val1\n val1_max_matched = val1_matched\n if val2 > val2_max:\n val2_max = val2\n val2_max_matched = val2_matched\n\n val = val1_max if val1_max > val2_max else val2_max\n val_matched = val1_max_matched if val1_max > val2_max else val2_max_matched\n return val, val_matched, n_whole_label\n\n" ]
[ [ "numpy.zeros", "numpy.random.seed" ], [ "numpy.array", "numpy.expand_dims", "numpy.finfo" ], [ "numpy.log", "numpy.logaddexp", "numpy.full" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
EugeneNdiaye/rootCP
[ "a9777d0f4871dbd1bc0afd680889c0a3e73ec7d0" ]
[ "rootcp/models.py" ]
[ "import numpy as np\n\n\nclass ridge:\n \"\"\" Ridge estimator.\n \"\"\"\n\n def __init__(self, lmd=0.1):\n\n self.lmd = lmd\n self.hat = None\n self.hatn = None\n\n def fit(self, X, y):\n\n if self.hat is None:\n G = X.T.dot(X) + self.lmd * np.eye(X.shape[1])\n self.hat = np.linalg.solve(G, X.T)\n\n if self.hatn is None:\n y0 = np.array(list(y[:-1]) + [0])\n self.hatn = self.hat.dot(y0)\n\n self.beta = self.hatn + y[-1] * self.hat[:, -1]\n\n def predict(self, X):\n\n return X.dot(self.beta)\n\n def conformity(self, y, y_pred):\n\n return 0.5 * np.square(y - y_pred)\n\n\nclass regressor:\n\n def __init__(self, model=None, s_eps=0., conform=None):\n\n self.model = model\n self.coefs = []\n self.s_eps = s_eps\n self.conform = conform\n\n def fit(self, X, y):\n\n refit = True\n\n for t in range(len(self.coefs)):\n\n if self.s_eps == 0:\n break\n\n if abs(self.coefs[t][0] - y[-1]) <= self.s_eps:\n self.beta = self.coefs[t][1].copy()\n refit = False\n break\n\n if refit:\n self.beta = self.model.fit(X, y)\n if self.s_eps != 0:\n self.coefs += [[y[-1], self.beta.copy()]]\n\n def predict(self, X):\n\n if len(X.shape) == 1:\n X = X.reshape(1, -1)\n\n return self.model.predict(X)\n\n def conformity(self, y, y_pred):\n\n if self.conform is None:\n return np.abs(y - y_pred)\n\n else:\n return self.conform(y, y_pred)\n" ]
[ [ "numpy.square", "numpy.eye", "numpy.linalg.solve", "numpy.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
NinaHerrmann/muesli2py
[ "632bb67433c6f67eaa48dc431d51914e0fde8f22" ]
[ "swig_muesli/muesli/da/setup_da.py" ]
[ "import os\nfrom setuptools import setup, Extension\nfrom setuptools.command.build_ext import build_ext\nfrom Cython.Distutils import build_ext\nimport numpy as np\nfrom os.path import join as pjoin\nfrom setup_cuda import cuda_setup\n\nmpi_compile_args = os.popen(\"mpic++ --showme:compile\").read().strip().split(' ')\nmpi_link_args = os.popen(\"mpic++ --showme:link\").read().strip().split(' ')\n\n\ndef find_in_path(name, path):\n \"\"\"Find a file in a search path\"\"\"\n\n # Adapted fom http://code.activestate.com/recipes/52224\n for dir in path.split(os.pathsep):\n binpath = pjoin(dir, name)\n if os.path.exists(binpath):\n return os.path.abspath(binpath)\n return None\n\n\ntry:\n numpy_include = np.get_include()\nexcept AttributeError:\n numpy_include = np.get_numpy_include()\n\nnvcc = find_in_path('nvcc', os.environ['PATH'])\nif isinstance(nvcc, str):\n print('CUDA')\n # setup(name='PackageName',\n # author='Nina Herrmann',\n # version='1.0',\n # description='This is a package for Muesli',\n # ext_modules=cythonize(cuda_setup.get_module()),\n # cmdclass={'build_ext': cuda_setup.custom_build_ext()}\n # )\nelse:\n module = Extension('_da', sources=['da.cxx', 'da_wrap.cxx'],\n include_dirs=[np.get_include(), 'src'],\n library_dirs=['/usr/include/boost/'],\n language=\"c++\",\n swig_opts=['-c++'],\n libraries=['/usr/include/boost/chrono'],\n extra_compile_args=([\"-fopenmp\"] + mpi_compile_args),\n extra_link_args=([\"-fopenmp\"] + mpi_link_args)\n )\n\n setup(name='da',\n author='Nina Herrmann',\n version='1.0',\n description='This is a package for Muesli',\n ext_modules=[module],\n py_modules=[\"da\"]\n )\n" ]
[ [ "numpy.get_numpy_include", "numpy.get_include" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
x109airfighter/akshare
[ "06b553d0a56f54a0e8f8a2031c374366a8b25e91" ]
[ "akshare/stock/zh_stock_a_sina.py" ]
[ "# -*- coding:utf-8 -*-\n# /usr/bin/env python\n\"\"\"\nDate: 2019/10/30 11:28\nDesc: 新浪财经-A股-实时行情数据和历史行情数据(包含前复权和后复权因子)\n\"\"\"\nimport re\n\nimport demjson\nimport execjs\nimport pandas as pd\nimport requests\nfrom tqdm import tqdm\n\nfrom akshare.stock.cons import (zh_sina_a_stock_payload,\n zh_sina_a_stock_url,\n zh_sina_a_stock_count_url,\n zh_sina_a_stock_hist_url,\n hk_js_decode,\n zh_sina_a_stock_hfq_url,\n zh_sina_a_stock_qfq_url,\n zh_sina_a_stock_amount_url)\n\n\ndef _get_zh_a_page_count() -> int:\n \"\"\"\n 所有股票的总页数\n http://vip.stock.finance.sina.com.cn/mkt/#hs_a\n :return: 需要抓取的股票总页数\n :rtype: int\n \"\"\"\n res = requests.get(zh_sina_a_stock_count_url)\n page_count = int(re.findall(re.compile(r\"\\d+\"), res.text)[0]) / 80\n if isinstance(page_count, int):\n return page_count\n else:\n return int(page_count) + 1\n\n\ndef stock_zh_a_spot() -> pd.DataFrame:\n \"\"\"\n 从新浪财经-A股获取所有A股的实时行情数据, 重复运行本函数会被新浪暂时封 IP\n http://vip.stock.finance.sina.com.cn/mkt/#qbgg_hk\n :return: pandas.DataFrame\n symbol code name trade pricechange changepercent buy \\\n 0 sh600000 600000 浦发银行 12.920 -0.030 -0.232 12.920\n 1 sh600004 600004 白云机场 18.110 -0.370 -2.002 18.110\n 2 sh600006 600006 东风汽车 4.410 -0.030 -0.676 4.410\n 3 sh600007 600007 中国国贸 17.240 -0.360 -2.045 17.240\n 4 sh600008 600008 首创股份 3.320 -0.030 -0.896 3.310\n ... ... ... ... ... ... ...\n 3755 sh600096 600096 云天化 5.270 -0.220 -4.007 5.270\n 3756 sh600097 600097 开创国际 10.180 -0.120 -1.165 10.180\n 3757 sh600098 600098 广州发展 6.550 -0.040 -0.607 6.540\n 3758 sh600099 600099 林海股份 6.540 -0.150 -2.242 6.540\n 3759 sh600100 600100 同方股份 8.200 -0.100 -1.205 8.200\n sell settlement open high low volume amount \\\n 0 12.930 12.950 12.950 13.100 12.860 46023920 597016896\n 1 18.120 18.480 18.510 18.510 17.880 24175071 437419344\n 2 4.420 4.440 4.490 4.490 4.410 4304900 19130233\n 3 17.280 17.600 17.670 17.670 17.220 684801 11879731\n 4 3.320 3.350 3.360 3.360 3.300 8284294 27579688\n ... ... ... ... ... ... ...\n 3755 5.280 5.490 5.490 5.500 5.220 16964636 90595172\n 3756 10.190 10.300 10.220 10.340 10.090 1001676 10231669\n 3757 6.550 6.590 6.560 6.620 6.500 1996449 13098901\n 3758 6.580 6.690 6.650 6.680 6.530 1866180 12314997\n 3759 8.210 8.300 8.300 8.310 8.120 12087236 99281447\n ticktime per pb mktcap nmc turnoverratio\n 0 15:00:00 6.984 0.790 3.792289e+07 3.631006e+07 0.16376\n 1 15:00:07 32.927 2.365 3.747539e+06 3.747539e+06 1.16826\n 2 15:00:02 15.926 1.207 8.820000e+05 8.820000e+05 0.21525\n 3 15:00:02 22.390 2.367 1.736555e+06 1.736555e+06 0.06798\n 4 15:00:07 22.912 1.730 1.887569e+06 1.600444e+06 0.17185\n ... ... ... ... ... ...\n 3755 15:00:00 56.728 1.566 7.523847e+05 6.963668e+05 1.28386\n 3756 15:00:00 17.552 1.434 2.452734e+05 2.303459e+05 0.44268\n 3757 15:00:00 25.476 1.059 1.785659e+06 1.785659e+06 0.07323\n 3758 15:00:00 540.496 3.023 1.433045e+05 1.433045e+05 0.85167\n 3759 15:00:07 -6.264 1.465 2.430397e+06 2.430397e+06 0.40782\n \"\"\"\n big_df = pd.DataFrame()\n page_count = _get_zh_a_page_count()\n zh_sina_stock_payload_copy = zh_sina_a_stock_payload.copy()\n\n for page in tqdm(range(1, page_count+1), desc=\"Please wait for a moment\"):\n zh_sina_stock_payload_copy.update({\"page\": page})\n r = requests.get(\n zh_sina_a_stock_url,\n params=zh_sina_stock_payload_copy)\n data_json = demjson.decode(r.text)\n big_df = big_df.append(pd.DataFrame(data_json), ignore_index=True)\n\n return big_df\n\n\ndef stock_zh_a_daily(symbol: str = \"sz000613\", adjust: str = \"qfq\") -> pd.DataFrame:\n \"\"\"\n 新浪财经-A股-个股的历史行情数据, 大量抓取容易封IP\n :param symbol: sh600000\n :type symbol: str\n :param adjust: 默认为空: 返回不复权的数据; qfq: 返回前复权后的数据; hfq: 返回后复权后的数据; hfq-factor: 返回后复权因子; hfq-factor: 返回前复权因子\n :type adjust: str\n :return: specific data\n :rtype: pandas.DataFrame\n \"\"\"\n res = requests.get(zh_sina_a_stock_hist_url.format(symbol))\n js_code = execjs.compile(hk_js_decode)\n dict_list = js_code.call(\n 'd', res.text.split(\"=\")[1].split(\";\")[0].replace(\n '\"', \"\")) # 执行js解密代码\n data_df = pd.DataFrame(dict_list)\n data_df[\"date\"] = data_df[\"date\"].str.split(\"T\", expand=True).iloc[:, 0]\n data_df.index = pd.to_datetime(data_df[\"date\"])\n del data_df[\"date\"]\n data_df = data_df.astype(\"float\")\n\n r = requests.get(zh_sina_a_stock_amount_url.format(symbol, symbol))\n amount_data_json = demjson.decode(r.text[r.text.find(\"[\"): r.text.rfind(\"]\") + 1])\n amount_data_df = pd.DataFrame(amount_data_json)\n amount_data_df.index = pd.to_datetime(amount_data_df.date)\n del amount_data_df[\"date\"]\n temp_df = pd.merge(data_df, amount_data_df, left_index=True, right_index=True, how=\"left\")\n temp_df.fillna(method=\"ffill\", inplace=True)\n temp_df = temp_df.astype(float)\n temp_df[\"amount\"] = temp_df[\"amount\"] * 10000\n temp_df[\"turnover\"] = temp_df[\"volume\"] / temp_df[\"amount\"]\n temp_df.columns = ['open', 'high', 'low', 'close', 'volume', 'outstanding_share', 'turnover']\n\n if adjust == \"\":\n return temp_df\n\n if adjust == \"hfq\":\n res = requests.get(zh_sina_a_stock_hfq_url.format(symbol))\n hfq_factor_df = pd.DataFrame(\n eval(res.text.split(\"=\")[1].split(\"\\n\")[0])['data'])\n hfq_factor_df.columns = [\"date\", \"hfq_factor\"]\n hfq_factor_df.index = pd.to_datetime(hfq_factor_df.date)\n del hfq_factor_df[\"date\"]\n\n temp_df = pd.merge(\n temp_df, hfq_factor_df, left_index=True, right_index=True, how=\"left\"\n )\n temp_df.fillna(method=\"ffill\", inplace=True)\n temp_df = temp_df.astype(float)\n temp_df[\"open\"] = temp_df[\"open\"] * temp_df[\"hfq_factor\"]\n temp_df[\"high\"] = temp_df[\"high\"] * temp_df[\"hfq_factor\"]\n temp_df[\"close\"] = temp_df[\"close\"] * temp_df[\"hfq_factor\"]\n temp_df[\"low\"] = temp_df[\"low\"] * temp_df[\"hfq_factor\"]\n return temp_df.iloc[:, :-1]\n\n if adjust == \"qfq\":\n res = requests.get(zh_sina_a_stock_qfq_url.format(symbol))\n qfq_factor_df = pd.DataFrame(\n eval(res.text.split(\"=\")[1].split(\"\\n\")[0])['data'])\n qfq_factor_df.columns = [\"date\", \"qfq_factor\"]\n qfq_factor_df.index = pd.to_datetime(qfq_factor_df.date)\n del qfq_factor_df[\"date\"]\n\n temp_df = pd.merge(\n temp_df, qfq_factor_df, left_index=True, right_index=True, how=\"left\"\n )\n temp_df.fillna(method=\"ffill\", inplace=True)\n temp_df = temp_df.astype(float)\n temp_df[\"open\"] = temp_df[\"open\"] / temp_df[\"qfq_factor\"]\n temp_df[\"high\"] = temp_df[\"high\"] / temp_df[\"qfq_factor\"]\n temp_df[\"close\"] = temp_df[\"close\"] / temp_df[\"qfq_factor\"]\n temp_df[\"low\"] = temp_df[\"low\"] / temp_df[\"qfq_factor\"]\n return temp_df.iloc[:, :-1]\n\n if adjust == \"hfq-factor\":\n res = requests.get(zh_sina_a_stock_hfq_url.format(symbol))\n hfq_factor_df = pd.DataFrame(\n eval(res.text.split(\"=\")[1].split(\"\\n\")[0])['data'])\n hfq_factor_df.columns = [\"date\", \"hfq_factor\"]\n hfq_factor_df.index = pd.to_datetime(hfq_factor_df.date)\n del hfq_factor_df[\"date\"]\n return hfq_factor_df\n\n if adjust == \"qfq-factor\":\n res = requests.get(zh_sina_a_stock_qfq_url.format(symbol))\n qfq_factor_df = pd.DataFrame(\n eval(res.text.split(\"=\")[1].split(\"\\n\")[0])['data'])\n qfq_factor_df.columns = [\"date\", \"qfq_factor\"]\n qfq_factor_df.index = pd.to_datetime(qfq_factor_df.date)\n del qfq_factor_df[\"date\"]\n return qfq_factor_df\n\n\nif __name__ == \"__main__\":\n stock_zh_a_daily_hfq_df = stock_zh_a_daily(symbol=\"sh600582\", adjust=\"qfq-factor\")\n print(stock_zh_a_daily_hfq_df)\n stock_zh_a_daily_df = stock_zh_a_daily(symbol=\"sz000613\", adjust=\"qfq\")\n print(stock_zh_a_daily_df)\n stock_zh_a_spot_df = stock_zh_a_spot()\n print(stock_zh_a_spot_df)\n" ]
[ [ "pandas.merge", "pandas.to_datetime", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
FitMachineLearning/FitML
[ "a60f49fce1799ca4b11b48307441325b6272719a", "4ecdaa38127680c41b6d599de8011a5ad1a2c101", "4ecdaa38127680c41b6d599de8011a5ad1a2c101", "4ecdaa38127680c41b6d599de8011a5ad1a2c101", "a60f49fce1799ca4b11b48307441325b6272719a", "a60f49fce1799ca4b11b48307441325b6272719a", "4ecdaa38127680c41b6d599de8011a5ad1a2c101" ]
[ "Pytorch/ActorCritic/agent_and_model.py", "DeepDeterministicSeletiveMemory/RoboschoolHalfCheetah_v1.py", "DeepDeterministicSeletiveMemory/Tensorflow/_Main_Algo_v1.py", "DeepDeterministicSeletiveMemory/LunarLander_v1.py", "Pytorch/DQN/DQN_tut.py", "Pytorch/DQN/Load_Agent.py", "DeepDeterministicSeletiveMemory/Tensorflow/Rocker_lander.py" ]
[ "## DQN Tutorial\r\n## Implementation from https://github.com/FitMachineLearning\r\nimport torch\r\nimport gym\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport numpy as np\r\nfrom dataclasses import dataclass\r\nfrom typing import Any\r\nfrom random import random\r\n\r\n\r\n@dataclass\r\nclass sars:\r\n state: Any\r\n action: Any\r\n reward: float\r\n next_state: Any\r\n done: bool\r\n qval: float\r\n advantage: float = 0.0\r\n\r\nclass DQNAgent:\r\n def __init__(self,actor_model,critic_model):\r\n self.actor_model = actor_model\r\n self.critic_model = critic_model\r\n\r\n def get_actions(self, observations):\r\n # import ipdb; ipdb.set_trace()\r\n guessed_actions = self.actor_model(torch.Tensor(observations).to(self.actor_model.device))\r\n return guessed_actions\r\n\r\n def get_predicted_Q_values(self,observation_and_action):\r\n guessed_Qs = self.critic_model(torch.Tensor(observation_and_action))\r\n return guessed_Qs(-1)[1]\r\n\r\n def update_target_model(self):\r\n self.targetModel.load_state_dict(self.model.state_dict())\r\n\r\nclass ActorModel(nn.Module):\r\n def __init__(self, obs_shape, action_shape,lr):\r\n super(ActorModel,self).__init__()\r\n assert len(obs_shape) ==1, \"This network only works on flat observations\"\r\n self.obs_shape = obs_shape\r\n self.action_shape = action_shape\r\n\r\n # import ipdb; ipdb.set_trace()\r\n self.net = torch.nn.Sequential(\r\n torch.nn.Linear(obs_shape[0],512),\r\n torch.nn.ReLU(),\r\n # torch.nn.Linear(1024,256),\r\n # torch.nn.ReLU(),\r\n torch.nn.Linear(512,action_shape[0])\r\n )\r\n self.opt = optim.Adam(self.net.parameters(),lr=lr)\r\n if torch.cuda.is_available():\r\n print(\"Using CUDA\")\r\n self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cuda:1')\r\n self.to(self.device)\r\n\r\n def forward(self, x):\r\n return self.net(x)\r\n\r\n\r\nclass CriticModel(nn.Module):\r\n def __init__(self, obs_shape, action_shape,lr):\r\n super(CriticModel,self).__init__()\r\n assert len(obs_shape) ==1, \"This network only works on flat observations\"\r\n self.obs_shape = obs_shape\r\n self.action_shape = action_shape\r\n\r\n self.net = torch.nn.Sequential(\r\n torch.nn.Linear(obs_shape[0]+action_shape[0],512),\r\n torch.nn.ReLU(),\r\n # torch.nn.Linear(2048,512),\r\n # torch.nn.ReLU(),\r\n torch.nn.Linear(512,1) # one out put because we are predicting Q values\r\n )\r\n self.opt = optim.Adam(self.net.parameters(),lr=lr)\r\n if torch.cuda.is_available():\r\n print(\"Using CUDA\")\r\n self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cuda:1')\r\n self.to(self.device)\r\n\r\n def forward(self, x):\r\n return self.net(x)\r\n\r\nclass ReplayBuffer:\r\n def __init__(self, buffer_size = 1000):\r\n # self.buffer_size = buffer_size\r\n self.buffer_size = buffer_size\r\n self.buffer = np.empty((buffer_size),dtype=object)\r\n\r\n # self.buffer = []\r\n self.index = 0\r\n\r\n def insert(self, sars):\r\n # self.buffer.append(sars)\r\n # print(\"inserting index \", self.index, \"@\",self.index%self.buffer_size)\r\n if(self.index == 10):\r\n print(\"first 10 \",self.buffer[0:10])\r\n # import ipdb; ipdb.set_trace()\r\n\r\n # if(self.index > self.buffer_size and self.index%self.buffer_size==0):\r\n # print(\"first 10 \",self.buffer[0:10])\r\n # print(\"last 10 \",self.buffer[-10:])\r\n # print(\"\")\r\n # import ipdb; ipdb.set_trace()\r\n self.buffer[self.index%self.buffer_size] = sars\r\n self.index+=1\r\n # self.buffer.append(sars)\r\n # if(len(self.buffer)>self.buffer_size):\r\n # self.buffer = self.buffer[1:]\r\n # # print(\"Clipping Buffer at size\", len(self.buffer))\r\n\r\n def sample(self, num_samples,current_episode_steps):\r\n # assert num_samples < min(len(self.buffer),self.index)\r\n # if num_samples>self.index:\r\n # print(\"sampling n \",min(num_samples,self.index))\r\n a = self.buffer[0:min(self.index,self.buffer_size)]\r\n if len(self.buffer) > 0:\r\n return np.random.choice(a, min(num_samples,self.index))\r\n else:\r\n return []\r\n", "'''\nPyBullet Hopper Walker with\n - Selective Memory\n - Actor Critic\n - Parameter Noising\n - Q as discriminator\nsolution by Michel Aka author of FitML github blog and repository\nhttps://github.com/FitMachineLearning/FitML/\nhttps://www.youtube.com/channel/UCi7_WxajoowBl4_9P0DhzzA/featured\nUpdate\nDeep Network\nStarts Hopping at 200\n\n\n'''\nimport numpy as np\nimport keras\nimport gym\n#import pybullet\n#import pybullet_envs\nimport roboschool\n\n\nimport pygal\nimport os\nimport h5py\n#import matplotlib.pyplot as plt\nimport math\n\nfrom keras.layers.advanced_activations import LeakyReLU, PReLU\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\nPLAY_GAME = False #Set to True if you want to agent to play without training\nuses_critic = True\nuses_parameter_noising = False\nUSE_Q_AS_DISCRIMINATOR = False\n\nnum_env_variables = 26\nnum_env_actions = 6\nnum_initial_observation = 0\nlearning_rate = 0.002\napLearning_rate = 0.001\nlittl_sigma = 0.00006\nbig_sigma = 0.006\nupper_delta = 0.35\nlower_delta = 0.1\nENVIRONMENT_NAME = \"RoboschoolHalfCheetah-v1\"\nversion_name = ENVIRONMENT_NAME + \"ker_v10\"\nweigths_filename = version_name+\"-weights.h5\"\napWeights_filename = version_name+\"-weights-ap.h5\"\n\n\n#range within wich the SmartCrossEntropy action parameters will deviate from\n#remembered optimal policy\nsce_range = 0.2\nb_discount = 0.98\nmax_memory_len = 300000\nexperience_replay_size = 300000\nrandom_every_n = 50\nnum_retries = 60\nstarting_explore_prob = 0.005\ntraining_epochs = 1\ncritic_training_epochs = 1\nmini_batch = 512*4\nload_previous_weights = False\nobserve_and_train = True\nsave_weights = True\nsave_memory_arrays = True\nload_memory_arrays = False\ndo_training = True\nnum_games_to_play = 20000\nrandom_num_games_to_play = num_games_to_play/3\nCLIP_ACTION = True\nHAS_EARLY_TERMINATION_REWARD = False\nEARLY_TERMINATION_REWARD = -2\nHAS_REWARD_SCALLING = True\nREWARD_SCALE = 1/90\nmax_steps = 496\n\n\n\n#Selective memory settings\nsm_normalizer = 20\nsm_memory_size = 10500\n\nlast_game_average = -1000\nlast_best_noisy_game = -1000\nmax_game_average = -1000\nnum_positive_avg_games = 0\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\n\nenv = gym.make(ENVIRONMENT_NAME)\n#env.render(mode=\"human\")\nenv.reset()\n\n\nprint(\"-- Observations\",env.observation_space)\nprint(\"-- actionspace\",env.action_space)\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,num_env_actions))\n\ndef custom_error(y_true, y_pred, Qsa):\n cce=0.001*(y_true - y_pred)*Qsa\n return cce\n\n\n\n#nitialize the Reward predictor model\nQmodel = Sequential()\n#model.add(Dense(num_env_variables+num_env_actions, activation='tanh', input_dim=dataX.shape[1]))\nQmodel.add(Dense(128, activation='relu', input_dim=dataX.shape[1]))\n#Qmodel.add(Dropout(0.5))\nQmodel.add(Dense(128, activation='relu'))\n\n#Qmodel.add(Dense(128, activation='relu'))\n\n#Qmodel.add(Dropout(0.5))\nQmodel.add(Dense(4, activation='relu'))\n#Qmodel.add(Dropout(0.5))\n\nQmodel.add(Dense(dataY.shape[1]))\n#opt = optimizers.adam(lr=learning_rate)\nopt = optimizers.Adadelta()\n\nQmodel.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(128, activation='relu', input_dim=apdataX.shape[1]))\n#action_predictor_model.add(Dropout(0.5))\naction_predictor_model.add(Dense(128, activation='relu'))\n\n#action_predictor_model.add(Dense(128, activation='relu'))\n\n#action_predictor_model.add(Dropout(0.5))\naction_predictor_model.add(Dense(6, activation='relu'))\n#action_predictor_model.add(Dropout(0.5))\n\naction_predictor_model.add(Dense(apdataY.shape[1]))\n#opt2 = optimizers.adam(lr=apLearning_rate)\nopt2 = optimizers.Adadelta()\n\naction_predictor_model.compile(loss='mse', optimizer=opt2, metrics=['accuracy'])\n\n\n\n\n#initialize the action predictor model\nnoisy_model = Sequential()\n#model.add(Dense(num_env_variables+num_env_actions, activation='tanh', input_dim=dataX.shape[1]))\nnoisy_model.add(Dense(2096, activation='relu', input_dim=apdataX.shape[1]))\n#noisy_model.add(Dropout(0.5))\n#noisy_model.add(Dense(50, activation='relu'))\n#noisy_model.add(Dropout(0.5))\nnoisy_model.add(Dense(6, activation='relu'))\n#noisy_model.add(Dropout(0.5))\nnoisy_model.add(Dense(apdataY.shape[1]))\nopt3 = optimizers.Adadelta()\n\nnoisy_model.compile(loss='mse', optimizer=opt3, 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 Qmodel.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\nmemorySA = np.zeros(shape=(1,num_env_variables+num_env_actions))\nmemoryS = np.zeros(shape=(1,num_env_variables))\nmemoryA = np.zeros(shape=(1,1))\nmemoryR = np.zeros(shape=(1,1))\nmemoryRR = np.zeros(shape=(1,1))\nmemoryW = np.zeros(shape=(1,1))\n\nBestGameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\nBestGameS = np.zeros(shape=(1,num_env_variables))\nBestGameA = np.zeros(shape=(1,num_env_actions))\nBestGameR = np.zeros(shape=(1,1))\nBestGameW = np.zeros(shape=(1,1))\n\nif load_memory_arrays:\n if os.path.isfile(version_name+'memorySA.npy'):\n print(\"Memory Files exist. Loading...\")\n memorySA = np.load(version_name+'memorySA.npy')\n memoryRR = np.load(version_name+'memoryRR.npy')\n memoryS = np.load(version_name+'memoryS.npy')\n memoryA = np.load(version_name+'memoryA.npy')\n memoryR = np.load(version_name+'memoryR.npy')\n memoryW = np.load(version_name+'memoryW.npy')\n\n else:\n print(\"No memory Files. Recreating\")\n\n\nmstats = []\nmGames = []\nmAverageScores = []\nmSteps = []\nmAP_Counts = 0\nnum_add_mem = 0\nmAPPicks = []\n\n#------\n\n\n# --- Parameter Noising\ndef add_noise(mu, largeNoise=False):\n\n if largeNoise:\n sig = big_sigma\n else:\n #print(\"Adding Large parameter noise\")\n sig = littl_sigma #Sigma = width of the standard deviaion\n #mu = means\n x = np.random.rand(1) #probability of doing x\n #print (\"x prob \",x)\n if x >0.5:\n return mu + np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))\n else:\n return mu - np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))\n\n# --- Parameter Noising\ndef add_noise_simple(mu, largeNoise=False):\n x = np.random.rand(1) - 0.5 #probability of doing x\n if not largeNoise:\n x = x*big_sigma\n else:\n x = x*big_sigma #Sigma = width of the standard deviaion\n #print (\"x/200\",x,\"big_sigma\",big_sigma)\n return mu + x\n\n\n#add_noise_simple = np.vectorize(add_noise_simple,otypes=[np.float])\nadd_noise = np.vectorize(add_noise,otypes=[np.float])\nadd_noise_simple = np.vectorize(add_noise_simple,otypes=[np.float])\n\n\ndef add_noise_to_model(targetModel,largeNoise = False):\n #noisy_model = keras.models.clone_model(action_predictor_model)\n #noisy_model.set_weights(action_predictor_model.get_weights())\n #print(\"Adding Noise to actor\")\n #largeNoise = last_game_average < memoryR.mean()\n sz = len(noisy_model.layers)\n #if largeNoise:\n # print(\"Setting Large Noise!\")\n for k in range(sz):\n w = targetModel.layers[k].get_weights()\n if np.alen(w) >0 :\n #print(\"k==>\",k)\n w[0] = add_noise(w[0],largeNoise)\n\n targetModel.layers[k].set_weights(w)\n return targetModel\n\n\n\n\ndef reset_noisy_model_weights_to_apWeights(mu):\n x = mu+0.0 #probability of doing x\n return x\n\nreset_noisy_model_weights_to_apWeights = np.vectorize(reset_noisy_model_weights_to_apWeights,otypes=[np.float])\n\ndef reset_noisy_model():\n sz = len(noisy_model.layers)\n #if largeNoise:\n # print(\"Setting Large Noise!\")\n for k in range(sz):\n w = noisy_model.layers[k].get_weights()\n apW = action_predictor_model.layers[k].get_weights()\n\n if np.alen(w) >0:\n w[0] = reset_noisy_model_weights_to_apWeights(apW[0])\n noisy_model.layers[k].set_weights(w)\n #print(\"w\",w)\n #print(\"apW\",apW)\n\ndef reset_noisy_model2():\n action_predictor_model.save_weights(apWeights_filename)\n\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 noisy_model.load_weights(apWeights_filename)\n else:\n print(\"File \",apWeights_filename,\" does not exis. Retraining... \")\n\n# --- Parameter Noising\n\ndef predictTotalRewards(qstate, action):\n qs_a = np.concatenate((qstate,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 = Qmodel.predict(predX[0].reshape(1,predX.shape[1]))\n remembered_total_reward = pred[0][0]\n return remembered_total_reward\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 GetRememberedOptimalPolicyFromNoisyModel(targetModel,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 = targetModel.predict(predX[0].reshape(1,predX.shape[1]))\n r_remembered_optimal_policy = pred[0]\n return r_remembered_optimal_policy\n\ndef addToMemory(reward,mem_mean,memMax,averegeReward,gameAverage,mstd):\n target = mem_mean + math.fabs((memMax-mem_mean)/2)\n d_target_max = math.fabs(memMax-target)\n d_target_reward = math.fabs(reward-target)\n advantage = d_target_reward / d_target_max\n gameAdvantage = math.fabs((averegeReward-gameAverage)/(averegeReward-memMax))\n prob = 0.000000000000005\n if gameAdvantage < 0.05:\n gameAdvantage = 0.000000000000005\n if reward > target:\n return True, 0.0000000005 + (1-0.0000000005)*advantage #*gameAdvantage\n else:\n return False, 0.000000000000005\n\n\ndef scale_weights(memR,memW):\n rmax = memR.max()\n rmin = memR.min()\n reward_range = math.fabs(rmax - rmin )\n if reward_range == 0:\n reward_range = 10\n for i in range(np.alen(memR)):\n memW[i][0] = math.fabs(memR[i][0]-rmin)/reward_range\n memW[i][0] = max(memW[i][0],0.001)\n #print(\"memW %5.2f reward %5.2f rmax %5.2f rmin %5.2f \"%(memW[i][0],memR[i][0],rmax,rmin))\n #print(\"memW\",memW)\n return memW\n\n\ndef pr_actor_experience_replay(memSA,memR,memS,memA,memW,num_epochs=1):\n for t in range(training_epochs):\n tSA = (memSA)+0.0\n tR = (memR)+0.0\n tX = (memS)+0.0\n tY = (memA)+0.0\n tW = (memW)+0.0\n tS = memW +0.0\n\n treshold = memoryR.mean()\n gameAverage = memoryR.mean()\n gameDistance = math.fabs(memoryW.max() - memoryR.mean())\n gameTreshold = memoryW.mean() + gameDistance*0\n\n #print(\"gameMean\",tS.mean(),\"gameMax\",tS.max(),\"gameTreshold\",gameTreshold)\n\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n tR = tR[train_A,:]\n tS = tS[train_A,:]\n\n train_C = np.arange(np.alen(tR))\n #train_C = train_C[tR.flatten()>treshold]\n tX = tX[train_C,:]\n tY = tY[train_C,:]\n tW = tW[train_C,:]\n tR = tR[train_C,:]\n tS = tS[train_C,:]\n\n\n\n\n tX_train = np.zeros(shape=(1,num_env_variables))\n tY_train = np.zeros(shape=(1,num_env_actions))\n for i in range(np.alen(tR)):\n pr = predictTotalRewards(tX[i],GetRememberedOptimalPolicy(tX[i]))\n #print (\"tR[i]\",tR[i],\"pr\",pr)\n d = math.fabs( memoryR.max() - pr)\n tW[i]= 0.0000000000000005\n if (tR[i]>pr ):\n tW[i]=0.15\n #if (tR[i]>pr and tS[i]>gameAverage):\n # tW[i]=0.25\n if (tR[i]>pr + d*0.5):\n tW[i]=1\n #if (tR[i]>pr+d*0.005 and tR[i]>game_max) :\n # tW[i] = 1\n if tW[i]> np.random.rand(1):\n tX_train = np.vstack((tX_train,tX[i]))\n tY_train = np.vstack((tY_train,tY[i]))\n\n\n tX_train = tX_train[1:]\n tY_train = tY_train[1:]\n print(\"%8d were better After removing first element\"%np.alen(tX_train))\n if np.alen(tX_train)>0:\n action_predictor_model.fit(tX_train,tY_train, batch_size=mini_batch, nb_epoch=1,verbose=0)\n\n\n\n\ndef actor_experience_replay(memSA,memR,memS,memA,memW,num_epochs=1):\n for t in range(training_epochs):\n tSA = (memSA)+0.0\n tR = (memR)+0.0\n tX = (memS)+0.0\n tY = (memA)+0.0\n tW = (memW)+0.0\n tS = memW +0.0\n\n stdDev = np.std(tR)\n gameStdDev = np.std(tS)\n\n distance = math.fabs(memoryR.max()-memoryR.mean())\n #treshold = memoryR.mean()+ distance*0.75\n treshold = memoryR.mean()+ stdDev*1.3\n gameAverage = memoryR.mean()\n gameDistance = math.fabs(memoryW.max() - memoryR.mean())\n gameTreshold = memoryW.mean() + gameStdDev*0\n\n #print(\"gameMean\",tS.mean(),\"gameMax\",tS.max(),\"gameTreshold\",gameTreshold)\n\n train_C = np.arange(np.alen(tR))\n #train_C = train_C[tS.flatten()> gameTreshold] # Only take games that are above gameTreshold\n tX = tX[train_C,:]\n tY = tY[train_C,:]\n tW = tW[train_C,:]\n tR = tR[train_C,:]\n tS = tS[train_C,:]\n\n\n\n #ßprint(\"TY.shape\",tY.shape[0], \"exp replay\",experience_replay_size,\"np \", np.alen(tR))\n\n if np.alen(tR) <= 0:\n break\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n tR = tR[train_A,:]\n tS = tS[train_A,:]\n\n\n #print(\"gameMean\",tS.mean(),\"gameMax\",tS.max(),\"gameTreshold\",gameTreshold)\n\n train_D = np.arange(np.alen(tR))\n train_D = train_D[tR.flatten()>treshold] # Only take steps with rewards above threshold\n tX = tX[train_D,:]\n tY = tY[train_D,:]\n tW = tW[train_D,:]\n tR = tR[train_D,:]\n tS = tS[train_D,:]\n\n\n tX_train = tX\n tY_train = tY\n #if t%training_epochs==0:\n print(\"%8d were better After removing first element\"%np.alen(tX_train), \"Upper_cut\",memoryR.mean()+stdDev,\"gameStdDev\",memoryW.mean()+gameStdDev)\n if np.alen(tX_train)>0:\n action_predictor_model.fit(tX_train,tY_train, batch_size=mini_batch, nb_epoch=20,verbose=0)\n\n\n\ndef train_noisy_actor():\n tX = (memoryS)\n tY = (memoryA)\n tW = (memoryW)\n\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tY) )))\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n\n noisy_model.fit(tX,tY, batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)\n\n\ndef add_controlled_noise(targetModel,big_sigma,largeNoise = False):\n tR = (memoryR)\n tX = (memoryS)\n tY = (memoryA)\n tW = (memoryW)\n train_C = np.random.randint(tY.shape[0],size=100)\n\n tX = tX[train_C,:]\n tY_old = tY[train_C,:]\n tY_new = tY[train_C,:]\n diffs = np.zeros(np.alen(tX))\n delta = 1000\n deltaCount = 0\n\n for i in range(np.alen(tX)):\n a = GetRememberedOptimalPolicyFromNoisyModel(noisy_model,tX[i])\n a = a.flatten()\n #print(\"Output Before noise \",a)\n\n while ( delta > upper_delta or delta < lower_delta) and deltaCount <3:\n #noisy_model.set_weights(action_predictor_model.get_weights())\n reset_noisy_model()\n targetModel = noisy_model\n targetModel = add_noise_to_model(noisy_model,largeNoise)\n\n\n for i in range(np.alen(tX)):\n b = GetRememberedOptimalPolicyFromNoisyModel(targetModel,tX[i])\n b = b.flatten()\n\n c = np.abs(a-b)\n delta = c.mean()\n\n deltaCount+=1\n if delta > upper_delta:\n big_sigma = big_sigma *0.9\n #print(\"Delta\",delta,\" out of bound adjusting big_sigma\", big_sigma)\n\n if delta < lower_delta:\n big_sigma = big_sigma *1.1\n #print(\"Delta\",delta,\" out of bound adjusting big_sigma\", big_sigma)\n #if delta > 3 or delta <0.01:\n # print(\"Delta\",delta,\" out of bound adjusting big_sigma\", big_sigma, \"to\",1/delta)\n # big_sigma = 1 / delta\n print(\"Tried x time \", deltaCount,\"delta =\", delta,\"big_sigma \",big_sigma)\n return targetModel,big_sigma\n\n\n\n\n#Play the game 500 times\nfor game in range(num_games_to_play):\n gameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\n gameS = np.zeros(shape=(1,num_env_variables))\n gameA = np.zeros(shape=(1,num_env_actions))\n gameR = np.zeros(shape=(1,1))\n gameW = np.zeros(shape=(1,1))\n #Get the Q state\n qs = env.reset()\n mAP_Counts = 0\n num_add_mem = 0\n #print(\"qs \", qs)\n is_noisy_game = False\n\n #noisy_model.set_weights(action_predictor_model.get_weights())\n\n #Add noise to Actor\n if game > num_initial_observation and uses_parameter_noising:\n is_noisy_game = False\n #print(\"Adding Noise\")\n if (game%2==0 ):\n is_noisy_game = True\n if True or last_best_noisy_game < memoryR.mean() or game%6==0:\n print(\"Adding BIG Noise\")\n #noisy_model = keras.models.clone_model(action_predictor_model)\n reset_noisy_model()\n noisy_model,big_sigma = add_controlled_noise(noisy_model,big_sigma,True)\n #last_best_noisy_game = -1000\n '''\n else:\n print(\"Adding Small Noise\")\n #print(\"Not Changing weights last_best_noisy_game\", last_best_noisy_game,\" mean \",memoryR.mean())\n reset_noisy_model()\n add_controlled_noise(noisy_model,False)\n '''\n\n for step in range (5000):\n\n if PLAY_GAME:\n remembered_optimal_policy = GetRememberedOptimalPolicy(qs)\n a = remembered_optimal_policy\n elif 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/random_num_games_to_play)*game\n\n if game > random_num_games_to_play:\n prob = 0.000001\n #Chose between prediction and chance\n if prob < explore_prob or game%random_every_n==1:\n #take a random action\n a = env.action_space.sample()\n\n else:\n #print(\"Using Actor\")\n if is_noisy_game and uses_parameter_noising:\n remembered_optimal_policy = GetRememberedOptimalPolicyFromNoisyModel(noisy_model,qs)\n else:\n remembered_optimal_policy = GetRememberedOptimalPolicy(qs)\n a = remembered_optimal_policy\n\n if uses_critic:\n #print(\"Using critric\")\n stock = np.zeros(num_retries)\n stockAction = np.zeros(shape=(num_retries,num_env_actions))\n for i in range(num_retries):\n stockAction[i] = env.action_space.sample()\n stock[i] = predictTotalRewards(qs,stockAction[i])\n best_index = np.argmax(stock)\n randaction = stockAction[best_index]\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 mAP_Counts += 1\n #print(\" | selecting remembered_optimal_policy \",a)\n else:\n a = randaction\n #print(\" - selecting generated optimal policy \",a)\n\n if CLIP_ACTION:\n for i in range (np.alen(a)):\n if a[i] < -1: a[i]=-0.99999999999\n if a[i] > 1: a[i] = 0.99999999999\n\n\n\n\n\n\n qs_a = np.concatenate((qs,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 env.render()\n\n if HAS_EARLY_TERMINATION_REWARD and done and step<max_steps-3:\n r = EARLY_TERMINATION_REWARD\n\n if HAS_REWARD_SCALLING:\n r= r * REWARD_SCALE #reward scalling to from [-1,1] to [-100,100]\n #r=r*100\n if step ==0:\n gameSA[0] = qs_a\n gameS[0] = qs\n gameR[0] = np.array([r])\n gameA[0] = np.array([r])\n gameW[0] = np.array([0.000000005])\n else:\n gameSA= np.vstack((gameSA, qs_a))\n gameS= np.vstack((gameS, qs))\n gameR = np.vstack((gameR, np.array([r])))\n gameA = np.vstack((gameA, np.array([a])))\n gameW = np.vstack((gameW, np.array([0.000000005])))\n\n if step > max_steps:\n done = True\n\n if done :\n tempGameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\n tempGameS = np.zeros(shape=(1,num_env_variables))\n tempGameA = np.zeros(shape=(1,num_env_actions))\n tempGameR = np.zeros(shape=(1,1))\n tempGameRR = np.zeros(shape=(1,1))\n tempGameW = np.zeros(shape=(1,1))\n\n #Calculate Q values from end to start of game\n #mstats.append(step)\n for i in range(0,gameR.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 gameR[(gameR.shape[0]-1)-i][0] = gameR[(gameR.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 gameR[(gameR.shape[0]-1)-i][0] = gameR[(gameR.shape[0]-1)-i][0]+b_discount*gameR[(gameR.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\n if memoryR.shape[0] ==1:\n memorySA = gameSA\n memoryR = gameR\n memoryA = gameA\n memoryS = gameS\n memoryRR = gameR\n memoryW = gameW\n\n tempGameA = tempGameA[1:]\n tempGameS = tempGameS[1:]\n tempGameRR = tempGameRR[1:]\n tempGameR = tempGameR[1:]\n tempGameSA = tempGameSA[1:]\n tempGameW = tempGameW[1:]\n\n\n for i in range(gameR.shape[0]):\n tempGameSA = np.vstack((tempGameSA,gameSA[i]))\n tempGameR = np.vstack((tempGameR,gameR[i]))\n\n tempGameA = np.vstack((tempGameA,gameA[i]))\n tempGameS = np.vstack((tempGameS,gameS[i]))\n tempGameRR = np.vstack((tempGameRR,gameR[i]))\n tempGameW = np.vstack((tempGameW,gameR.mean()))\n\n\n #train actor network based on last rollout\n if game>3:\n tX = (tempGameS)\n tY = (tempGameA)\n tW = (tempGameW)\n #action_predictor_model.fit(tX,tY,sample_weight=tW.flatten(), batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)\n\n\n\n if memoryR.shape[0] ==1:\n memoryA = tempGameA\n memoryS = tempGameS\n memoryRR = tempGameRR\n memoryR = tempGameR\n memorySA = tempGameSA\n memoryW = tempGameW\n else:\n #Add experience to memory\n memoryS = np.concatenate((memoryS,tempGameS),axis=0)\n memoryRR = np.concatenate((memoryRR,tempGameRR),axis=0)\n memoryA = np.concatenate((memoryA,tempGameA),axis=0)\n memorySA = np.concatenate((memorySA,tempGameSA),axis=0)\n\n memoryR = np.concatenate((memoryR,tempGameR),axis=0)\n memoryW = np.concatenate((memoryW,tempGameW),axis=0)\n\n\n if gameR.mean() > max_game_average :\n max_game_average = gameR.mean()\n\n #if memory is full remove first element\n if np.alen(memoryR) >= max_memory_len:\n memorySA = memorySA[gameR.shape[0]:]\n memoryR = memoryR[gameR.shape[0]:]\n memoryA = memoryA[gameR.shape[0]:]\n memoryS = memoryS[gameR.shape[0]:]\n memoryRR = memoryRR[gameR.shape[0]:]\n memoryW = memoryW[gameR.shape[0]:]\n\n\n qs=s\n\n if done and game > num_initial_observation and not PLAY_GAME:\n last_game_average = gameR.mean()\n if is_noisy_game and last_game_average > memoryR.mean():\n last_best_noisy_game = last_game_average\n #if game >3:\n #actor_experience_replay(gameSA,gameR,gameS,gameA,gameW,1)\n\n if game > 3 and game %1 ==0:\n # train on all memory\n #print(\"Experience Replay\")\n #for i in range(3):\n if USE_Q_AS_DISCRIMINATOR:\n print(\"Experience Replay with Q as discriminator\")\n pr_actor_experience_replay(memorySA,memoryR,memoryS,memoryA,memoryW,training_epochs)\n else:\n print(\"Experience Replay with stdVar as discriminator\")\n actor_experience_replay(memorySA,memoryR,memoryS,memoryA,memoryW,training_epochs)\n if game > 3 and game %1 ==0 and uses_critic:\n for t in range(critic_training_epochs):\n tSA = (memorySA)\n tR = (memoryR)\n train_A = np.random.randint(tR.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n tR = tR[train_A,:]\n tSA = tSA [train_A,:]\n #print(\"Training Critic n elements =\", np.alen(tR))\n Qmodel.fit(tSA,tR, batch_size=mini_batch, nb_epoch=1,verbose=0)\n if game > 3 and game %5 ==-1 and uses_parameter_noising:\n print(\"Training noisy_actor\")\n train_noisy_actor()\n #Reinforce training with best game\n\n\n if done and game >= num_initial_observation and not PLAY_GAME:\n if save_weights and game%20 == 0 and game >35:\n #Save model\n #print(\"Saving weights\")\n Qmodel.save_weights(weigths_filename)\n action_predictor_model.save_weights(apWeights_filename)\n\n if save_memory_arrays and game%20 == 0 and game >35:\n np.save(version_name+'memorySA.npy',memorySA)\n np.save(version_name+'memoryRR.npy',memoryRR)\n np.save(version_name+'memoryS.npy',memoryS)\n np.save(version_name+'memoryA.npy',memoryA)\n np.save(version_name+'memoryR.npy',memoryR)\n np.save(version_name+'memoryW.npy',memoryW)\n\n\n\n\n if done:\n\n rScale = 1/REWARD_SCALE\n\n if gameR.mean() >0:\n num_positive_avg_games += 1\n if game%1==0:\n #print(\"Training Game #\",game,\"last everage\",memoryR.mean(),\"max_game_average\",max_game_average,,\"game mean\",gameR.mean(),\"memMax\",memoryR.max(),\"memoryR\",memoryR.shape[0], \"SelectiveMem Size \",memoryRR.shape[0],\"Selective Mem mean\",memoryRR.mean(axis=0)[0], \" steps = \", step )\n if is_noisy_game:\n print(\"Noisy Game # %7d avgScore %8.3f last_game_avg %8.3f max_game_avg %8.3f memory size %8d memMax %8.3f steps %5d pos games %5d\" % (game, memoryR.mean(), last_game_average, memoryW.max() , memoryR.shape[0], memoryR.max(), step,num_positive_avg_games ) )\n else:\n print(\"Reg Game # %7d avgScore %8.3f last_game_avg %8.3f max_game_avg %8.3f memory size %8d memMax %8.3f steps %5d pos games %5d\" % (game, memoryR.mean(), last_game_average, memoryW.max() , memoryR.shape[0], memoryR.max(), step ,num_positive_avg_games ) )\n\n if game%5 ==0 and np.alen(memoryR)>1000:\n mGames.append(game)\n mSteps.append(step/1000*100)\n mAPPicks.append(mAP_Counts/step*100)\n mAverageScores.append(max(memoryR.mean()*rScale, -150))\n bar_chart = pygal.HorizontalLine()\n bar_chart.x_labels = map(str, mGames) # Then create a bar graph object\n bar_chart.add('Average score', mAverageScores) # Add some values\n bar_chart.add('percent actor picks ', mAPPicks) # Add some values\n bar_chart.add('percent steps complete ', mSteps) # Add some values\n\n\n bar_chart.render_to_file(version_name+'Performance2_bar_chart.svg')\n\n break\n\n\nplt.plot(mstats)\nplt.show()\n\nif save_weights:\n #Save model\n print(\"Saving weights\")\n Qmodel.save_weights(weigths_filename)\n action_predictor_model.save_weights(apWeights_filename)\n", "'''\nHopper with\n - Selective Memory\n - Actor Critic\n - Parameter Noising\n - Q as discriminator\nsolution by Michel Aka author of FitML github blog and repository\nhttps://github.com/FitMachineLearning/FitML/\nhttps://www.youtube.com/channel/UCi7_WxajoowBl4_9P0DhzzA/featured\nUpdate\nDeep Network\nStarts to Land at episode 400\n\nAdagrad\n0.99 delta\n0.1 dropout\n\n'''\n#from environments.rocketlander import RocketLander\nimport tensorflow as tf\nimport numpy as np\nimport gym\nimport pybullet\nimport pybullet_envs\n\nimport pygal\nimport os\nimport h5py\n#import matplotlib.pyplot as plt\nimport math\n\nfrom keras import optimizers\n\n\nPLAY_GAME = False #Set to True if you want to agent to play without training\nuses_critic = True\nuses_parameter_noising = False\n\nnum_env_variables = 15\nnum_env_actions = 3\nnum_initial_observation = 8\nlearning_rate = 0.003\napLearning_rate = 0.001\nbig_sigma = 0.0006\nlittl_sigma = 0.00006\nupper_delta = 0.0015\nlower_delta = 0.0010\nENVIRONMENT_NAME = \"HopperBulletEnv-v0\"\nversion_name = ENVIRONMENT_NAME + \"With_PN_v10\"\nweigths_filename = version_name+\"-weights.h5\"\napWeights_filename = version_name+\"-weights-ap.h5\"\n\n\n#range within wich the SmartCrossEntropy action parameters will deviate from\n#remembered optimal policy\nsce_range = 0.2\nb_discount = 0.99\nmax_memory_len = 100000\nexperience_replay_size = 25000\nrandom_every_n = 50\nnum_retries = 60\nstarting_explore_prob = 0.05\ntraining_epochs = 1\nmini_batch = 512\nload_previous_weights = False\nobserve_and_train = True\nsave_weights = True\nsave_memory_arrays = True\nload_memory_arrays = False\ndo_training = True\nnum_games_to_play = 6000\nrandom_num_games_to_play = num_games_to_play\nmax_steps =995\n\n#Selective memory settings\nsm_normalizer = 20\nsm_memory_size = 10500\n\nlast_game_average = -1000\nlast_best_noisy_game = -1000\nmax_game_average = -1000\nnoisy_game_no_longer_valid = False\n\n\n#Create testing enviroment\n\nsettings = {'Side Engines': True,\n 'Clouds': True,\n 'Vectorized Nozzle': True,\n 'Starting Y-Pos Constant': 1,\n 'Initial Force': 'random'} # (6000, -10000)}\n\n#env = RocketLander(settings)\nenv = gym.make(ENVIRONMENT_NAME)\n\n#env.refresh(render=True)\nenv.render(mode=\"human\")\nenv.reset()\n\n\n\nprint(\"-- Observations\",env.observation_space)\nprint(\"-- actionspace\",env.action_space)\n\n#initialize training matrix with random states and actions\n#dataX = np.random.random(( 5,num_env_variables+num_env_actions ))\ndataX = tf.placeholder(\"float\", [None, num_env_variables+num_env_actions])\n\n#Only one output for the total score / reward\n#dataY = np.random.random((5,1))\ndataY = tf.placeholder(\"float\", [None, 1])\n\n\n#initialize training matrix with random states and actions\n#apdataX = np.random.random(( 5,num_env_variables ))\napdataX = tf.placeholder(\"float\", [None, num_env_variables])\n#apdataY = np.random.random((5,num_env_actions))\napdataY = tf.placeholder(\"float\", [None, num_env_actions])\n\n\ndef init_weights(shape):\n return tf.Variable(tf.random_normal(shape, stddev=0.01))\n\ndef Qmodel(X, w_h,w_h2,w_h3, w_o):\n h = tf.nn.leaky_relu(tf.matmul(X, w_h)) # this is a basic mlp, think 2 stacked logistic regressions\n h2 = tf.nn.leaky_relu(tf.matmul(h, w_h2)) # this is a basic mlp, think 2 stacked logistic regressions\n h3 = tf.nn.leaky_relu(tf.matmul(h2, w_h3)) # this is a basic mlp, think 2 stacked logistic regressions\n return tf.matmul(h3, w_o) # note that we dont take the softmax at the end because our cost fn does that for us\n\ndef apModel(X, apw_h,apw_h2,apw_h3, apw_o):\n h = tf.nn.leaky_relu(tf.matmul(X, apw_h)) # this is a basic mlp, think 2 stacked logistic regressions\n h2 = tf.nn.leaky_relu(tf.matmul(h, apw_h2)) # this is a basic mlp, think 2 stacked logistic regressions\n h3 = tf.nn.leaky_relu(tf.matmul(h2, apw_h3)) # this is a basic mlp, think 2 stacked logistic regressions\n return tf.matmul(h3, apw_o) # note that we dont take the softmax at the end because our cost fn does that for us\n\n''' QModel '''\nQw_h = init_weights([num_env_variables+num_env_actions, 32]) # create symbolic variables\nQw_h2 = init_weights([32, 32]) # create symbolic variables\nQw_h3 = init_weights([32, 32]) # create symbolic variables\nQw_o = init_weights([32, 1])\n\nQpy_x = Qmodel(dataX, Qw_h,Qw_h2,Qw_h3, Qw_o)\n\n\nQcost = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(dataY, Qpy_x))))\nQoptimizer = tf.train.AdadeltaOptimizer(1.,0.9,1e-6)\nQtrain_op = Qoptimizer.minimize(Qcost)\n\n''' apModel '''\napw_h = init_weights([num_env_variables, 32]) # create symbolic variables\napw_h2 = init_weights([32, 32]) # create symbolic variables\napw_h3 = init_weights([32, 32]) # create symbolic variable\napw_o = init_weights([32, num_env_actions])\n\nappy_x = apModel(apdataX, apw_h,apw_h2,apw_h3, apw_o)\n\napcost = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(apdataY, appy_x))))\napOptimizer = tf.train.AdadeltaOptimizer(1.,0.9,1e-6)\naptrain_op = apOptimizer.minimize(apcost)\n\n\n''' naModel '''\nnaw_h = init_weights([num_env_variables, 32]) # create symbolic variables\nnaw_h2 = init_weights([32, 32]) # create symbolic variables\nnaw_h3 = init_weights([32, 32]) # create symbolic variable\nnaw_o = init_weights([32, num_env_actions])\n\nnapy_x = apModel(apdataX, naw_h, naw_h2, naw_h3, naw_o)\n\nnacost = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(apdataY, napy_x))))\nnaOptimizer = tf.train.AdadeltaOptimizer(1.,0.9,1e-6)\nnatrain_op = apOptimizer.minimize(apcost)\n#natrain_op = tf.train.AdadeltaOptimizer(1).minimize(nacost)\n\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n\n''' LOAD MODEL\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 Qmodel.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\nmemorySA = np.zeros(shape=(1,num_env_variables+num_env_actions))\nmemoryS = np.zeros(shape=(1,num_env_variables))\nmemoryA = np.zeros(shape=(1,1))\nmemoryR = np.zeros(shape=(1,1))\nmemoryRR = np.zeros(shape=(1,1))\nmemoryW = np.zeros(shape=(1,1))\n\nBestGameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\nBestGameS = np.zeros(shape=(1,num_env_variables))\nBestGameA = np.zeros(shape=(1,num_env_actions))\nBestGameR = np.zeros(shape=(1,1))\nBestGameW = np.zeros(shape=(1,1))\n\nif load_memory_arrays:\n if os.path.isfile(version_name+'memorySA.npy'):\n print(\"Memory Files exist. Loading...\")\n memorySA = np.load(version_name+'memorySA.npy')\n memoryRR = np.load(version_name+'memoryRR.npy')\n memoryS = np.load(version_name+'memoryS.npy')\n memoryA = np.load(version_name+'memoryA.npy')\n memoryR = np.load(version_name+'memoryR.npy')\n memoryW = np.load(version_name+'memoryW.npy')\n\n else:\n print(\"No memory Files. Recreating\")\n\n\nmstats = []\nmGames = []\nmAverageScores = []\nmSteps = []\nmAP_Counts = 0\nnum_add_mem = 0\nmAPPicks = []\n\ndef GenerateSampleAction(dim=3):\n retVal = np.random.rand(3)\n retVal = retVal -0.5\n retVal = retVal * 2\n return retVal\n\n# --- Parameter Noising\ndef add_noise(mu, largeNoise=False):\n\n if not largeNoise:\n sig = littl_sigma\n else:\n #print(\"Adding Large parameter noise\")\n sig = big_sigma #Sigma = width of the standard deviaion\n #mu = means\n x = np.random.rand(1) #probability of doing x\n #print (\"x prob \",x)\n if x >0.5:\n return mu + np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))\n else:\n return mu - np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))\n\n# --- Parameter Noising\ndef add_noise_simple(mu, largeNoise=False):\n x = np.random.rand(1) - 0.5 #probability of doing x\n if not largeNoise:\n x = x*littl_sigma\n else:\n x = x*big_sigma #Sigma = width of the standard deviaion\n #print (\"x/200\",x)\n return mu + x\n\n\n#add_noise_simple = np.vectorize(add_noise_simple,otypes=[np.float])\nadd_noise = np.vectorize(add_noise,otypes=[np.float])\nadd_noise_simple = np.vectorize(add_noise_simple,otypes=[np.float])\n\n\n\ndef add_noise_TF(largeNoise = False):\n variables_names =[v.name for v in tf.trainable_variables()]\n values = sess.run(variables_names)\n #for k,v in zip(variables_names, values):\n # if(k==naw_h.name):\n # print(k, v)\n for k,v in zip(variables_names, values):\n if(k==naw_h.name):\n v2=add_noise_simple(v,True)\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op = tf.assign(naw_h,v2)\n sess.run(assign_op)\n\n #for k,v in zip(variables_names, values):\n # if(k==naw_o.name):\n # print(k, v)\n for k,v in zip(variables_names, values):\n if(k==naw_h2.name):\n v2=add_noise_simple(v,True)\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op2 = tf.assign(naw_h2,v2)\n sess.run(assign_op2)\n\n #for k,v in zip(variables_names, values):\n # if(k==naw_o.name):\n # print(k, v)\n for k,v in zip(variables_names, values):\n if(k==naw_h3.name):\n v2=add_noise_simple(v,True)\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op2 = tf.assign(naw_h3,v2)\n sess.run(assign_op2)\n\n #for k,v in zip(variables_names, values):\n # if(k==naw_o.name):\n # print(k, v)\n for k,v in zip(variables_names, values):\n if(k==naw_o.name):\n v2=add_noise_simple(v,True)\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op2 = tf.assign(naw_o,v2)\n sess.run(assign_op2)\n '''\n variables_names =[v.name for v in tf.trainable_variables()]\n values = sess.run(variables_names)\n for k,v in zip(variables_names, values):\n if(k==naw_h.name):\n print(k, v)\n '''\n return None\n\ndef reset_noisy_model_TF():\n variables_names =[v.name for v in tf.trainable_variables()]\n values = sess.run(variables_names)\n\n ## RESET FIRST LAYER\n for k,v in zip(variables_names, values):\n if(k==apw_h.name):\n v2=v+0.000000000000000001\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op = tf.assign(naw_h,v2)\n sess.run(assign_op)\n\n ## RESET FIRST LAYER\n for k,v in zip(variables_names, values):\n if(k==apw_h2.name):\n v2=v+0.000000000000000001\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op = tf.assign(naw_h2,v2)\n sess.run(assign_op)\n\n ## RESET LAST LAYER\n for k,v in zip(variables_names, values):\n if(k==apw_o.name):\n v2=v+0.000000000000000001\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op = tf.assign(naw_o,v2)\n sess.run(assign_op)\n\n '''\n variables_names =[v.name for v in tf.trainable_variables()]\n values = sess.run(variables_names)\n for k,v in zip(variables_names, values):\n if(k==naw_h.name):\n print(k, v)\n '''\n return None\n\n\n# --- Parameter Noising\n\ndef predictTotalRewards(qstate, action):\n qs_a = np.concatenate((qstate,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 = Qmodel.predict(predX[0].reshape(1,predX.shape[1]))\n inputVal = predX[0].reshape(1,predX.shape[1])\n pred = sess.run(Qpy_x, feed_dict={dataX: inputVal})\n remembered_total_reward = pred[0][0]\n return remembered_total_reward\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\n inputVal = predX[0].reshape(1,predX.shape[1])\n pred = sess.run(appy_x, feed_dict={apdataX: inputVal})\n r_remembered_optimal_policy = pred[0]\n return r_remembered_optimal_policy\n\ndef GetRememberedOptimalPolicyFromNoisyModel(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 = targetModel.predict(predX[0].reshape(1,predX.shape[1]))\n inputVal = predX[0].reshape(1,predX.shape[1])\n pred = sess.run(napy_x, feed_dict={apdataX: inputVal})\n\n r_remembered_optimal_policy = pred[0]\n return r_remembered_optimal_policy\n\ndef addToMemory(reward,mem_mean,memMax,averegeReward,gameAverage,mstd):\n target = mem_mean + math.fabs((memMax-mem_mean)/2)\n d_target_max = math.fabs(memMax-target)\n d_target_reward = math.fabs(reward-target)\n advantage = d_target_reward / d_target_max\n gameAdvantage = math.fabs((averegeReward-gameAverage)/(averegeReward-memMax))\n prob = 0.000000000000005\n if gameAdvantage < 0.05:\n gameAdvantage = 0.000000000000005\n if reward > target:\n return True, 0.0000000005 + (1-0.0000000005)*advantage #*gameAdvantage\n else:\n return False, 0.000000000000005\n\n\n\ndef pr_actor_experience_replay(memSA,memR,memS,memA,memW,num_epoch=1):\n for num_epoch in range(training_epochs):\n tSA = (memSA)+0.0\n tR = (memR)+0.0\n tX = (memS)+0.0\n tY = (memA)+0.0\n tW = (memW)+0.0\n tS = memW +0.0\n\n game_max = tW.max()+0.0\n gameAverage = memR.mean()\n treshold = memR.flatten()[-15000:].mean()\n\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n tSA = tSA[train_A,:]\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n tR = tR[train_A,:]\n tS = tS[train_A,:]\n\n tX_train = np.zeros(shape=(1,num_env_variables))\n tY_train = np.zeros(shape=(1,num_env_actions))\n for i in range(np.alen(tR)):\n pr = predictTotalRewards(tX[i],GetRememberedOptimalPolicy(tX[i]))\n #print (\"tR[i]\",tR[i],\"pr\",pr)\n d = math.fabs( memoryR.max() - pr)\n tW[i]= 0.0000000000000005\n if (tR[i]>pr ):\n tW[i]=0.15\n if (tR[i]>pr and tS[i]>treshold):\n tW[i]=0.55\n if (tR[i]>pr+d*0.005 and tR[i]>game_max) :\n tW[i] = 1\n if tW[i]> np.random.rand(1):\n tX_train = np.vstack((tX_train,tX[i]))\n tY_train = np.vstack((tY_train,tY[i]))\n\n\n tX_train = tX_train[1:]\n tY_train = tY_train[1:]\n print(num_epoch,\"%8d were better After removing first element\"%np.alen(tX_train))\n if np.alen(tX_train)>0:\n #action_predictor_model.fit(tX_train,tY_train, batch_size=mini_batch, nb_epoch=num_epochs,verbose=0)\n for t in range(25):\n sess.run(aptrain_op, feed_dict={apdataX: tX_train, apdataY: tY_train})\n\n\n\n\n\ndef actor_experience_replay(memSA,memR,memS,memA,memW,num_epoch=1):\n tSA = (memSA)\n tR = (memR)\n tX = (memS)\n tY = (memA)\n tW = (memW)\n\n target = tR.mean() #+ math.fabs( tR.mean() - tR.max() )/2 #+ math.fabs( tR.mean() - tR.max() )/4\n train_C = np.arange(np.alen(tR))\n train_C = train_C[tR.flatten()>target]\n tX = tX[train_C,:]\n tY = tY[train_C,:]\n tW = tW[train_C,:]\n tR = tR[train_C,:]\n\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n tR = tR[train_A,:]\n\n train_B = np.arange(np.alen(tR))\n\n tX_train = np.zeros(shape=(1,num_env_variables))\n tY_train = np.zeros(shape=(1,num_env_actions))\n for i in range(np.alen(train_B)):\n #pr = predictTotalRewards(tX[i],tY[i])\n ''' YOU CAN\"T USE predictTotalRewards\n IF YOU DON\"T TRAIN THE QMODEL\n\n if tR[i][0] < pr:\n tW[i][0] = -1\n else:\n '''\n d = math.fabs( memoryR.max() - target)\n tW[i] = math.fabs(tR[i]-(target+0.000000000005)) / d\n #tW[i] = math.exp(1-(1/tW[i]**2))\n\n\n tW[i]= 0.0000000000000005\n if (tR[i]>target):\n tW[i]=0.5\n if (tR[i]>max_game_average):\n tW[i] = 1\n\n if tW[i]> np.random.rand(1):\n tX_train = np.vstack((tX_train,tX[i]))\n tY_train = np.vstack((tY_train,tY[i]))\n\n\n #print (\"tW\",tW[i],\"exp\", math.exp(1-(1/tW[i]**2)))\n #tW[i] = math.exp(1-(1/tW[i]**2))\n #tW[i] = 1\n #print(\"tW[i] %3.1f tR %3.2f target %3.2f max_game_average %3.2f \"%(tW[i],tR[i],target,max_game_average))\n '''\n train_B = train_B[tW.flatten()>0]\n\n #print(\"%8d were better results than pr\"%np.alen(tX_train))\n\n tX = tX[train_B,:]\n tY = tY[train_B,:]\n tW = tW[train_B,:]\n tR = tR[train_B,:]\n #print(\"tW\",tW)\n '''\n #print(\"%8d were better results than pr\"%np.alen(tX_train))\n ''' REMOVE FIRST ELEMENT BEFORE TRAINING '''\n tX_train = tX_train[1:]\n tY_train = tY_train[1:]\n #print(\"%8d were better After removing first element\"%np.alen(tX_train))\n if np.alen(tX_train)>0:\n #tW = scale_weights(tR,tW)\n #print(\"# setps short listed \", np.alen(tR))\n\n #action_predictor_model.fit(tX_train,tY_train, batch_size=mini_batch, nb_epoch=num_epochs,verbose=0)\n for num_epoch in range(training_epochs):\n sess.run(aptrain_op, feed_dict={apdataX: tX_train, apdataY: tY_train})\n\n\n\ndef train_noisy_actor():\n tX = (memoryS)\n tY = (memoryA)\n tW = (memoryW)\n\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tY) )))\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n\n #noisy_model.fit(tX,tY, batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)\n for num_epoch in range(training_epochs):\n sess.run(natrain_op, feed_dict={apdataX: tX, apdataY: tY})\n\n\n\ndef add_controlled_noise(targetModel,big_sigma,small_sigma,largeNoise = False):\n tR = (memoryR)\n tX = (memoryS)\n tY = (memoryA)\n tW = (memoryW)\n train_C = np.random.randint(tY.shape[0],size=100)\n sigma = False\n if largeNoise:\n sigma = True\n else:\n sigma = False\n tX = tX[train_C,:]\n tY_old = tY[train_C,:]\n tY_new = tY[train_C,:]\n diffs = np.zeros(np.alen(tX))\n delta = 1000\n deltaCount = 0\n\n for i in range(np.alen(tX)):\n a = GetRememberedOptimalPolicyFromNoisyModel(tX[i])\n a = a.flatten()\n #print(\"Output Before noise \",a)\n\n\n while ( delta > upper_delta or delta < lower_delta) and deltaCount <5:\n reset_noisy_model_TF()\n targetModel\n #noisy_model.set_weights(action_predictor_model.get_weights())\n add_noise_TF(largeNoise)\n for i in range(np.alen(tX)):\n b = GetRememberedOptimalPolicyFromNoisyModel(tX[i])\n b = b.flatten()\n\n c = np.abs(a-b)\n delta = c.mean()\n deltaCount+=1\n if delta > upper_delta:\n big_sigma = big_sigma *0.9\n print(\"Delta\",delta,\" out of bound adjusting big_sigma\", big_sigma)\n\n if delta < lower_delta:\n big_sigma = big_sigma *1.1\n print(\"Delta\",delta,\" out of bound adjusting big_sigma\", big_sigma)\n\n print(\"Tried x time \", deltaCount,\"delta =\", delta)\n\n return big_sigma\n\n\n\n#Play the game 500 times\nfor game in range(num_games_to_play):\n gameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\n gameS = np.zeros(shape=(1,num_env_variables))\n gameA = np.zeros(shape=(1,num_env_actions))\n gameR = np.zeros(shape=(1,1))\n gameW = np.zeros(shape=(1,1))\n #Get the Q state\n qs = env.reset()\n #env.refresh(render=True)\n\n mAP_Counts = 0\n num_add_mem = 0\n #print(\"qs \", qs)\n is_noisy_game = False\n\n #noisy_model.set_weights(action_predictor_model.get_weights())\n\n #Add noise to Actor\n if game > num_initial_observation and uses_parameter_noising:\n is_noisy_game = False\n #print(\"Adding Noise\")\n if (game%2==0 ):\n is_noisy_game = True\n if noisy_game_no_longer_valid or game %50==0:\n print(\"Adding BIG Noise\")\n #noisy_model = keras.models.clone_model(action_predictor_model)\n reset_noisy_model_TF()\n big_sigma = add_controlled_noise(None,big_sigma,littl_sigma,True)\n #else:\n # print(\"Adding small noise\")\n # big_sigma = add_controlled_noise(None,big_sigma,littl_sigma,False)\n\n #last_best_noisy_game = -1000\n #else:\n # print(\"Adding Small Noise\")\n # #print(\"Not Changing weights last_best_noisy_game\", last_best_noisy_game,\" mean \",memoryR.mean())\n # reset_noisy_model_TF()\n # big_sigma = add_controlled_noise(None,big_sigma,True)\n\n\n\n for step in range (5000):\n\n if PLAY_GAME:\n remembered_optimal_policy = GetRememberedOptimalPolicy(qs)\n a = remembered_optimal_policy\n elif game < num_initial_observation:\n #take a radmon action\n a = GenerateSampleAction(3)\n else:\n prob = np.random.rand(1)\n explore_prob = starting_explore_prob-(starting_explore_prob/random_num_games_to_play)*game\n\n if game > random_num_games_to_play:\n prob = 0.000001\n #Chose between prediction and chance\n if prob < explore_prob or game%random_every_n==1:\n #take a random action\n a = GenerateSampleAction(3)\n\n else:\n #print(\"Using Actor\")\n if is_noisy_game and uses_parameter_noising:\n remembered_optimal_policy = GetRememberedOptimalPolicyFromNoisyModel(qs)\n else:\n remembered_optimal_policy = GetRememberedOptimalPolicy(qs)\n a = remembered_optimal_policy\n\n if uses_critic:\n #print(\"Using critric\")\n stock = np.zeros(num_retries)\n stockAction = np.zeros(shape=(num_retries,num_env_actions))\n for i in range(num_retries):\n #stockAction[i] = env.action_space.sample()\n stockAction[i] = GenerateSampleAction(3)\n\n stock[i] = predictTotalRewards(qs,stockAction[i])\n best_index = np.argmax(stock)\n randaction = stockAction[best_index]\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 mAP_Counts += 1\n #print(\" | selecting remembered_optimal_policy \",a)\n else:\n a = randaction\n #print(\" - selecting generated optimal policy \",a)\n\n\n# for i in range (np.alen(a)):\n# if a[i] < -1: a[i]=-0.99999999999\n# if a[i] > 1: a[i] = 0.99999999999\n #if step%50==0:\n # print(\"a =>\",a)\n\n env.render()\n #env.refresh(render=True)\n\n qs_a = np.concatenate((qs,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 #if done and step<max_steps-3:\n # r = -50\n\n if step ==0:\n gameSA[0] = qs_a\n gameS[0] = qs\n gameR[0] = np.array([r])\n gameA[0] = np.array([r])\n gameW[0] = np.array([0.000000005])\n else:\n gameSA= np.vstack((gameSA, qs_a))\n gameS= np.vstack((gameS, qs))\n gameR = np.vstack((gameR, np.array([r])))\n gameA = np.vstack((gameA, np.array([a])))\n gameW = np.vstack((gameW, np.array([0.000000005])))\n\n if step > max_steps:\n done = True\n\n if done :\n tempGameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\n tempGameS = np.zeros(shape=(1,num_env_variables))\n tempGameA = np.zeros(shape=(1,num_env_actions))\n tempGameR = np.zeros(shape=(1,1))\n tempGameRR = np.zeros(shape=(1,1))\n tempGameW = np.zeros(shape=(1,1))\n\n #Calculate Q values from end to start of game\n #mstats.append(step)\n for i in range(0,gameR.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 gameR[(gameR.shape[0]-1)-i][0] = gameR[(gameR.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 gameR[(gameR.shape[0]-1)-i][0] = gameR[(gameR.shape[0]-1)-i][0]+b_discount*gameR[(gameR.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\n if memoryR.shape[0] ==1:\n memorySA = gameSA\n memoryR = gameR\n memoryA = gameA\n memoryS = gameS\n memoryRR = gameR\n memoryW = gameW\n\n tempGameA = tempGameA[1:]\n tempGameS = tempGameS[1:]\n tempGameRR = tempGameRR[1:]\n tempGameR = tempGameR[1:]\n tempGameSA = tempGameSA[1:]\n tempGameW = tempGameW[1:]\n\n\n for i in range(gameR.shape[0]):\n tempGameSA = np.vstack((tempGameSA,gameSA[i]))\n tempGameR = np.vstack((tempGameR,gameR[i]))\n\n #print(\"add_prob\",add_prob)\n tempGameA = np.vstack((tempGameA,gameA[i]))\n tempGameS = np.vstack((tempGameS,gameS[i]))\n tempGameRR = np.vstack((tempGameRR,gameR[i]))\n tempGameW = np.vstack((tempGameW,gameR.mean()))\n\n\n #train actor network based on last rollout\n if game>3:\n tX = (tempGameS)\n tY = (tempGameA)\n tW = (tempGameW)\n #action_predictor_model.fit(tX,tY,sample_weight=tW.flatten(), batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)\n\n\n\n if memoryR.shape[0] ==1:\n memoryA = tempGameA\n memoryS = tempGameS\n memoryRR = tempGameRR\n memoryR = tempGameR\n memorySA = tempGameSA\n memoryW = tempGameW\n else:\n #Add experience to memory\n memoryS = np.concatenate((memoryS,tempGameS),axis=0)\n memoryRR = np.concatenate((memoryRR,tempGameRR),axis=0)\n memoryA = np.concatenate((memoryA,tempGameA),axis=0)\n memorySA = np.concatenate((memorySA,tempGameSA),axis=0)\n\n memoryR = np.concatenate((memoryR,tempGameR),axis=0)\n memoryW = np.concatenate((memoryW,tempGameW),axis=0)\n\n\n if gameR.mean() > max_game_average :\n max_game_average = gameR.mean()\n\n #if memory is full remove first element\n if np.alen(memoryR) >= max_memory_len:\n memorySA = memorySA[gameR.shape[0]:]\n memoryR = memoryR[gameR.shape[0]:]\n memoryA = memoryA[gameR.shape[0]:]\n memoryS = memoryS[gameR.shape[0]:]\n memoryRR = memoryRR[gameR.shape[0]:]\n memoryW = memoryW[gameR.shape[0]:]\n\n\n qs=s\n\n if done and game > num_initial_observation and not PLAY_GAME:\n last_game_average = gameR.mean()\n if is_noisy_game:\n if last_game_average < memoryR.flatten()[-5000:].mean():\n noisy_game_no_longer_valid = True\n else:\n noisy_game_no_longer_valid = False\n #if game >3:\n #actor_experience_replay(gameSA,gameR,gameS,gameA,gameW,1)\n max_game_average = memoryW.max()\n if game > 3 and game %1 ==0:\n # train on all memory\n print(\"Experience Replay\")\n #for i in range(3):\n\n pr_actor_experience_replay(memorySA,memoryR,memoryS,memoryA,memoryW,training_epochs)\n if game > 3 and game %1 ==0 and uses_critic:\n for num_epoch in range(training_epochs):\n tSA = (memorySA)+0.0\n tR = (memoryR)+0.0\n train_A = np.random.randint(tR.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n tR = tR[train_A,:]\n tSA = tSA [train_A,:]\n print(num_epoch,\"Training Critic n elements =\", np.alen(tR))\n for t in range(25):\n sess.run(Qtrain_op, feed_dict={dataX: tSA, dataY: tR})\n\n #Qmodel.fit(tSA,tR, batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)\n if game > 3 and game %5 ==-1 and uses_parameter_noising:\n print(\"Training noisy_actor\")\n train_noisy_actor()\n #Reinforce training with best game\n\n ''' SAVE MODEL\n if done and game >= num_initial_observation and not PLAY_GAME:\n if save_weights and game%20 == 0 and game >35:\n #Save model\n #print(\"Saving weights\")\n Qmodel.save_weights(weigths_filename)\n action_predictor_model.save_weights(apWeights_filename)\n\n if save_memory_arrays and game%20 == 0 and game >35:\n np.save(version_name+'memorySA.npy',memorySA)\n np.save(version_name+'memoryRR.npy',memoryRR)\n np.save(version_name+'memoryS.npy',memoryS)\n np.save(version_name+'memoryA.npy',memoryA)\n np.save(version_name+'memoryR.npy',memoryR)\n np.save(version_name+'memoryW.npy',memoryW)\n\n '''\n\n\n if done:\n\n if game%1==0:\n #print(\"Training Game #\",game,\"last everage\",memoryR.mean(),\"max_game_average\",max_game_average,,\"game mean\",gameR.mean(),\"memMax\",memoryR.max(),\"memoryR\",memoryR.shape[0], \"SelectiveMem Size \",memoryRR.shape[0],\"Selective Mem mean\",memoryRR.mean(axis=0)[0], \" steps = \", step )\n if is_noisy_game:\n print(\"Noisy Game # %7d avgScore %8.3f [-1000]avg %8.3f last_game %8.3f max_game_avg %8.3f memory size %8d memMax %8.3f steps %5d\" % (game, memoryR.mean(),memoryR.flatten()[-5000:].mean(), last_game_average, max_game_average , memoryR.shape[0], memoryR.max(), step ) )\n else:\n print(\"Reg Game # %7d avgScore %8.3f [-1000]avg %8.3f last_game %8.3f max_game_avg %8.3f memory size %8d memMax %8.3f steps %5d\" % (game, memoryR.mean(),memoryR.flatten()[-5000:].mean(), last_game_average, max_game_average , memoryR.shape[0], memoryR.max(), step ) )\n\n if game%5 ==0 and np.alen(memoryR)>1000:\n mGames.append(game)\n mSteps.append(step/1000*100)\n mAPPicks.append(mAP_Counts/step*100)\n mAverageScores.append(max(memoryR.mean(), -50)/100*100)\n bar_chart = pygal.HorizontalLine()\n bar_chart.x_labels = map(str, mGames) # Then create a bar graph object\n bar_chart.add('Average score', mAverageScores) # Add some values\n bar_chart.add('percent actor picks ', mAPPicks) # Add some values\n bar_chart.add('percent steps complete ', mSteps) # Add some values\n\n\n bar_chart.render_to_file(version_name+'Performance2_bar_chart.svg')\n\n break\n\n\nplt.plot(mstats)\nplt.show()\n\nif save_weights:\n #Save model\n print(\"Saving weights\")\n Qmodel.save_weights(weigths_filename)\n action_predictor_model.save_weights(apWeights_filename)\n", "'''\nLunarLanderContinuous solution with\n - Selective Memory\n - Actor Critic\n - Parameter Noising\n - Q as discriminator\nsolution by Michel Aka author of FitML github blog and repository\nhttps://github.com/FitMachineLearning/FitML/\nhttps://www.youtube.com/channel/UCi7_WxajoowBl4_9P0DhzzA/featured\nUpdate\nDeep Network\nStarts to land consistantly at 350\n\n\n'''\nimport numpy as np\nimport keras\nimport gym\n#import pybullet\n#import pybullet_envs\n#import roboschool\n\n\nimport pygal\nimport os\nimport h5py\n#import matplotlib.pyplot as plt\nimport math\n\nfrom keras.layers.advanced_activations import LeakyReLU, PReLU\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\nPLAY_GAME = False #Set to True if you want to agent to play without training\nuses_critic = True\nuses_parameter_noising = False\n\nnum_env_variables = 8\nnum_env_actions = 2\nnum_initial_observation = 0\nlearning_rate = 0.002\napLearning_rate = 0.001\nlittl_sigma = 0.00006\nbig_sigma = 0.006\nupper_delta = 0.0035\nlower_delta = 0.001\nENVIRONMENT_NAME = \"LunarLanderContinuous-v2\"\nversion_name = ENVIRONMENT_NAME + \"ker_v10\"\nweigths_filename = version_name+\"-weights.h5\"\napWeights_filename = version_name+\"-weights-ap.h5\"\n\n\n#range within wich the SmartCrossEntropy action parameters will deviate from\n#remembered optimal policy\nsce_range = 0.2\nb_discount = 0.98\nmax_memory_len = 40000\nexperience_replay_size = 40000\nrandom_every_n = 30\nnum_retries = 60\nstarting_explore_prob = 0.005\ntraining_epochs = 1\nmini_batch = 512*4\nload_previous_weights = False\nobserve_and_train = True\nsave_weights = True\nsave_memory_arrays = True\nload_memory_arrays = False\ndo_training = True\nnum_games_to_play = 20000\nrandom_num_games_to_play = num_games_to_play/3\nCLIP_ACTION = True\nHAS_REWARD_SCALLING = True\nREWARD_SCALE = 1/300\nmax_steps = 1490\n\n\n\n#Selective memory settings\nsm_normalizer = 20\nsm_memory_size = 10500\n\nlast_game_average = -1000\nlast_best_noisy_game = -1000\nmax_game_average = -1000\nnum_positive_avg_games = 0\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\n\nenv = gym.make(ENVIRONMENT_NAME)\n#env.render(mode=\"human\")\nenv.reset()\n\n\nprint(\"-- Observations\",env.observation_space)\nprint(\"-- actionspace\",env.action_space)\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,num_env_actions))\n\ndef custom_error(y_true, y_pred, Qsa):\n cce=0.001*(y_true - y_pred)*Qsa\n return cce\n\n\n\n\n#nitialize the Reward predictor model\nQmodel = Sequential()\n#model.add(Dense(num_env_variables+num_env_actions, activation='tanh', input_dim=dataX.shape[1]))\nQmodel.add(Dense(32, activation='relu', input_dim=dataX.shape[1]))\n#Qmodel.add(Dropout(0.5))\nQmodel.add(Dense(32, activation='relu'))\n\nQmodel.add(Dense(32, activation='relu'))\n\nQmodel.add(Dense(32, activation='relu'))\n\nQmodel.add(Dense(32, activation='relu'))\n\nQmodel.add(Dense(32, activation='relu'))\n\nQmodel.add(Dense(32, activation='relu'))\n\nQmodel.add(Dense(32, activation='relu'))\n\n#Qmodel.add(Dropout(0.5))\nQmodel.add(Dense(4, activation='relu'))\n#Qmodel.add(Dropout(0.5))\n\nQmodel.add(Dense(dataY.shape[1]))\n#opt = optimizers.adam(lr=learning_rate)\nopt = optimizers.Adadelta()\n\nQmodel.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(32, activation='relu', input_dim=apdataX.shape[1]))\n#action_predictor_model.add(Dropout(0.5))\naction_predictor_model.add(Dense(32, activation='relu'))\n\naction_predictor_model.add(Dense(32, activation='relu'))\n\naction_predictor_model.add(Dense(32, activation='relu'))\n\naction_predictor_model.add(Dense(32, activation='relu'))\n\naction_predictor_model.add(Dense(32, activation='relu'))\n\naction_predictor_model.add(Dense(32, activation='relu'))\n\naction_predictor_model.add(Dense(32, activation='relu'))\n#action_predictor_model.add(Dropout(0.5))\naction_predictor_model.add(Dense(3, activation='relu'))\n#action_predictor_model.add(Dropout(0.5))\n\naction_predictor_model.add(Dense(apdataY.shape[1]))\n#opt2 = optimizers.adam(lr=apLearning_rate)\nopt2 = optimizers.Adadelta()\n\naction_predictor_model.compile(loss='mse', optimizer=opt2, metrics=['accuracy'])\n\n\n\n\n#initialize the action predictor model\nnoisy_model = Sequential()\n#model.add(Dense(num_env_variables+num_env_actions, activation='tanh', input_dim=dataX.shape[1]))\nnoisy_model.add(Dense(1024, activation='relu', input_dim=apdataX.shape[1]))\n#noisy_model.add(Dropout(0.5))\n#noisy_model.add(Dense(256, activation='relu'))\n#noisy_model.add(Dropout(0.5))\n#noisy_model.add(Dense(3, activation='relu'))\n#noisy_model.add(Dropout(0.5))\nnoisy_model.add(Dense(apdataY.shape[1]))\nopt3 = optimizers.Adadelta()\n\nnoisy_model.compile(loss='mse', optimizer=opt3, 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 Qmodel.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\nmemorySA = np.zeros(shape=(1,num_env_variables+num_env_actions))\nmemoryS = np.zeros(shape=(1,num_env_variables))\nmemoryA = np.zeros(shape=(1,1))\nmemoryR = np.zeros(shape=(1,1))\nmemoryRR = np.zeros(shape=(1,1))\nmemoryW = np.zeros(shape=(1,1))\n\nBestGameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\nBestGameS = np.zeros(shape=(1,num_env_variables))\nBestGameA = np.zeros(shape=(1,num_env_actions))\nBestGameR = np.zeros(shape=(1,1))\nBestGameW = np.zeros(shape=(1,1))\n\nif load_memory_arrays:\n if os.path.isfile(version_name+'memorySA.npy'):\n print(\"Memory Files exist. Loading...\")\n memorySA = np.load(version_name+'memorySA.npy')\n memoryRR = np.load(version_name+'memoryRR.npy')\n memoryS = np.load(version_name+'memoryS.npy')\n memoryA = np.load(version_name+'memoryA.npy')\n memoryR = np.load(version_name+'memoryR.npy')\n memoryW = np.load(version_name+'memoryW.npy')\n\n else:\n print(\"No memory Files. Recreating\")\n\n\nmstats = []\nmGames = []\nmAverageScores = []\nmSteps = []\nmAP_Counts = 0\nnum_add_mem = 0\nmAPPicks = []\n\n#------\n\n\n# --- Parameter Noising\ndef add_noise(mu, largeNoise=False):\n\n if largeNoise:\n sig = big_sigma\n else:\n #print(\"Adding Large parameter noise\")\n sig = littl_sigma #Sigma = width of the standard deviaion\n #mu = means\n x = np.random.rand(1) #probability of doing x\n #print (\"x prob \",x)\n if x >0.5:\n return mu + np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))\n else:\n return mu - np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))\n\n# --- Parameter Noising\ndef add_noise_simple(mu, largeNoise=False):\n x = np.random.rand(1) - 0.5 #probability of doing x\n if not largeNoise:\n x = x*big_sigma\n else:\n x = x*big_sigma #Sigma = width of the standard deviaion\n #print (\"x/200\",x,\"big_sigma\",big_sigma)\n return mu + x\n\n\n#add_noise_simple = np.vectorize(add_noise_simple,otypes=[np.float])\nadd_noise = np.vectorize(add_noise,otypes=[np.float])\nadd_noise_simple = np.vectorize(add_noise_simple,otypes=[np.float])\n\n\ndef add_noise_to_model(targetModel,largeNoise = False):\n #noisy_model = keras.models.clone_model(action_predictor_model)\n #noisy_model.set_weights(action_predictor_model.get_weights())\n #print(\"Adding Noise to actor\")\n #largeNoise = last_game_average < memoryR.mean()\n sz = len(noisy_model.layers)\n #if largeNoise:\n # print(\"Setting Large Noise!\")\n for k in range(sz):\n w = targetModel.layers[k].get_weights()\n if np.alen(w) >0 :\n #print(\"k==>\",k)\n w[0] = add_noise_simple(w[0],largeNoise)\n\n targetModel.layers[k].set_weights(w)\n return targetModel\n\n\n\n\ndef reset_noisy_model_weights_to_apWeights(mu):\n x = mu+0.0 #probability of doing x\n return x\n\nreset_noisy_model_weights_to_apWeights = np.vectorize(reset_noisy_model_weights_to_apWeights,otypes=[np.float])\n\ndef reset_noisy_model():\n sz = len(noisy_model.layers)\n #if largeNoise:\n # print(\"Setting Large Noise!\")\n for k in range(sz):\n w = noisy_model.layers[k].get_weights()\n apW = action_predictor_model.layers[k].get_weights()\n\n if np.alen(w) >0:\n w[0] = reset_noisy_model_weights_to_apWeights(apW[0])\n noisy_model.layers[k].set_weights(w)\n #print(\"w\",w)\n #print(\"apW\",apW)\n\ndef reset_noisy_model2():\n action_predictor_model.save_weights(apWeights_filename)\n\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 noisy_model.load_weights(apWeights_filename)\n else:\n print(\"File \",apWeights_filename,\" does not exis. Retraining... \")\n\n# --- Parameter Noising\n\ndef predictTotalRewards(qstate, action):\n qs_a = np.concatenate((qstate,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 = Qmodel.predict(predX[0].reshape(1,predX.shape[1]))\n remembered_total_reward = pred[0][0]\n return remembered_total_reward\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 GetRememberedOptimalPolicyFromNoisyModel(targetModel,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 = targetModel.predict(predX[0].reshape(1,predX.shape[1]))\n r_remembered_optimal_policy = pred[0]\n return r_remembered_optimal_policy\n\ndef addToMemory(reward,mem_mean,memMax,averegeReward,gameAverage,mstd):\n target = mem_mean + math.fabs((memMax-mem_mean)/2)\n d_target_max = math.fabs(memMax-target)\n d_target_reward = math.fabs(reward-target)\n advantage = d_target_reward / d_target_max\n gameAdvantage = math.fabs((averegeReward-gameAverage)/(averegeReward-memMax))\n prob = 0.000000000000005\n if gameAdvantage < 0.05:\n gameAdvantage = 0.000000000000005\n if reward > target:\n return True, 0.0000000005 + (1-0.0000000005)*advantage #*gameAdvantage\n else:\n return False, 0.000000000000005\n\n\ndef scale_weights(memR,memW):\n rmax = memR.max()\n rmin = memR.min()\n reward_range = math.fabs(rmax - rmin )\n if reward_range == 0:\n reward_range = 10\n for i in range(np.alen(memR)):\n memW[i][0] = math.fabs(memR[i][0]-rmin)/reward_range\n memW[i][0] = max(memW[i][0],0.001)\n #print(\"memW %5.2f reward %5.2f rmax %5.2f rmin %5.2f \"%(memW[i][0],memR[i][0],rmax,rmin))\n #print(\"memW\",memW)\n return memW\n\n\ndef pr_actor_experience_replay(memSA,memR,memS,memA,memW,num_epochs=1):\n for t in range(training_epochs):\n tSA = (memSA)+0.0\n tR = (memR)+0.0\n tX = (memS)+0.0\n tY = (memA)+0.0\n tW = (memW)+0.0\n tS = memW +0.0\n\n treshold = memoryR.mean()\n gameAverage = memoryR.mean()\n gameDistance = math.fabs(memoryW.max() - memoryR.mean())\n gameTreshold = memoryW.mean() + gameDistance*0.4\n\n #print(\"gameMean\",tS.mean(),\"gameMax\",tS.max(),\"gameTreshold\",gameTreshold)\n\n train_C = np.arange(np.alen(tR))\n train_C = train_C[tR.flatten()>treshold]\n tX = tX[train_C,:]\n tY = tY[train_C,:]\n tW = tW[train_C,:]\n tR = tR[train_C,:]\n tS = tS[train_C,:]\n\n\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n tR = tR[train_A,:]\n tS = tS[train_A,:]\n\n tX_train = np.zeros(shape=(1,num_env_variables))\n tY_train = np.zeros(shape=(1,num_env_actions))\n for i in range(np.alen(tR)):\n pr = predictTotalRewards(tX[i],GetRememberedOptimalPolicy(tX[i]))\n #print (\"tR[i]\",tR[i],\"pr\",pr)\n d = math.fabs( memoryR.max() - pr)\n tW[i]= 0.0000000000000005\n if (tR[i]>pr ):\n tW[i]=0.15\n #if (tR[i]>pr and tS[i]>gameAverage):\n # tW[i]=0.25\n if (tR[i]>pr + d*0.5 and tS[i]>gameAverage):\n tW[i]=1\n #if (tR[i]>pr+d*0.005 and tR[i]>game_max) :\n # tW[i] = 1\n if tW[i]> np.random.rand(1):\n tX_train = np.vstack((tX_train,tX[i]))\n tY_train = np.vstack((tY_train,tY[i]))\n\n\n tX_train = tX_train[1:]\n tY_train = tY_train[1:]\n print(\"%8d were better After removing first element\"%np.alen(tX_train))\n if np.alen(tX_train)>0:\n action_predictor_model.fit(tX_train,tY_train, batch_size=mini_batch, nb_epoch=1,verbose=0)\n\n\n\n\ndef actor_experience_replay(memSA,memR,memS,memA,memW,num_epochs=1):\n for t in range(training_epochs):\n tSA = (memSA)+0.0\n tR = (memR)+0.0\n tX = (memS)+0.0\n tY = (memA)+0.0\n tW = (memW)+0.0\n tS = memW +0.0\n\n stdDev = np.std(tR)\n gameStdDev = np.std(tS)\n\n distance = math.fabs(memoryR.max()-memoryR.mean())\n #treshold = memoryR.mean()+ distance*0.75\n treshold = memoryR.mean()+ stdDev*1.1\n gameAverage = memoryR.mean()\n gameDistance = math.fabs(memoryW.max() - memoryR.mean())\n gameTreshold = memoryW.mean() + gameStdDev*0\n\n #print(\"gameMean\",tS.mean(),\"gameMax\",tS.max(),\"gameTreshold\",gameTreshold)\n\n train_C = np.arange(np.alen(tR))\n #train_C = train_C[tS.flatten()> gameTreshold] # Only take games that are above gameTreshold\n tX = tX[train_C,:]\n tY = tY[train_C,:]\n tW = tW[train_C,:]\n tR = tR[train_C,:]\n tS = tS[train_C,:]\n\n\n\n #ßprint(\"TY.shape\",tY.shape[0], \"exp replay\",experience_replay_size,\"np \", np.alen(tR))\n\n if np.alen(tR) <= 0:\n break\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n tR = tR[train_A,:]\n tS = tS[train_A,:]\n\n\n #print(\"gameMean\",tS.mean(),\"gameMax\",tS.max(),\"gameTreshold\",gameTreshold)\n\n train_D = np.arange(np.alen(tR))\n train_D = train_D[tR.flatten()>treshold] # Only take steps with rewards above threshold\n tX = tX[train_D,:]\n tY = tY[train_D,:]\n tW = tW[train_D,:]\n tR = tR[train_D,:]\n tS = tS[train_D,:]\n\n\n tX_train = tX\n tY_train = tY\n if t%89==0:\n print(\"%8d were better After removing first element\"%np.alen(tX_train), \"Upper_cut\",memoryR.mean()+stdDev,\"gameStdDev\",memoryW.mean()+gameStdDev)\n if np.alen(tX_train)>0:\n action_predictor_model.fit(tX_train,tY_train, batch_size=mini_batch, nb_epoch=1,verbose=0)\n\n\n\ndef train_noisy_actor():\n tX = (memoryS)\n tY = (memoryA)\n tW = (memoryW)\n\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tY) )))\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n\n noisy_model.fit(tX,tY, batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)\n\n\ndef add_controlled_noise(targetModel,big_sigma,largeNoise = False):\n tR = (memoryR)\n tX = (memoryS)\n tY = (memoryA)\n tW = (memoryW)\n train_C = np.random.randint(tY.shape[0],size=100)\n\n tX = tX[train_C,:]\n tY_old = tY[train_C,:]\n tY_new = tY[train_C,:]\n diffs = np.zeros(np.alen(tX))\n delta = 1000\n deltaCount = 0\n\n for i in range(np.alen(tX)):\n a = GetRememberedOptimalPolicyFromNoisyModel(noisy_model,tX[i])\n a = a.flatten()\n #print(\"Output Before noise \",a)\n\n while ( delta > upper_delta or delta < lower_delta) and deltaCount <3:\n #noisy_model.set_weights(action_predictor_model.get_weights())\n reset_noisy_model()\n targetModel = noisy_model\n targetModel = add_noise_to_model(noisy_model,largeNoise)\n\n\n for i in range(np.alen(tX)):\n b = GetRememberedOptimalPolicyFromNoisyModel(targetModel,tX[i])\n b = b.flatten()\n\n c = np.abs(a-b)\n delta = c.mean()\n\n deltaCount+=1\n if delta > upper_delta:\n big_sigma = big_sigma *0.9\n #print(\"Delta\",delta,\" out of bound adjusting big_sigma\", big_sigma)\n\n if delta < lower_delta:\n big_sigma = big_sigma *1.1\n #print(\"Delta\",delta,\" out of bound adjusting big_sigma\", big_sigma)\n #if delta > 3 or delta <0.01:\n # print(\"Delta\",delta,\" out of bound adjusting big_sigma\", big_sigma, \"to\",1/delta)\n # big_sigma = 1 / delta\n print(\"Tried x time \", deltaCount,\"delta =\", delta,\"big_sigma \",big_sigma)\n return targetModel,big_sigma\n\n\n\n\n#Play the game 500 times\nfor game in range(num_games_to_play):\n gameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\n gameS = np.zeros(shape=(1,num_env_variables))\n gameA = np.zeros(shape=(1,num_env_actions))\n gameR = np.zeros(shape=(1,1))\n gameW = np.zeros(shape=(1,1))\n #Get the Q state\n qs = env.reset()\n mAP_Counts = 0\n num_add_mem = 0\n #print(\"qs \", qs)\n is_noisy_game = False\n\n #noisy_model.set_weights(action_predictor_model.get_weights())\n\n #Add noise to Actor\n if game > num_initial_observation and uses_parameter_noising:\n is_noisy_game = False\n #print(\"Adding Noise\")\n if (game%2==0 ):\n is_noisy_game = True\n if True or last_best_noisy_game < memoryR.mean() or game%6==0:\n print(\"Adding BIG Noise\")\n #noisy_model = keras.models.clone_model(action_predictor_model)\n reset_noisy_model()\n noisy_model,big_sigma = add_controlled_noise(noisy_model,big_sigma,True)\n #last_best_noisy_game = -1000\n '''\n else:\n print(\"Adding Small Noise\")\n #print(\"Not Changing weights last_best_noisy_game\", last_best_noisy_game,\" mean \",memoryR.mean())\n reset_noisy_model()\n add_controlled_noise(noisy_model,False)\n '''\n\n for step in range (5000):\n\n if PLAY_GAME:\n remembered_optimal_policy = GetRememberedOptimalPolicy(qs)\n a = remembered_optimal_policy\n elif 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/random_num_games_to_play)*game\n\n if game > random_num_games_to_play:\n prob = 0.000001\n #Chose between prediction and chance\n if prob < explore_prob or game%random_every_n==1:\n #take a random action\n a = env.action_space.sample()\n\n else:\n #print(\"Using Actor\")\n if is_noisy_game and uses_parameter_noising:\n remembered_optimal_policy = GetRememberedOptimalPolicyFromNoisyModel(noisy_model,qs)\n else:\n remembered_optimal_policy = GetRememberedOptimalPolicy(qs)\n a = remembered_optimal_policy\n\n if uses_critic:\n #print(\"Using critric\")\n stock = np.zeros(num_retries)\n stockAction = np.zeros(shape=(num_retries,num_env_actions))\n for i in range(num_retries):\n stockAction[i] = env.action_space.sample()\n stock[i] = predictTotalRewards(qs,stockAction[i])\n best_index = np.argmax(stock)\n randaction = stockAction[best_index]\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 mAP_Counts += 1\n #print(\" | selecting remembered_optimal_policy \",a)\n else:\n a = randaction\n #print(\" - selecting generated optimal policy \",a)\n\n if CLIP_ACTION:\n for i in range (np.alen(a)):\n if a[i] < -1: a[i]=-0.99999999999\n if a[i] > 1: a[i] = 0.99999999999\n\n\n\n\n\n\n qs_a = np.concatenate((qs,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 env.render()\n #if done and step<max_steps-3:\n # r = -100\n if HAS_REWARD_SCALLING:\n r= r * REWARD_SCALE #reward scalling to from [-1,1] to [-100,100]\n\n if step ==0:\n gameSA[0] = qs_a\n gameS[0] = qs\n gameR[0] = np.array([r])\n gameA[0] = np.array([r])\n gameW[0] = np.array([0.000000005])\n else:\n gameSA= np.vstack((gameSA, qs_a))\n gameS= np.vstack((gameS, qs))\n gameR = np.vstack((gameR, np.array([r])))\n gameA = np.vstack((gameA, np.array([a])))\n gameW = np.vstack((gameW, np.array([0.000000005])))\n\n if step > max_steps:\n done = True\n\n if done :\n tempGameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\n tempGameS = np.zeros(shape=(1,num_env_variables))\n tempGameA = np.zeros(shape=(1,num_env_actions))\n tempGameR = np.zeros(shape=(1,1))\n tempGameRR = np.zeros(shape=(1,1))\n tempGameW = np.zeros(shape=(1,1))\n\n #Calculate Q values from end to start of game\n #mstats.append(step)\n for i in range(0,gameR.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 gameR[(gameR.shape[0]-1)-i][0] = gameR[(gameR.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 gameR[(gameR.shape[0]-1)-i][0] = gameR[(gameR.shape[0]-1)-i][0]+b_discount*gameR[(gameR.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\n if memoryR.shape[0] ==1:\n memorySA = gameSA\n memoryR = gameR\n memoryA = gameA\n memoryS = gameS\n memoryRR = gameR\n memoryW = gameW\n\n tempGameA = tempGameA[1:]\n tempGameS = tempGameS[1:]\n tempGameRR = tempGameRR[1:]\n tempGameR = tempGameR[1:]\n tempGameSA = tempGameSA[1:]\n tempGameW = tempGameW[1:]\n\n\n for i in range(gameR.shape[0]):\n tempGameSA = np.vstack((tempGameSA,gameSA[i]))\n tempGameR = np.vstack((tempGameR,gameR[i]))\n\n tempGameA = np.vstack((tempGameA,gameA[i]))\n tempGameS = np.vstack((tempGameS,gameS[i]))\n tempGameRR = np.vstack((tempGameRR,gameR[i]))\n tempGameW = np.vstack((tempGameW,gameR.mean()))\n\n\n #train actor network based on last rollout\n if game>3:\n tX = (tempGameS)\n tY = (tempGameA)\n tW = (tempGameW)\n #action_predictor_model.fit(tX,tY,sample_weight=tW.flatten(), batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)\n\n\n\n if memoryR.shape[0] ==1:\n memoryA = tempGameA\n memoryS = tempGameS\n memoryRR = tempGameRR\n memoryR = tempGameR\n memorySA = tempGameSA\n memoryW = tempGameW\n else:\n #Add experience to memory\n memoryS = np.concatenate((memoryS,tempGameS),axis=0)\n memoryRR = np.concatenate((memoryRR,tempGameRR),axis=0)\n memoryA = np.concatenate((memoryA,tempGameA),axis=0)\n memorySA = np.concatenate((memorySA,tempGameSA),axis=0)\n\n memoryR = np.concatenate((memoryR,tempGameR),axis=0)\n memoryW = np.concatenate((memoryW,tempGameW),axis=0)\n\n\n if gameR.mean() > max_game_average :\n max_game_average = gameR.mean()\n\n #if memory is full remove first element\n if np.alen(memoryR) >= max_memory_len:\n memorySA = memorySA[gameR.shape[0]:]\n memoryR = memoryR[gameR.shape[0]:]\n memoryA = memoryA[gameR.shape[0]:]\n memoryS = memoryS[gameR.shape[0]:]\n memoryRR = memoryRR[gameR.shape[0]:]\n memoryW = memoryW[gameR.shape[0]:]\n\n\n qs=s\n\n if done and game > num_initial_observation and not PLAY_GAME:\n last_game_average = gameR.mean()\n if is_noisy_game and last_game_average > memoryR.mean():\n last_best_noisy_game = last_game_average\n #if game >3:\n #actor_experience_replay(gameSA,gameR,gameS,gameA,gameW,1)\n\n if game > 3 and game %1 ==0:\n # train on all memory\n print(\"Experience Replay\")\n #for i in range(3):\n\n actor_experience_replay(memorySA,memoryR,memoryS,memoryA,memoryW,training_epochs)\n if game > 3 and game %1 ==0 and uses_critic:\n for t in range(training_epochs):\n tSA = (memorySA)\n tR = (memoryR)\n train_A = np.random.randint(tR.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n tR = tR[train_A,:]\n tSA = tSA [train_A,:]\n #print(\"Training Critic n elements =\", np.alen(tR))\n Qmodel.fit(tSA,tR, batch_size=mini_batch, nb_epoch=1,verbose=0)\n if game > 3 and game %5 ==-1 and uses_parameter_noising:\n print(\"Training noisy_actor\")\n train_noisy_actor()\n #Reinforce training with best game\n\n\n if done and game >= num_initial_observation and not PLAY_GAME:\n if save_weights and game%20 == 0 and game >35:\n #Save model\n #print(\"Saving weights\")\n Qmodel.save_weights(weigths_filename)\n action_predictor_model.save_weights(apWeights_filename)\n\n if save_memory_arrays and game%20 == 0 and game >35:\n np.save(version_name+'memorySA.npy',memorySA)\n np.save(version_name+'memoryRR.npy',memoryRR)\n np.save(version_name+'memoryS.npy',memoryS)\n np.save(version_name+'memoryA.npy',memoryA)\n np.save(version_name+'memoryR.npy',memoryR)\n np.save(version_name+'memoryW.npy',memoryW)\n\n\n\n\n if done:\n rScale = 1\n if HAS_REWARD_SCALLING:\n rScale = 1*REWARD_SCALE\n if gameR.mean() >0:\n num_positive_avg_games += 1\n if game%1==0:\n #print(\"Training Game #\",game,\"last everage\",memoryR.mean(),\"max_game_average\",max_game_average,,\"game mean\",gameR.mean(),\"memMax\",memoryR.max(),\"memoryR\",memoryR.shape[0], \"SelectiveMem Size \",memoryRR.shape[0],\"Selective Mem mean\",memoryRR.mean(axis=0)[0], \" steps = \", step )\n if is_noisy_game:\n print(\"Noisy Game # %7d avgScore %8.3f last_game_avg %8.3f max_game_avg %8.3f memory size %8d memMax %8.3f steps %5d pos games %5d\" % (game, memoryR.mean(), last_game_average, memoryW.max() , memoryR.shape[0], memoryR.max(), step,num_positive_avg_games ) )\n else:\n print(\"Reg Game # %7d avgScore %8.3f last_game_avg %8.3f max_game_avg %8.3f memory size %8d memMax %8.3f steps %5d pos games %5d\" % (game, memoryR.mean(), last_game_average, memoryW.max() , memoryR.shape[0], memoryR.max(), step ,num_positive_avg_games ) )\n\n if game%5 ==0 and np.alen(memoryR)>1000:\n mGames.append(game)\n mSteps.append(step/1000*100)\n mAPPicks.append(mAP_Counts/step*100)\n mAverageScores.append(max(memoryR.mean()*rScale, -150))\n bar_chart = pygal.HorizontalLine()\n bar_chart.x_labels = map(str, mGames) # Then create a bar graph object\n bar_chart.add('Average score', mAverageScores) # Add some values\n bar_chart.add('percent actor picks ', mAPPicks) # Add some values\n bar_chart.add('percent steps complete ', mSteps) # Add some values\n\n\n bar_chart.render_to_file(version_name+'Performance2_bar_chart.svg')\n\n break\n\n\nplt.plot(mstats)\nplt.show()\n\nif save_weights:\n #Save model\n print(\"Saving weights\")\n Qmodel.save_weights(weigths_filename)\n action_predictor_model.save_weights(apWeights_filename)\n", "## DQN Tutorial\r\n## https://www.youtube.com/watch?v=WHRQUZrxxGw\r\nimport torch\r\nimport gym\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport numpy as np\r\nfrom dataclasses import dataclass\r\nfrom typing import Any\r\nfrom random import random\r\n\r\n@dataclass\r\nclass sars:\r\n state: Any\r\n action: int\r\n reward: float\r\n next_state: Any\r\n done: bool\r\n qval: float\r\n\r\nclass DQNAgent:\r\n def __init__(self,model,targetModel):\r\n self.model = model\r\n self.targetModel = targetModel\r\n\r\n def get_actions(self, observations):\r\n q_vals = self.model(torch.Tensor(observations).to(self.model.device))\r\n\r\n\r\n return q_vals.max(-1)[1]\r\n\r\n def update_target_model(self):\r\n self.targetModel.load_state_dict(self.model.state_dict())\r\n\r\nclass Model(nn.Module):\r\n def __init__(self, obs_shape, num_actions,lr):\r\n super(Model,self).__init__()\r\n assert len(obs_shape) ==1, \"This network only works on flat observations\"\r\n self.obs_shape = obs_shape\r\n self.num_action = num_actions\r\n\r\n self.net = torch.nn.Sequential(\r\n torch.nn.Linear(obs_shape[0],32),\r\n torch.nn.ReLU(),\r\n torch.nn.Linear(32,num_actions)\r\n )\r\n self.opt = optim.Adam(self.net.parameters(),lr=lr)\r\n if torch.cuda.is_available():\r\n print(\"Using CUDA\")\r\n self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cuda:1')\r\n self.to(self.device)\r\n\r\n\r\n def forward(self, x):\r\n return self.net(x)\r\n\r\n\r\n\r\nclass ReplayBuffer:\r\n def __init__(self, buffer_size = 1000):\r\n self.buffer_size = buffer_size\r\n # self.buffer = [None]*buffer_size\r\n self.buffer = []\r\n self.index = 0\r\n\r\n def insert(self, sars):\r\n # self.buffer.append(sars)\r\n # print(\"inserting index \", self.index, \"@\",self.index%self.buffer_size)\r\n if(self.index == 10):\r\n print(\"first 10 \",self.buffer[0:10])\r\n # import ipdb; ipdb.set_trace()\r\n\r\n # if(self.index > self.buffer_size and self.index%self.buffer_size==0):\r\n # print(\"first 10 \",self.buffer[0:10])\r\n # print(\"last 10 \",self.buffer[-10:])\r\n # print(\"\")\r\n # import ipdb; ipdb.set_trace()\r\n # self.buffer[self.index%self.buffer_size] = sars\r\n self.index+=1\r\n self.buffer.append(sars)\r\n if(len(self.buffer)>self.buffer_size):\r\n self.buffer = self.buffer[1:]\r\n # print(\"Clipping Buffer at size\", len(self.buffer))\r\n\r\n def sample(self, num_samples,current_episode_steps):\r\n # assert num_samples < min(len(self.buffer),self.index)\r\n # if num_samples>self.index:\r\n # print(\"sampling n \",min(num_samples,self.index))\r\n # a = self.buffer[0:((self.index-current_episode_steps)%self.buffer_size)]\r\n if len(self.buffer) > 0:\r\n return np.random.choice(self.buffer, min(num_samples,self.index))\r\n else:\r\n return []\r\n\r\n\r\n\r\ndef get_one_hot(action,n_dim):\r\n retval = np.zeros(n_dim)\r\n retval[action] = 1.0\r\n return retval\r\n\r\n\r\ndef train_step(model, state_transitions, tgt, num_actions):\r\n if len(state_transitions) <=0:\r\n print(\"empty state transitions\")\r\n return\r\n cur_states = torch.stack( ([torch.Tensor(s.state) for s in state_transitions]) ).to(model.device)\r\n rewards = torch.stack( ([torch.Tensor([s.reward]) for s in state_transitions]) ).to(model.device)\r\n Qs = torch.stack( ([torch.Tensor([s.qval]) for s in state_transitions]) ).to(model.device)\r\n mask = torch.stack(([torch.Tensor([0]) if s.done else torch.Tensor([1]) for s in state_transitions])).to(model.device)\r\n next_states = torch.stack( ([torch.Tensor(s.next_state) for s in state_transitions]) ).to(model.device)\r\n actions = [s.action for s in state_transitions]\r\n with torch.no_grad():\r\n actual_Q_values = Qs\r\n model.opt.zero_grad()\r\n pred_qvals = model(cur_states)\r\n\r\n one_hot_actions = F.one_hot(torch.LongTensor(actions),num_actions).to(model.device)\r\n # loss = torch.mean(torch.sqrt((torch.sum(pred_qvals*one_hot_actions,-1) - actual_Q_values.view(-1) )**2)).to(model.device)\r\n loss = F.smooth_l1_loss(torch.sum(pred_qvals*one_hot_actions,-1), actual_Q_values.view(-1) )\r\n loss.backward()\r\n model.opt.step()\r\n return loss\r\n\r\n# def train_step3(model, state_transitions, tgt, num_actions):\r\n# cur_states = torch.stack( ([torch.Tensor(s.state) for s in state_transitions]) ).to(model.device)\r\n# rewards = torch.stack( ([torch.Tensor([s.reward]) for s in state_transitions]) ).to(model.device)\r\n# Qs = torch.stack( ([torch.Tensor([s.qval]) for s in state_transitions]) ).to(model.device)\r\n# mask = torch.stack(([torch.Tensor([0]) if s.done else torch.Tensor([1]) for s in state_transitions])).to(model.device)\r\n# next_states = torch.stack( ([torch.Tensor(s.next_state) for s in state_transitions]) ).to(model.device)\r\n# actions = [s.action for s in state_transitions]\r\n# with torch.no_grad():\r\n# qvals_next = tgt(next_states).max(-1)[0]\r\n# model.opt.zero_grad()\r\n# qvals = model(cur_states)\r\n# one_hot_actions = F.one_hot(torch.LongTensor(actions),num_actions).to(model.device)\r\n# loss = (\r\n# ( rewards + mask[:,0]*qvals_next - torch.sum(qvals*one_hot_actions,-1) )\r\n# ).mean()\r\n# loss.backward()\r\n# model.opt.step()\r\n# return loss\r\n\r\n\r\n\r\ndef update_Qs(replay_buffer,step_counter,episode_len,buffer_size):\r\n for i in range(episode_len):\r\n # if(step_counter > buffer_size):\r\n # import ipdb; ipdb.set_trace()\r\n index = episode_len-i\r\n next_index = index+1\r\n if i==0:\r\n replay_buffer[index].qval = replay_buffer[index].reward\r\n if(step_counter%2000==0):\r\n print(\"i\",i,\"q \",replay_buffer[index].qval)\r\n else:\r\n replay_buffer[index].qval = replay_buffer[index].reward + 0.98 * replay_buffer[next_index].qval\r\n if(step_counter%2000==0):\r\n print(\"i\",i,\"q \",replay_buffer[index].qval)\r\n return replay_buffer\r\n\r\n# def train_step2(model,state_transitions,targetModel,num_actions):\r\n# # print(\"state_transitions\" , state_transitions)\r\n# cur_states = torch.stack(([torch.Tensor(s.state) for s in state_transitions]))\r\n# next_states = torch.stack(([torch.Tensor(s.next_state) for s in state_transitions]))\r\n#\r\n# rewards = torch.stack(([torch.Tensor([s.reward]) for s in state_transitions]))\r\n# # act = torch.Tensor(np.zeros(num_actions))\r\n# actions = torch.stack([torch.Tensor(get_one_hot(action,num_actions)) for s in state_transitions])\r\n#\r\n# mask = torch.stack([torch.Tensor([0]) if s.done else torch.Tensor([1]) for s in state_transitions])\r\n#\r\n# with torch.no_grad():\r\n# # qevals_next = targetModel(next_states).max(-1)\r\n# qevals_next = targetModel(next_states)\r\n# # print(\"qevals_next\",qevals_next)\r\n# qevals_next = qevals_next.max(axis=1)[0]\r\n# # print(\"qevals_next . max\",qevals_next)\r\n#\r\n# model.opt.zero_grad()\r\n# qevals = model(cur_states)\r\n#\r\n# # print(\"rewards \",rewards.shape, rewards)\r\n# # print(\"qevals \",qevals.shape,qevals)\r\n# # # print(\"maks \",mask.shape,mask)\r\n# # print(\"actions \",actions.shape,actions)\r\n# print(\"qevals_next\",qevals_next)\r\n# #\r\n# print(\"qeval*actions \", torch.sum(qevals*actions,axis=1) )\r\n# # print(\"qeval*actions . mean() \", torch.sum(qevals*actions,axis=1).mean() )\r\n#\r\n#\r\n# loss = ( (rewards + 0.98 * qevals_next*mask[:,0] ) - (torch.sum(qevals*actions,axis=1)) ).mean()\r\n# # loss = ( (rewards + 0.98 * qevals_next*mask) - qevals*actions ).mean()\r\n# loss.backward()\r\n# model.opt.step()\r\n#\r\n# print(\"Loss \", loss)\r\n# return loss\r\n\r\n\r\nif __name__=='__main__':\r\n DEBUGER_ON = True\r\n NUM_GAMES = 50000\r\n MAX_EPISODE_STEPS = 1000\r\n TARGET_MODEL_UPDATE_INTERVAL = 50\r\n EPSILON_MIN = 0.05\r\n EPSILON_START = 0.5\r\n EPSLILON_COUNT = 6000 #Games\r\n RANDOM_GAME_EVERY = 20\r\n TRAIN_EVERY_N_STEPS = 25\r\n TRAINING_SAMPLE_SIZE = 256\r\n TRAINING_ITTERATIONS = 1\r\n PRINT_EVERY = 2\r\n RENDER_ENV = False\r\n LOAD_MODEL = False\r\n SAVE_MODEL = True\r\n MODEL_FILE_NAME = \"TDQN_RL_MODEL.trl\"\r\n MODEL_ID = \"01\"\r\n SAVE_MODEL_EVERY = 25\r\n\r\n epsilon = EPSILON_START\r\n env = gym.make('LunarLander-v2')\r\n # env = gym.make('CartPole-v1')\r\n\r\n observation = env.reset()\r\n # obs2 = np.random.random(4)\r\n # allObs = np.array([observation,obs2])\r\n\r\n\r\n\r\n rb = ReplayBuffer(30000)\r\n agent = DQNAgent(Model(env.observation_space.shape,env.action_space.n,lr=0.01), Model(env.observation_space.shape,env.action_space.n,lr=0.01) )\r\n if LOAD_MODEL:\r\n agent.model.load_state_dict(torch.load(\"\"+MODEL_ID+MODEL_FILE_NAME))\r\n agent.model.eval()\r\n step_counter = 0\r\n avg_reward = []\r\n # qeval = m(torch.Tensor(allObs))\r\n # # print(\"allObs \", allObs)\r\n # # print(\"qeval \",qeval)\r\n\r\n\r\n for game in range (NUM_GAMES):\r\n # if game == 8:\r\n # print(\"rb \",rb.buffer)\r\n episode_sars = []\r\n if game%TARGET_MODEL_UPDATE_INTERVAL == 0 :\r\n print(\"game\", game,\" updating target model\")\r\n agent.update_target_model()\r\n for step in range (MAX_EPISODE_STEPS):\r\n if RENDER_ENV:\r\n env.render()\r\n # import ipdb; ipdb.set_trace()\r\n action = 0\r\n if step_counter<2000 or random()<epsilon or game%RANDOM_GAME_EVERY==0:\r\n action = env.action_space.sample()\r\n # print(\"random action\")\r\n else:\r\n action = agent.get_actions(observation).item()\r\n # print(\"*** action \",action)\r\n # action = action.data.cpu()\r\n\r\n observation_next, reward, done, info = env.step(action)\r\n # if done and reward <=-100:\r\n # reward = -300\r\n _sars = sars(observation,action,reward,observation_next,done,0.0)\r\n episode_sars.append(_sars)\r\n avg_reward.append([reward])\r\n # if(reward==-100):\r\n # print(\"Adding -100 \",reward)\r\n if rb.index > 3000 and step_counter%TRAIN_EVERY_N_STEPS==0:\r\n # import ipdb; ipdb.set_trace()\r\n\r\n for s in range(TRAINING_ITTERATIONS):\r\n dick = rb.sample(TRAINING_SAMPLE_SIZE,step)\r\n train_step(agent.model,dick,agent.targetModel,env.action_space.n)\r\n # print(\"training size \",rb.index%rb.buffer_size, \" - sample \",dick)\r\n observation = observation_next\r\n step_counter+=1\r\n if done:\r\n\r\n\r\n # print(\"last reward \", reward)\r\n\r\n episode_sars = update_Qs(episode_sars,step_counter,step,len(episode_sars))\r\n for j in range(len(episode_sars)):\r\n rb.insert(episode_sars[j])\r\n\r\n if(SAVE_MODEL and game%SAVE_MODEL_EVERY==0 and game>50):\r\n # torch.save(agent.model.state_dict(),\"\"+MODEL_ID+MODEL_FILE_NAME)\r\n torch.save(agent.model,\"\"+MODEL_ID+MODEL_FILE_NAME)\r\n\r\n\r\n observation = env.reset()\r\n break\r\n\r\n\r\n epsilon = max(EPSILON_MIN, epsilon-((EPSILON_START-EPSILON_MIN)/EPSLILON_COUNT) )\r\n if (game%PRINT_EVERY==0):\r\n print(\"episide \", game,\"last score\",reward ,\"episode_len\", len(episode_sars),\"buffer\",len(rb.buffer), \"score\", np.average( avg_reward), \"epsilon\",epsilon )\r\n avg_reward = []\r\n # print(\"epsilon \", epsilon)\r\n", "## DQN Tutorial\r\n## https://www.youtube.com/watch?v=WHRQUZrxxGw\r\nimport torch\r\nimport gym\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport numpy as np\r\nfrom dataclasses import dataclass\r\nfrom typing import Any\r\nfrom random import random\r\n\r\n@dataclass\r\nclass sars:\r\n state: Any\r\n action: int\r\n reward: float\r\n next_state: Any\r\n done: bool\r\n qval: float\r\n\r\nclass DQNAgent:\r\n def __init__(self,model,targetModel):\r\n self.model = model\r\n self.targetModel = targetModel\r\n\r\n def get_actions(self, observations):\r\n q_vals = self.model(torch.Tensor(observations).to(self.model.device))\r\n return q_vals.max(-1)[1]\r\n\r\n def update_target_model(self):\r\n self.targetModel.load_state_dict(self.model.state_dict())\r\n\r\nclass Model(nn.Module):\r\n def __init__(self, obs_shape, num_actions,lr):\r\n super(Model,self).__init__()\r\n assert len(obs_shape) ==1, \"This network only works on flat observations\"\r\n self.obs_shape = obs_shape\r\n self.num_action = num_actions\r\n\r\n self.net = torch.nn.Sequential(\r\n torch.nn.Linear(obs_shape[0],128),\r\n torch.nn.ReLU(),\r\n torch.nn.Linear(128,num_actions)\r\n )\r\n self.opt = optim.Adam(self.net.parameters(),lr=lr)\r\n if torch.cuda.is_available():\r\n print(\"Using CUDA\")\r\n self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cuda:1')\r\n self.to(self.device)\r\n\r\n\r\n def forward(self, x):\r\n return self.net(x)\r\n\r\n\r\n\r\nclass ReplayBuffer:\r\n def __init__(self, buffer_size = 1000):\r\n self.buffer_size = buffer_size\r\n # self.buffer = [None]*buffer_size\r\n self.buffer = []\r\n self.index = 0\r\n\r\n def insert(self, sars):\r\n # self.buffer.append(sars)\r\n # print(\"inserting index \", self.index, \"@\",self.index%self.buffer_size)\r\n if(self.index == 10):\r\n print(\"first 10 \",self.buffer[0:10])\r\n # import ipdb; ipdb.set_trace()\r\n\r\n # if(self.index > self.buffer_size and self.index%self.buffer_size==0):\r\n # print(\"first 10 \",self.buffer[0:10])\r\n # print(\"last 10 \",self.buffer[-10:])\r\n # print(\"\")\r\n # import ipdb; ipdb.set_trace()\r\n # self.buffer[self.index%self.buffer_size] = sars\r\n self.index+=1\r\n self.buffer.append(sars)\r\n if(len(self.buffer)>self.buffer_size):\r\n self.buffer = self.buffer[1:]\r\n # print(\"Clipping Buffer at size\", len(self.buffer))\r\n\r\n def sample(self, num_samples,current_episode_steps):\r\n # assert num_samples < min(len(self.buffer),self.index)\r\n # if num_samples>self.index:\r\n # print(\"sampling n \",min(num_samples,self.index))\r\n # a = self.buffer[0:((self.index-current_episode_steps)%self.buffer_size)]\r\n if len(self.buffer) > 0:\r\n return np.random.choice(self.buffer, min(num_samples,self.index))\r\n else:\r\n return []\r\n\r\n\r\n\r\ndef get_one_hot(action,n_dim):\r\n retval = np.zeros(n_dim)\r\n retval[action] = 1.0\r\n return retval\r\n\r\n\r\ndef train_step(model, state_transitions, tgt, num_actions):\r\n if len(state_transitions) <=0:\r\n print(\"empty state transitions\")\r\n return\r\n cur_states = torch.stack( ([torch.Tensor(s.state) for s in state_transitions]) ).to(model.device)\r\n rewards = torch.stack( ([torch.Tensor([s.reward]) for s in state_transitions]) ).to(model.device)\r\n Qs = torch.stack( ([torch.Tensor([s.qval]) for s in state_transitions]) ).to(model.device)\r\n mask = torch.stack(([torch.Tensor([0]) if s.done else torch.Tensor([1]) for s in state_transitions])).to(model.device)\r\n next_states = torch.stack( ([torch.Tensor(s.next_state) for s in state_transitions]) ).to(model.device)\r\n actions = [s.action for s in state_transitions]\r\n # import ipdb; ipdb.set_trace()\r\n with torch.no_grad():\r\n # actual_Q_values = Qs\r\n pred_qvals_next = model(next_states).max(-1)[0]\r\n model.opt.zero_grad()\r\n pred_qvals = model(cur_states)\r\n\r\n one_hot_actions = F.one_hot(torch.LongTensor(actions),num_actions).to(model.device)\r\n # loss = torch.mean(torch.sqrt((torch.sum(pred_qvals*one_hot_actions,-1) - actual_Q_values.view(-1) )**2)).to(model.device)\r\n # loss = F.smooth_l1_loss(torch.sum(pred_qvals*one_hot_actions,-1), actual_Q_values.view(-1) )\r\n loss = F.smooth_l1_loss(torch.sum(pred_qvals*one_hot_actions,-1), rewards.view(-1)+0.99*mask[:,0]*pred_qvals_next.view(-1) ).mean()\r\n loss.backward()\r\n model.opt.step()\r\n return loss\r\n\r\n\r\n\r\n\r\n\r\ndef update_Qs(replay_buffer,step_counter,episode_len,buffer_size):\r\n for i in range(episode_len):\r\n # if(step_counter > buffer_size):\r\n # import ipdb; ipdb.set_trace()\r\n index = episode_len-i\r\n next_index = index+1\r\n if i==0:\r\n replay_buffer[index].qval = replay_buffer[index].reward\r\n if(step_counter%2000==0):\r\n print(\"i\",i,\"q \",replay_buffer[index].qval)\r\n else:\r\n replay_buffer[index].qval = replay_buffer[index].reward + 0.99 * replay_buffer[next_index].qval\r\n if(step_counter%2000==0):\r\n print(\"i\",i,\"q \",replay_buffer[index].qval)\r\n return replay_buffer\r\n\r\n\r\nif __name__=='__main__':\r\n DEBUGER_ON = True\r\n NUM_GAMES = 50000\r\n MAX_EPISODE_STEPS = 1490\r\n TARGET_MODEL_UPDATE_INTERVAL = 50\r\n EPSILON_MIN = 0.05\r\n EPSILON_START = 0.5\r\n EPSLILON_COUNT = 6000 #Games\r\n RANDOM_GAME_EVERY = 20\r\n TRAIN_EVERY_N_STEPS = 25\r\n TRAINING_SAMPLE_SIZE = 256\r\n TRAINING_ITTERATIONS = 1\r\n PRINT_EVERY = 1\r\n RENDER_ENV = True\r\n LOAD_MODEL = True\r\n SAVE_MODEL = False\r\n MODEL_FILE_NAME = \"TDQN_RL_MODEL.trl\"\r\n MODEL_ID = \"01\"\r\n SAVE_MODEL_EVERY = 25\r\n\r\n epsilon = EPSILON_START\r\n env = gym.make('LunarLander-v2')\r\n # env = gym.make('CartPole-v1')\r\n\r\n observation = env.reset()\r\n agent = DQNAgent(Model(env.observation_space.shape,env.action_space.n,lr=0.0001), Model(env.observation_space.shape,env.action_space.n,lr=0.0001) )\r\n if LOAD_MODEL:\r\n print(\"Loading Model \", \"\"+MODEL_ID+MODEL_FILE_NAME)\r\n agent.model = torch.load(\"\"+MODEL_ID+MODEL_FILE_NAME)\r\n agent.model.eval()\r\n step_counter = 0\r\n avg_reward = []\r\n last_step_count = 0\r\n # qeval = m(torch.Tensor(allObs))\r\n # # print(\"allObs \", allObs)\r\n # # print(\"qeval \",qeval)\r\n\r\n\r\n for game in range (NUM_GAMES):\r\n # if game == 8:\r\n # print(\"rb \",rb.buffer)\r\n score = 0\r\n\r\n for step in range (MAX_EPISODE_STEPS):\r\n if RENDER_ENV:\r\n env.render()\r\n # import ipdb; ipdb.set_trace()\r\n action = 0\r\n action = agent.get_actions(observation).item()\r\n\r\n\r\n observation_next, reward, done, info = env.step(action)\r\n\r\n score += reward\r\n\r\n observation = observation_next\r\n step_counter+=1\r\n last_step_count = step\r\n if done:\r\n\r\n observation = env.reset()\r\n break\r\n\r\n\r\n epsilon = max(EPSILON_MIN, epsilon-((EPSILON_START-EPSILON_MIN)/EPSLILON_COUNT) )\r\n if (game%PRINT_EVERY==0):\r\n print(\"episide \", game,\"last score\",reward, \"game score \", score ,\"episode_len\",last_step_count, \"epsilon\",epsilon )\r\n avg_reward = []\r\n # print(\"epsilon \", epsilon)\r\n", "'''\nSee https://github.com/FitMachineLearning/rocket-lander for complete repo\nRocket Lander Continuous Walker with\n - Selective Memory\n - Actor Critic\n - Parameter Noising\n - Q as discriminator\nsolution by Michel Aka author of FitML github blog and repository\nhttps://github.com/FitMachineLearning/FitML/\nhttps://www.youtube.com/channel/UCi7_WxajoowBl4_9P0DhzzA/featured\nUpdate\nDeep Network\nStarts to Land at episode 400\n\nAdagrad\n0.99 delta\n0.1 dropout\n\n'''\nfrom environments.rocketlander import RocketLander\nimport tensorflow as tf\nimport numpy as np\nimport gym\nimport pybullet\nimport pybullet_envs\n\nimport pygal\nimport os\nimport h5py\n#import matplotlib.pyplot as plt\nimport math\n\nfrom keras import optimizers\n\n\nPLAY_GAME = False #Set to True if you want to agent to play without training\nuses_critic = True\nuses_parameter_noising = False\n\nnum_env_variables = 8\nnum_env_actions = 3\nnum_initial_observation = 8\nlearning_rate = 0.003\napLearning_rate = 0.001\nbig_sigma = 0.0006\nlittl_sigma = 0.00006\nupper_delta = 0.0015\nlower_delta = 0.0010\nENVIRONMENT_NAME = \"RocketBulletEnv-v0\"\nversion_name = ENVIRONMENT_NAME + \"With_PN_v10\"\nweigths_filename = version_name+\"-weights.h5\"\napWeights_filename = version_name+\"-weights-ap.h5\"\n\n\n#range within wich the SmartCrossEntropy action parameters will deviate from\n#remembered optimal policy\nsce_range = 0.2\nb_discount = 0.99\nmax_memory_len = 500000\nexperience_replay_size = 10000\nrandom_every_n = 20\nnum_retries = 60\nstarting_explore_prob = 0.05\ntraining_epochs = 3\nmini_batch = 512\nload_previous_weights = False\nobserve_and_train = True\nsave_weights = True\nsave_memory_arrays = True\nload_memory_arrays = False\ndo_training = True\nnum_games_to_play = 6000\nrandom_num_games_to_play = num_games_to_play\nmax_steps =995\n\n#Selective memory settings\nsm_normalizer = 20\nsm_memory_size = 10500\n\nlast_game_average = -1000\nlast_best_noisy_game = -1000\nmax_game_average = -1000\nnoisy_game_no_longer_valid = False\n\n\n#Create testing enviroment\n\nsettings = {'Side Engines': True,\n 'Clouds': True,\n 'Vectorized Nozzle': True,\n 'Starting Y-Pos Constant': 1,\n 'Initial Force': 'random'} # (6000, -10000)}\n\nenv = RocketLander(settings)\nenv.refresh(render=True)\nenv.render(mode=\"human\")\nenv.reset()\n\n\n\nprint(\"-- Observations\",env.observation_space)\nprint(\"-- actionspace\",env.action_space)\n\n#initialize training matrix with random states and actions\n#dataX = np.random.random(( 5,num_env_variables+num_env_actions ))\ndataX = tf.placeholder(\"float\", [None, num_env_variables+num_env_actions])\n\n#Only one output for the total score / reward\n#dataY = np.random.random((5,1))\ndataY = tf.placeholder(\"float\", [None, 1])\n\n\n#initialize training matrix with random states and actions\n#apdataX = np.random.random(( 5,num_env_variables ))\napdataX = tf.placeholder(\"float\", [None, num_env_variables])\n#apdataY = np.random.random((5,num_env_actions))\napdataY = tf.placeholder(\"float\", [None, num_env_actions])\n\n\ndef init_weights(shape):\n return tf.Variable(tf.random_normal(shape, stddev=0.01))\n\ndef Qmodel(X, w_h,w_h2,w_h3, w_o):\n h = tf.nn.leaky_relu(tf.matmul(X, w_h)) # this is a basic mlp, think 2 stacked logistic regressions\n h2 = tf.nn.leaky_relu(tf.matmul(h, w_h2)) # this is a basic mlp, think 2 stacked logistic regressions\n h3 = tf.nn.leaky_relu(tf.matmul(h2, w_h3)) # this is a basic mlp, think 2 stacked logistic regressions\n return tf.matmul(h3, w_o) # note that we dont take the softmax at the end because our cost fn does that for us\n\ndef apModel(X, apw_h,apw_h2,apw_h3, apw_o):\n h = tf.nn.leaky_relu(tf.matmul(X, apw_h)) # this is a basic mlp, think 2 stacked logistic regressions\n h2 = tf.nn.leaky_relu(tf.matmul(h, apw_h2)) # this is a basic mlp, think 2 stacked logistic regressions\n h3 = tf.nn.leaky_relu(tf.matmul(h2, apw_h3)) # this is a basic mlp, think 2 stacked logistic regressions\n return tf.matmul(h2, apw_o) # note that we dont take the softmax at the end because our cost fn does that for us\n\n''' QModel '''\nQw_h = init_weights([num_env_variables+num_env_actions, 32]) # create symbolic variables\nQw_h2 = init_weights([32, 32]) # create symbolic variables\nQw_h3 = init_weights([32, 32]) # create symbolic variables\nQw_o = init_weights([32, 1])\n\nQpy_x = Qmodel(dataX, Qw_h,Qw_h2,Qw_h3, Qw_o)\n\n\nQcost = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(dataY, Qpy_x))))\nQoptimizer = tf.train.AdadeltaOptimizer(1.,0.9,1e-6)\nQtrain_op = Qoptimizer.minimize(Qcost)\n\n''' apModel '''\napw_h = init_weights([num_env_variables, 32]) # create symbolic variables\napw_h2 = init_weights([32, 32]) # create symbolic variables\napw_h3 = init_weights([32, 32]) # create symbolic variable\napw_o = init_weights([32, num_env_actions])\n\nappy_x = apModel(apdataX, apw_h,apw_h2,apw_h3, apw_o)\n\napcost = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(apdataY, appy_x))))\napOptimizer = tf.train.AdadeltaOptimizer(1.,0.9,1e-6)\naptrain_op = apOptimizer.minimize(apcost)\n\n\n''' naModel '''\nnaw_h = init_weights([num_env_variables, 32]) # create symbolic variables\nnaw_h2 = init_weights([32, 32]) # create symbolic variables\nnaw_h3 = init_weights([32, 32]) # create symbolic variable\nnaw_o = init_weights([32, num_env_actions])\n\nnapy_x = apModel(apdataX, naw_h, naw_h2, naw_h3, naw_o)\n\nnacost = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(apdataY, napy_x))))\nnaOptimizer = tf.train.AdadeltaOptimizer(1.,0.9,1e-6)\nnatrain_op = apOptimizer.minimize(apcost)\n#natrain_op = tf.train.AdadeltaOptimizer(1).minimize(nacost)\n\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n\n''' LOAD MODEL\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 Qmodel.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\nmemorySA = np.zeros(shape=(1,num_env_variables+num_env_actions))\nmemoryS = np.zeros(shape=(1,num_env_variables))\nmemoryA = np.zeros(shape=(1,1))\nmemoryR = np.zeros(shape=(1,1))\nmemoryRR = np.zeros(shape=(1,1))\nmemoryW = np.zeros(shape=(1,1))\n\nBestGameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\nBestGameS = np.zeros(shape=(1,num_env_variables))\nBestGameA = np.zeros(shape=(1,num_env_actions))\nBestGameR = np.zeros(shape=(1,1))\nBestGameW = np.zeros(shape=(1,1))\n\nif load_memory_arrays:\n if os.path.isfile(version_name+'memorySA.npy'):\n print(\"Memory Files exist. Loading...\")\n memorySA = np.load(version_name+'memorySA.npy')\n memoryRR = np.load(version_name+'memoryRR.npy')\n memoryS = np.load(version_name+'memoryS.npy')\n memoryA = np.load(version_name+'memoryA.npy')\n memoryR = np.load(version_name+'memoryR.npy')\n memoryW = np.load(version_name+'memoryW.npy')\n\n else:\n print(\"No memory Files. Recreating\")\n\n\nmstats = []\nmGames = []\nmAverageScores = []\nmSteps = []\nmAP_Counts = 0\nnum_add_mem = 0\nmAPPicks = []\n\ndef GenerateSampleAction(dim=3):\n retVal = np.random.rand(3)\n retVal = retVal -0.5\n retVal = retVal * 2\n return retVal\n\n# --- Parameter Noising\ndef add_noise(mu, largeNoise=False):\n\n if not largeNoise:\n sig = littl_sigma\n else:\n #print(\"Adding Large parameter noise\")\n sig = big_sigma #Sigma = width of the standard deviaion\n #mu = means\n x = np.random.rand(1) #probability of doing x\n #print (\"x prob \",x)\n if x >0.5:\n return mu + np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))\n else:\n return mu - np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))\n\n# --- Parameter Noising\ndef add_noise_simple(mu, largeNoise=False):\n x = np.random.rand(1) - 0.5 #probability of doing x\n if not largeNoise:\n x = x*littl_sigma\n else:\n x = x*big_sigma #Sigma = width of the standard deviaion\n #print (\"x/200\",x)\n return mu + x\n\n\n#add_noise_simple = np.vectorize(add_noise_simple,otypes=[np.float])\nadd_noise = np.vectorize(add_noise,otypes=[np.float])\nadd_noise_simple = np.vectorize(add_noise_simple,otypes=[np.float])\n\n\n\ndef add_noise_TF(largeNoise = False):\n variables_names =[v.name for v in tf.trainable_variables()]\n values = sess.run(variables_names)\n #for k,v in zip(variables_names, values):\n # if(k==naw_h.name):\n # print(k, v)\n for k,v in zip(variables_names, values):\n if(k==naw_h.name):\n v2=add_noise_simple(v,True)\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op = tf.assign(naw_h,v2)\n sess.run(assign_op)\n\n #for k,v in zip(variables_names, values):\n # if(k==naw_o.name):\n # print(k, v)\n for k,v in zip(variables_names, values):\n if(k==naw_h2.name):\n v2=add_noise_simple(v,True)\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op2 = tf.assign(naw_h2,v2)\n sess.run(assign_op2)\n\n #for k,v in zip(variables_names, values):\n # if(k==naw_o.name):\n # print(k, v)\n for k,v in zip(variables_names, values):\n if(k==naw_h3.name):\n v2=add_noise_simple(v,True)\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op2 = tf.assign(naw_h3,v2)\n sess.run(assign_op2)\n\n #for k,v in zip(variables_names, values):\n # if(k==naw_o.name):\n # print(k, v)\n for k,v in zip(variables_names, values):\n if(k==naw_o.name):\n v2=add_noise_simple(v,True)\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op2 = tf.assign(naw_o,v2)\n sess.run(assign_op2)\n '''\n variables_names =[v.name for v in tf.trainable_variables()]\n values = sess.run(variables_names)\n for k,v in zip(variables_names, values):\n if(k==naw_h.name):\n print(k, v)\n '''\n return None\n\ndef reset_noisy_model_TF():\n variables_names =[v.name for v in tf.trainable_variables()]\n values = sess.run(variables_names)\n\n ## RESET FIRST LAYER\n for k,v in zip(variables_names, values):\n if(k==apw_h.name):\n v2=v+0.000000000000000001\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op = tf.assign(naw_h,v2)\n sess.run(assign_op)\n\n ## RESET FIRST LAYER\n for k,v in zip(variables_names, values):\n if(k==apw_h2.name):\n v2=v+0.000000000000000001\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op = tf.assign(naw_h2,v2)\n sess.run(assign_op)\n\n ## RESET LAST LAYER\n for k,v in zip(variables_names, values):\n if(k==apw_o.name):\n v2=v+0.000000000000000001\n #v2 = v+0.001\n #print(\"Noise added. showing res v2\",v2)\n assign_op = tf.assign(naw_o,v2)\n sess.run(assign_op)\n\n '''\n variables_names =[v.name for v in tf.trainable_variables()]\n values = sess.run(variables_names)\n for k,v in zip(variables_names, values):\n if(k==naw_h.name):\n print(k, v)\n '''\n return None\n\n\n# --- Parameter Noising\n\ndef predictTotalRewards(qstate, action):\n qs_a = np.concatenate((qstate,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 = Qmodel.predict(predX[0].reshape(1,predX.shape[1]))\n inputVal = predX[0].reshape(1,predX.shape[1])\n pred = sess.run(Qpy_x, feed_dict={dataX: inputVal})\n remembered_total_reward = pred[0][0]\n return remembered_total_reward\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\n inputVal = predX[0].reshape(1,predX.shape[1])\n pred = sess.run(appy_x, feed_dict={apdataX: inputVal})\n r_remembered_optimal_policy = pred[0]\n return r_remembered_optimal_policy\n\ndef GetRememberedOptimalPolicyFromNoisyModel(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 = targetModel.predict(predX[0].reshape(1,predX.shape[1]))\n inputVal = predX[0].reshape(1,predX.shape[1])\n pred = sess.run(napy_x, feed_dict={apdataX: inputVal})\n\n r_remembered_optimal_policy = pred[0]\n return r_remembered_optimal_policy\n\ndef addToMemory(reward,mem_mean,memMax,averegeReward,gameAverage,mstd):\n target = mem_mean + math.fabs((memMax-mem_mean)/2)\n d_target_max = math.fabs(memMax-target)\n d_target_reward = math.fabs(reward-target)\n advantage = d_target_reward / d_target_max\n gameAdvantage = math.fabs((averegeReward-gameAverage)/(averegeReward-memMax))\n prob = 0.000000000000005\n if gameAdvantage < 0.05:\n gameAdvantage = 0.000000000000005\n if reward > target:\n return True, 0.0000000005 + (1-0.0000000005)*advantage #*gameAdvantage\n else:\n return False, 0.000000000000005\n\n\n\ndef pr_actor_experience_replay(memSA,memR,memS,memA,memW,num_epoch=1):\n for num_epoch in range(training_epochs):\n tSA = (memSA)+0.0\n tR = (memR)+0.0\n tX = (memS)+0.0\n tY = (memA)+0.0\n tW = (memW)+0.0\n tS = memW +0.0\n\n game_max = tW.max()+0.0\n gameAverage = memR.mean()\n treshold = memR.flatten()[-5000:].mean()\n\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n tSA = tSA[train_A,:]\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n tR = tR[train_A,:]\n tS = tS[train_A,:]\n\n tX_train = np.zeros(shape=(1,num_env_variables))\n tY_train = np.zeros(shape=(1,num_env_actions))\n for i in range(np.alen(tR)):\n pr = predictTotalRewards(tX[i],GetRememberedOptimalPolicy(tX[i]))\n #print (\"tR[i]\",tR[i],\"pr\",pr)\n d = math.fabs( memoryR.max() - pr)\n tW[i]= 0.0000000000000005\n if (tR[i]>pr and tS[i]>gameAverage):\n tW[i]=0.005\n if (tR[i]>pr and tS[i]>treshold):\n tW[i]=0.55\n if (tR[i]>pr+d*0.005 and tR[i]>game_max) :\n tW[i] = 1\n if tW[i]> np.random.rand(1):\n tX_train = np.vstack((tX_train,tX[i]))\n tY_train = np.vstack((tY_train,tY[i]))\n\n\n tX_train = tX_train[1:]\n tY_train = tY_train[1:]\n print(num_epoch,\"%8d were better After removing first element\"%np.alen(tX_train))\n if np.alen(tX_train)>0:\n #action_predictor_model.fit(tX_train,tY_train, batch_size=mini_batch, nb_epoch=num_epochs,verbose=0)\n for t in range(25):\n sess.run(aptrain_op, feed_dict={apdataX: tX_train, apdataY: tY_train})\n\n\n\n\n\ndef actor_experience_replay(memSA,memR,memS,memA,memW,num_epoch=1):\n tSA = (memSA)\n tR = (memR)\n tX = (memS)\n tY = (memA)\n tW = (memW)\n\n target = tR.mean() #+ math.fabs( tR.mean() - tR.max() )/2 #+ math.fabs( tR.mean() - tR.max() )/4\n train_C = np.arange(np.alen(tR))\n train_C = train_C[tR.flatten()>target]\n tX = tX[train_C,:]\n tY = tY[train_C,:]\n tW = tW[train_C,:]\n tR = tR[train_C,:]\n\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n tR = tR[train_A,:]\n\n train_B = np.arange(np.alen(tR))\n\n tX_train = np.zeros(shape=(1,num_env_variables))\n tY_train = np.zeros(shape=(1,num_env_actions))\n for i in range(np.alen(train_B)):\n #pr = predictTotalRewards(tX[i],tY[i])\n ''' YOU CAN\"T USE predictTotalRewards\n IF YOU DON\"T TRAIN THE QMODEL\n\n if tR[i][0] < pr:\n tW[i][0] = -1\n else:\n '''\n d = math.fabs( memoryR.max() - target)\n tW[i] = math.fabs(tR[i]-(target+0.000000000005)) / d\n #tW[i] = math.exp(1-(1/tW[i]**2))\n\n\n tW[i]= 0.0000000000000005\n if (tR[i]>target):\n tW[i]=0.5\n if (tR[i]>max_game_average):\n tW[i] = 1\n\n if tW[i]> np.random.rand(1):\n tX_train = np.vstack((tX_train,tX[i]))\n tY_train = np.vstack((tY_train,tY[i]))\n\n\n #print (\"tW\",tW[i],\"exp\", math.exp(1-(1/tW[i]**2)))\n #tW[i] = math.exp(1-(1/tW[i]**2))\n #tW[i] = 1\n #print(\"tW[i] %3.1f tR %3.2f target %3.2f max_game_average %3.2f \"%(tW[i],tR[i],target,max_game_average))\n '''\n train_B = train_B[tW.flatten()>0]\n\n #print(\"%8d were better results than pr\"%np.alen(tX_train))\n\n tX = tX[train_B,:]\n tY = tY[train_B,:]\n tW = tW[train_B,:]\n tR = tR[train_B,:]\n #print(\"tW\",tW)\n '''\n #print(\"%8d were better results than pr\"%np.alen(tX_train))\n ''' REMOVE FIRST ELEMENT BEFORE TRAINING '''\n tX_train = tX_train[1:]\n tY_train = tY_train[1:]\n #print(\"%8d were better After removing first element\"%np.alen(tX_train))\n if np.alen(tX_train)>0:\n #tW = scale_weights(tR,tW)\n #print(\"# setps short listed \", np.alen(tR))\n\n #action_predictor_model.fit(tX_train,tY_train, batch_size=mini_batch, nb_epoch=num_epochs,verbose=0)\n for num_epoch in range(training_epochs):\n sess.run(aptrain_op, feed_dict={apdataX: tX_train, apdataY: tY_train})\n\n\n\ndef train_noisy_actor():\n tX = (memoryS)\n tY = (memoryA)\n tW = (memoryW)\n\n train_A = np.random.randint(tY.shape[0],size=int(min(experience_replay_size,np.alen(tY) )))\n tX = tX[train_A,:]\n tY = tY[train_A,:]\n tW = tW[train_A,:]\n\n #noisy_model.fit(tX,tY, batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)\n for num_epoch in range(training_epochs):\n sess.run(natrain_op, feed_dict={apdataX: tX, apdataY: tY})\n\n\n\ndef add_controlled_noise(targetModel,big_sigma,largeNoise = False):\n tR = (memoryR)\n tX = (memoryS)\n tY = (memoryA)\n tW = (memoryW)\n train_C = np.random.randint(tY.shape[0],size=100)\n\n tX = tX[train_C,:]\n tY_old = tY[train_C,:]\n tY_new = tY[train_C,:]\n diffs = np.zeros(np.alen(tX))\n delta = 1000\n deltaCount = 0\n\n for i in range(np.alen(tX)):\n a = GetRememberedOptimalPolicyFromNoisyModel(tX[i])\n a = a.flatten()\n #print(\"Output Before noise \",a)\n\n\n while ( delta > upper_delta or delta < lower_delta) and deltaCount <5:\n reset_noisy_model_TF()\n targetModel\n #noisy_model.set_weights(action_predictor_model.get_weights())\n add_noise_TF(largeNoise)\n for i in range(np.alen(tX)):\n b = GetRememberedOptimalPolicyFromNoisyModel(tX[i])\n b = b.flatten()\n\n c = np.abs(a-b)\n delta = c.mean()\n deltaCount+=1\n if delta > upper_delta:\n big_sigma = big_sigma *0.9\n print(\"Delta\",delta,\" out of bound adjusting big_sigma\", big_sigma)\n\n if delta < lower_delta:\n big_sigma = big_sigma *1.1\n print(\"Delta\",delta,\" out of bound adjusting big_sigma\", big_sigma)\n\n print(\"Tried x time \", deltaCount,\"delta =\", delta)\n\n return big_sigma\n\n\n\n#Play the game 500 times\nfor game in range(num_games_to_play):\n gameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\n gameS = np.zeros(shape=(1,num_env_variables))\n gameA = np.zeros(shape=(1,num_env_actions))\n gameR = np.zeros(shape=(1,1))\n gameW = np.zeros(shape=(1,1))\n #Get the Q state\n qs = env.reset()\n env.refresh(render=True)\n\n mAP_Counts = 0\n num_add_mem = 0\n #print(\"qs \", qs)\n is_noisy_game = False\n\n #noisy_model.set_weights(action_predictor_model.get_weights())\n\n #Add noise to Actor\n if game > num_initial_observation and uses_parameter_noising:\n is_noisy_game = False\n #print(\"Adding Noise\")\n if (game%2==0 ):\n is_noisy_game = True\n if noisy_game_no_longer_valid or game %50==0:\n print(\"Adding BIG Noise\")\n #noisy_model = keras.models.clone_model(action_predictor_model)\n reset_noisy_model_TF()\n big_sigma = add_controlled_noise(None,big_sigma,True)\n #last_best_noisy_game = -1000\n #else:\n # print(\"Adding Small Noise\")\n # #print(\"Not Changing weights last_best_noisy_game\", last_best_noisy_game,\" mean \",memoryR.mean())\n # reset_noisy_model_TF()\n # big_sigma = add_controlled_noise(None,big_sigma,True)\n\n\n\n for step in range (5000):\n\n if PLAY_GAME:\n remembered_optimal_policy = GetRememberedOptimalPolicy(qs)\n a = remembered_optimal_policy\n elif game < num_initial_observation:\n #take a radmon action\n a = GenerateSampleAction(3)\n else:\n prob = np.random.rand(1)\n explore_prob = starting_explore_prob-(starting_explore_prob/random_num_games_to_play)*game\n\n if game > random_num_games_to_play:\n prob = 0.000001\n #Chose between prediction and chance\n if prob < explore_prob or game%random_every_n==1:\n #take a random action\n a = GenerateSampleAction(3)\n\n else:\n #print(\"Using Actor\")\n if is_noisy_game and uses_parameter_noising:\n remembered_optimal_policy = GetRememberedOptimalPolicyFromNoisyModel(qs)\n else:\n remembered_optimal_policy = GetRememberedOptimalPolicy(qs)\n a = remembered_optimal_policy\n\n if uses_critic:\n #print(\"Using critric\")\n stock = np.zeros(num_retries)\n stockAction = np.zeros(shape=(num_retries,num_env_actions))\n for i in range(num_retries):\n #stockAction[i] = env.action_space.sample()\n stockAction[i] = GenerateSampleAction(3)\n\n stock[i] = predictTotalRewards(qs,stockAction[i])\n best_index = np.argmax(stock)\n randaction = stockAction[best_index]\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 mAP_Counts += 1\n #print(\" | selecting remembered_optimal_policy \",a)\n else:\n a = randaction\n #print(\" - selecting generated optimal policy \",a)\n\n\n# for i in range (np.alen(a)):\n# if a[i] < -1: a[i]=-0.99999999999\n# if a[i] > 1: a[i] = 0.99999999999\n #if step%50==0:\n # print(\"a =>\",a)\n\n env.render()\n env.refresh(render=True)\n\n qs_a = np.concatenate((qs,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 #if done and step<max_steps-3:\n # r = -50\n\n if step ==0:\n gameSA[0] = qs_a\n gameS[0] = qs\n gameR[0] = np.array([r])\n gameA[0] = np.array([r])\n gameW[0] = np.array([0.000000005])\n else:\n gameSA= np.vstack((gameSA, qs_a))\n gameS= np.vstack((gameS, qs))\n gameR = np.vstack((gameR, np.array([r])))\n gameA = np.vstack((gameA, np.array([a])))\n gameW = np.vstack((gameW, np.array([0.000000005])))\n\n if step > max_steps:\n done = True\n\n if done :\n tempGameSA = np.zeros(shape=(1,num_env_variables+num_env_actions))\n tempGameS = np.zeros(shape=(1,num_env_variables))\n tempGameA = np.zeros(shape=(1,num_env_actions))\n tempGameR = np.zeros(shape=(1,1))\n tempGameRR = np.zeros(shape=(1,1))\n tempGameW = np.zeros(shape=(1,1))\n\n #Calculate Q values from end to start of game\n #mstats.append(step)\n for i in range(0,gameR.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 gameR[(gameR.shape[0]-1)-i][0] = gameR[(gameR.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 gameR[(gameR.shape[0]-1)-i][0] = gameR[(gameR.shape[0]-1)-i][0]+b_discount*gameR[(gameR.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\n if memoryR.shape[0] ==1:\n memorySA = gameSA\n memoryR = gameR\n memoryA = gameA\n memoryS = gameS\n memoryRR = gameR\n memoryW = gameW\n\n tempGameA = tempGameA[1:]\n tempGameS = tempGameS[1:]\n tempGameRR = tempGameRR[1:]\n tempGameR = tempGameR[1:]\n tempGameSA = tempGameSA[1:]\n tempGameW = tempGameW[1:]\n\n\n for i in range(gameR.shape[0]):\n tempGameSA = np.vstack((tempGameSA,gameSA[i]))\n tempGameR = np.vstack((tempGameR,gameR[i]))\n\n #print(\"add_prob\",add_prob)\n tempGameA = np.vstack((tempGameA,gameA[i]))\n tempGameS = np.vstack((tempGameS,gameS[i]))\n tempGameRR = np.vstack((tempGameRR,gameR[i]))\n tempGameW = np.vstack((tempGameW,gameR.mean()))\n\n\n #train actor network based on last rollout\n if game>3:\n tX = (tempGameS)\n tY = (tempGameA)\n tW = (tempGameW)\n #action_predictor_model.fit(tX,tY,sample_weight=tW.flatten(), batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)\n\n\n\n if memoryR.shape[0] ==1:\n memoryA = tempGameA\n memoryS = tempGameS\n memoryRR = tempGameRR\n memoryR = tempGameR\n memorySA = tempGameSA\n memoryW = tempGameW\n else:\n #Add experience to memory\n memoryS = np.concatenate((memoryS,tempGameS),axis=0)\n memoryRR = np.concatenate((memoryRR,tempGameRR),axis=0)\n memoryA = np.concatenate((memoryA,tempGameA),axis=0)\n memorySA = np.concatenate((memorySA,tempGameSA),axis=0)\n\n memoryR = np.concatenate((memoryR,tempGameR),axis=0)\n memoryW = np.concatenate((memoryW,tempGameW),axis=0)\n\n\n if gameR.mean() > max_game_average :\n max_game_average = gameR.mean()\n\n #if memory is full remove first element\n if np.alen(memoryR) >= max_memory_len:\n memorySA = memorySA[gameR.shape[0]:]\n memoryR = memoryR[gameR.shape[0]:]\n memoryA = memoryA[gameR.shape[0]:]\n memoryS = memoryS[gameR.shape[0]:]\n memoryRR = memoryRR[gameR.shape[0]:]\n memoryW = memoryW[gameR.shape[0]:]\n\n\n qs=s\n\n if done and game > num_initial_observation and not PLAY_GAME:\n last_game_average = gameR.mean()\n if is_noisy_game:\n if last_game_average < memoryR.flatten()[-5000:].mean():\n noisy_game_no_longer_valid = True\n else:\n noisy_game_no_longer_valid = False\n #if game >3:\n #actor_experience_replay(gameSA,gameR,gameS,gameA,gameW,1)\n max_game_average = memoryW.max()\n if game > 3 and game %1 ==0:\n # train on all memory\n print(\"Experience Replay\")\n #for i in range(3):\n\n pr_actor_experience_replay(memorySA,memoryR,memoryS,memoryA,memoryW,training_epochs)\n if game > 3 and game %1 ==0 and uses_critic:\n for num_epoch in range(training_epochs):\n tSA = (memorySA)+0.0\n tR = (memoryR)+0.0\n train_A = np.random.randint(tR.shape[0],size=int(min(experience_replay_size,np.alen(tR) )))\n tR = tR[train_A,:]\n tSA = tSA [train_A,:]\n print(num_epoch,\"Training Critic n elements =\", np.alen(tR))\n for t in range(25):\n sess.run(Qtrain_op, feed_dict={dataX: tSA, dataY: tR})\n\n #Qmodel.fit(tSA,tR, batch_size=mini_batch, nb_epoch=training_epochs,verbose=0)\n if game > 3 and game %5 ==-1 and uses_parameter_noising:\n print(\"Training noisy_actor\")\n train_noisy_actor()\n #Reinforce training with best game\n\n ''' SAVE MODEL\n if done and game >= num_initial_observation and not PLAY_GAME:\n if save_weights and game%20 == 0 and game >35:\n #Save model\n #print(\"Saving weights\")\n Qmodel.save_weights(weigths_filename)\n action_predictor_model.save_weights(apWeights_filename)\n\n if save_memory_arrays and game%20 == 0 and game >35:\n np.save(version_name+'memorySA.npy',memorySA)\n np.save(version_name+'memoryRR.npy',memoryRR)\n np.save(version_name+'memoryS.npy',memoryS)\n np.save(version_name+'memoryA.npy',memoryA)\n np.save(version_name+'memoryR.npy',memoryR)\n np.save(version_name+'memoryW.npy',memoryW)\n\n '''\n\n\n if done:\n\n if game%1==0:\n #print(\"Training Game #\",game,\"last everage\",memoryR.mean(),\"max_game_average\",max_game_average,,\"game mean\",gameR.mean(),\"memMax\",memoryR.max(),\"memoryR\",memoryR.shape[0], \"SelectiveMem Size \",memoryRR.shape[0],\"Selective Mem mean\",memoryRR.mean(axis=0)[0], \" steps = \", step )\n if is_noisy_game:\n print(\"Noisy Game # %7d avgScore %8.3f [-1000]avg %8.3f last_game %8.3f max_game_avg %8.3f memory size %8d memMax %8.3f steps %5d\" % (game, memoryR.mean(),memoryR.flatten()[-5000:].mean(), last_game_average, max_game_average , memoryR.shape[0], memoryR.max(), step ) )\n else:\n print(\"Reg Game # %7d avgScore %8.3f [-1000]avg %8.3f last_game %8.3f max_game_avg %8.3f memory size %8d memMax %8.3f steps %5d\" % (game, memoryR.mean(),memoryR.flatten()[-5000:].mean(), last_game_average, max_game_average , memoryR.shape[0], memoryR.max(), step ) )\n\n if game%5 ==0 and np.alen(memoryR)>1000:\n mGames.append(game)\n mSteps.append(step/1000*100)\n mAPPicks.append(mAP_Counts/step*100)\n mAverageScores.append(max(memoryR.mean(), -50)/100*100)\n bar_chart = pygal.HorizontalLine()\n bar_chart.x_labels = map(str, mGames) # Then create a bar graph object\n bar_chart.add('Average score', mAverageScores) # Add some values\n bar_chart.add('percent actor picks ', mAPPicks) # Add some values\n bar_chart.add('percent steps complete ', mSteps) # Add some values\n\n\n bar_chart.render_to_file(version_name+'Performance2_bar_chart.svg')\n\n break\n\n\nplt.plot(mstats)\nplt.show()\n\nif save_weights:\n #Save model\n print(\"Saving weights\")\n Qmodel.save_weights(weigths_filename)\n action_predictor_model.save_weights(apWeights_filename)\n" ]
[ [ "torch.Tensor", "torch.nn.Linear", "torch.cuda.is_available", "torch.nn.ReLU", "numpy.empty" ], [ "numpy.random.random", "numpy.abs", "numpy.alen", "numpy.power", "numpy.arange", "numpy.save", "numpy.concatenate", "numpy.std", "numpy.vectorize", "numpy.argmax", "numpy.random.rand", "numpy.load", "numpy.array", "numpy.zeros", "numpy.vstack", "numpy.random.randint" ], [ "numpy.concatenate", "numpy.random.randint", "tensorflow.subtract", "numpy.argmax", "tensorflow.Session", "tensorflow.trainable_variables", "numpy.load", "numpy.zeros", "tensorflow.matmul", "numpy.alen", "numpy.power", "tensorflow.train.AdadeltaOptimizer", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "numpy.random.rand", "numpy.array", "numpy.abs", "tensorflow.assign", "numpy.vectorize", "numpy.vstack", "tensorflow.random_normal" ], [ "numpy.random.random", "numpy.abs", "numpy.alen", "numpy.power", "numpy.arange", "numpy.save", "numpy.concatenate", "numpy.std", "numpy.vectorize", "numpy.argmax", "numpy.random.rand", "numpy.load", "numpy.array", "numpy.zeros", "numpy.vstack", "numpy.random.randint" ], [ "torch.LongTensor", "torch.Tensor", "torch.load", "torch.sum", "torch.nn.Linear", "torch.no_grad", "torch.cuda.is_available", "torch.nn.ReLU", "numpy.average", "numpy.zeros", "torch.save" ], [ "torch.LongTensor", "torch.Tensor", "torch.load", "torch.sum", "torch.nn.Linear", "torch.no_grad", "torch.cuda.is_available", "torch.nn.ReLU", "numpy.zeros" ], [ "numpy.concatenate", "numpy.random.randint", "tensorflow.subtract", "numpy.argmax", "tensorflow.Session", "tensorflow.trainable_variables", "numpy.load", "numpy.zeros", "tensorflow.matmul", "numpy.alen", "numpy.power", "tensorflow.train.AdadeltaOptimizer", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "numpy.random.rand", "numpy.array", "numpy.abs", "tensorflow.assign", "numpy.vectorize", "numpy.vstack", "tensorflow.random_normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
vandyzhou/wxcloudrun-django
[ "454f9c1ab827543f2635a549ca7e251ed35d9305" ]
[ "wxcloudrun/common/tabledrawer.py" ]
[ "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# @Time : 2022/2/9 12:09 下午\n# @Author: zhoumengjie\n# @File : tabledrawer.py\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\ndef draw_table(columns_head:[], cell_vals=[]):\n # 设置字体及负数\n plt.rcParams['font.sans-serif'] = ['SimHei']\n plt.rcParams['axes.unicode_minus'] = False\n\n # 画布\n fig, ax = plt.subplots(figsize=(10, 4), dpi=100)\n\n # 数据\n data = [\n [100, 200, 300, -100, 350],\n [-120, 290, -90, 450, 150]\n ]\n\n # 列与行\n columns = ('一', '二', '三', '四', '五')\n rows = ['A', 'B']\n\n # 作图参数\n index = np.arange(len(columns)) - 0.1\n bar_width = 0.4\n\n # 设置颜色\n colors = ['turquoise', 'coral']\n\n # 柱状图\n bar1 = plt.bar(index, data[0], bar_width, color=colors[0], edgecolor='grey')\n bar2 = plt.bar(index + bar_width, data[1], bar_width, color=colors[1], edgecolor='grey')\n\n # 设置标题\n ax.set_title('收益情况', fontsize=16, y=1.1, x=0.44)\n ax.set_ylabel('元', fontsize=12, color='black', alpha=0.7, rotation=360)\n ax.set_ylim(-150, 500)\n\n # 显示数据标签\n # ax.bar_label(bar1, label_type='edge')\n # ax.bar_label(bar2, label_type='edge')\n\n # x,y刻度不显示\n ax.tick_params(axis=u'both', which=u'both', length=0)\n plt.xticks([])\n\n table = plt.table(cellText=data, rowLabels=rows,\n rowColours=colors,\n colLabels=columns, cellLoc='center', loc='bottom',\n bbox=[0, -0.4, 1, 0.24])\n\n cellDict = table.get_celld()\n for i in range(0, len(columns)):\n cellDict[(0, i)].set_height(0.6)\n for j in range(1, len(rows) + 1):\n cellDict[(j, i)].set_height(0.4)\n\n cellDict[(1, -1)].set_height(0.4)\n cellDict[(2, -1)].set_height(0.4)\n\n table.auto_set_font_size(False)\n table.set_fontsize(10)\n\n for key, cell in table.get_celld().items():\n cell.set_linewidth(0.6)\n\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.spines['left'].set_visible(False)\n\n name = ['', '']\n ax.legend(name, handlelength=0.7, labelspacing=0.6,\n bbox_to_anchor=(-0.1, -0.23), loc='upper left', frameon=False)\n\n plt.show()\n\n\nif __name__ == '__main__':\n # draw_table(['A', 'B'], [['中国', '必胜'], ['你好', '谢谢']])\n # print(4800 / 1100 / 1000)\n data = {\n 'linux': [1.2, 2.2, 3.1, '中国', 2.0, 1.0, 2.1, 3.5, 4.0, 2.0, ],\n 'linuxmi': [5.2, 6.7, 7.9, 8.3, 1.2, 5.7, 6.1, 7.2, 8.3, '-', ],\n }\n\n df = pd.DataFrame(data)\n\n fig, ax = plt.subplots(figsize=(3, 3))\n\n ax.axis('off')\n ax.axis('tight')\n\n ax.table(cellText=df.values,\n colLabels=df.columns,\n bbox=[0, 0, 1, 1],\n )\n # plt.savefig('xx.png')\n plt.show()\n" ]
[ [ "matplotlib.pyplot.table", "matplotlib.pyplot.subplots", "pandas.DataFrame", "matplotlib.pyplot.bar", "matplotlib.pyplot.xticks", "matplotlib.pyplot.show" ] ]
[ { "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": [] } ]
DerryHub/the-TaobaoLive-Commodity-Identify-Competition
[ "7e5e5c4fbddd9949fe01810d58bd7994889c007c", "7e5e5c4fbddd9949fe01810d58bd7994889c007c" ]
[ "arcface/resnet_cbam.py", "validation_efficientdet.py" ]
[ "import torch\nimport torch.nn as nn\nimport math\nfrom arcface.utils import l2_norm, Flatten, SentVec_TFIDF\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\nclass ChannelAttention(nn.Module):\n def __init__(self, in_planes, ratio=16):\n super(ChannelAttention, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.max_pool = nn.AdaptiveMaxPool2d(1)\n\n self.fc1 = nn.Conv2d(in_planes, in_planes // 16, 1, bias=False)\n self.relu1 = nn.ReLU()\n self.fc2 = nn.Conv2d(in_planes // 16, in_planes, 1, bias=False)\n\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n avg_out = self.fc2(self.relu1(self.fc1(self.avg_pool(x))))\n max_out = self.fc2(self.relu1(self.fc1(self.max_pool(x))))\n out = avg_out + max_out\n return self.sigmoid(out)\n\nclass SpatialAttention(nn.Module):\n def __init__(self, kernel_size=7):\n super(SpatialAttention, self).__init__()\n\n assert kernel_size in (3, 7), 'kernel size must be 3 or 7'\n padding = 3 if kernel_size == 7 else 1\n\n self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n avg_out = torch.mean(x, dim=1, keepdim=True)\n max_out, _ = torch.max(x, dim=1, keepdim=True)\n x = torch.cat([avg_out, max_out], dim=1)\n x = self.conv1(x)\n return self.sigmoid(x)\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n\n self.ca = ChannelAttention(planes)\n self.sa = SpatialAttention()\n\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n out = self.ca(out) * out\n out = self.sa(out) * out\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n\n self.ca = ChannelAttention(planes * 4)\n self.sa = SpatialAttention()\n\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n out = self.ca(out) * out\n out = self.sa(out) * out\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\nMODEL = {\n 50:{\n 'layers': [3, 4, 6, 3]\n },\n 101:{\n 'layers': [3, 4, 23, 3]\n },\n 152:{\n 'layers': [3, 8, 36, 3]\n }\n}\n\nclass ResNetCBAM(nn.Module):\n\n def __init__(self, config):\n super(ResNetCBAM, self).__init__()\n embedding_size = config.embedding_size\n drop_ratio = config.drop_ratio\n model_dic = MODEL[config.num_layers_c]\n layers = model_dic['layers']\n # embedding_size = 2048\n # drop_ratio = 0.1\n # layers = [3, 4, 23, 3]\n\n # self.sentvec = SentVec_TFIDF(embedding_size=embedding_size, root_dir='data/')\n block = Bottleneck\n self.inplanes = 64\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=1)\n # self.avgpool = nn.AvgPool2d(4, stride=1)\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n # self.fc = nn.Linear(512* block.expansion, 1000)\n\n self.bn_last = nn.BatchNorm1d(embedding_size)\n self.bn_last.bias.requires_grad_(False)\n\n # self.output_layer = nn.Sequential(\n # nn.BatchNorm2d(512 * block.expansion),\n # nn.Dropout(drop_ratio),\n # Flatten(),\n # nn.Linear(512 * block.expansion, embedding_size),\n # nn.BatchNorm1d(embedding_size))\n\n # self.last_layer = nn.Sequential(\n # nn.Linear(2*embedding_size, embedding_size),\n # nn.BatchNorm1d(embedding_size)\n # )\n '''if not config.resume:\n self._initialize_weights() \n'''\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n \n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):\n import scipy.stats as stats\n X = stats.truncnorm(-2, 2, scale=0.01)\n values = torch.as_tensor(X.rvs(m.weight.numel()), dtype=m.weight.dtype)\n values = values.view(m.weight.size())\n with torch.no_grad():\n m.weight.copy_(values)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n # print(x.size())\n x = self.layer2(x)\n # print(x.size())\n x = self.layer3(x)\n # print(x.size())\n x = self.layer4(x)\n # print(x.size())\n\n x = self.avgpool(x)\n # x = self.output_layer(x)\n # sent = self.sentvec(text)\n # x = torch.cat((x, sent), dim=1)\n # x = self.last_layer(x)\n x = torch.flatten(x, 1)\n \n if self.training:\n return x, self.bn_last(x)\n else:\n return l2_norm(self.bn_last(x))\n\n\nif __name__ == \"__main__\":\n net = ResNetCBAM('aa')\n net.load_state_dict(torch.load('trained_models/resnet_cbam_101.pth'))\n # del net.output_layer\n # net.bn_last = nn.BatchNorm1d(2048)\n # l = [3, 4, 6, 3]\n # for i in range(3):\n # net.layer1[i].ca = ChannelAttention(64 * 4)\n # net.layer1[i].sa = SpatialAttention()\n # for i in range(4):\n # net.layer2[i].ca = ChannelAttention(64 * 8)\n # net.layer2[i].sa = SpatialAttention()\n # for i in range(6):\n # net.layer3[i].ca = ChannelAttention(64 * 16)\n # net.layer3[i].sa = SpatialAttention()\n # for i in range(3):\n # net.layer4[i].ca = ChannelAttention(64 * 32)\n # net.layer4[i].sa = SpatialAttention()\n \n # # net.sentvec = SentVec_TFIDF(embedding_size=512, root_dir='data/')\n # net.output_layer = nn.Sequential(\n # nn.BatchNorm2d(512* 4),\n # nn.Dropout(0.1),\n # Flatten(),\n # nn.Linear(512 * 4, 4096),\n # nn.BatchNorm1d(4096))\n \n # del net.fc\n torch.save(net.state_dict(), 'trained_models/resnet_cbam_101.pth')\n a = torch.randn(5,3,224,224)\n b = net(a)\n print(b[0].size())", "import os\nimport argparse\nimport torch\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\nfrom dataset import EfficientdetDataset\nfrom utils import Resizer, Normalizer, collater, iou, area\nfrom utils import colors\nimport cv2\nimport shutil\nfrom efficientdet.efficientdet import EfficientDet\nfrom config import get_args_efficientdet\nfrom tqdm import tqdm\nimport numpy as np\n\nwritePIC = False\ncalIOU = False\ncalPR = True\ncalAREA = None\n\nC = np.array([0, 1, 2, 3, 3, 2, 3, 2, 3, 3, 4, 0, 2, 2, 2, 2, 0, 1, 0, 2, 3, 3, 2])\n\ndef test(opt):\n opt.resume = True\n test_set = EfficientdetDataset(opt.data_path, mode='validation', transform=transforms.Compose([Normalizer(), Resizer()]), imgORvdo=opt.imgORvdo)\n opt.num_classes = test_set.num_classes\n opt.vocab_size = test_set.vocab_size\n opt.batch_size = 8\n test_params = {\"batch_size\": opt.batch_size,\n \"shuffle\": False,\n \"drop_last\": False,\n \"collate_fn\": collater,\n \"num_workers\": opt.workers}\n test_generator = DataLoader(test_set, **test_params)\n \n print(opt.network+'_'+opt.imgORvdo)\n model = EfficientDet(opt)\n model.load_state_dict(torch.load(os.path.join(opt.saved_path, opt.network+'_'+opt.imgORvdo+'.pth')))\n model.cuda()\n # model.set_is_training(False)\n model.eval()\n\n if writePIC:\n if os.path.isdir(opt.prediction_dir):\n shutil.rmtree(opt.prediction_dir)\n os.makedirs(opt.prediction_dir)\n \n progress_bar = tqdm(test_generator)\n progress_bar.set_description_str(' Evaluating')\n IoU_scores = []\n N_TP = 0\n N_P = 0\n N_GT = 0\n N_TP_iou = 0\n N_GT_ins = 0\n N_P_ins = 0\n N_TP_ins = 0\n for i, data in enumerate(progress_bar):\n scale = data['scale']\n with torch.no_grad():\n output_list = model([data['img'].cuda().float(), data['text'].cuda()])\n # output_list = model(data['img'].cuda().float())\n \n for j, output in enumerate(output_list):\n imgPath = test_set.getImagePath(i*opt.batch_size+j)\n scores, labels, instances, all_labels, boxes = output\n # scores, labels, all_labels, boxes = output\n # print(instances)\n annot = data['annot'][j]\n annot = annot[annot[:, 4]!=-1]\n # print(labels, torch.argsort(-all_labels, dim=1))\n top5_label = torch.argsort(-all_labels, dim=1)[:, :5]\n cat = torch.cat([scores.view(-1, 1), top5_label.float(), boxes, instances], dim=1).cpu()\n # cat = torch.cat([scores.view(-1, 1), top5_label.float(), boxes], dim=1).cpu()\n \n cat = cat[cat[:, 0]>=opt.cls_threshold]\n if calAREA is not None:\n areas = area(cat[:, 6:10])\n area_arg = np.argsort(-areas)\n cat = cat[area_arg[:calAREA]]\n\n # print(scores.size(), labels.size(), boxes.size(), annot.size())\n if calIOU:\n if boxes.shape[0] == 0:\n if annot.size(0) == 0:\n IoU_scores.append(1.0)\n else:\n IoU_scores.append(0.0)\n continue\n if annot.size(0) == 0:\n IoU_scores.append(0.0)\n else:\n classes = set(annot[:, 4].tolist())\n iou_score = []\n for c in classes:\n box = []\n for item in cat:\n if c in item[1:6]:\n box.append(item[6:10])\n if len(box) == 0:\n iou_score.append(0.0)\n continue\n box = torch.stack(box, dim=0)\n tgt = annot[annot[:, 4]==c][:, :4]\n iou_s = iou(box, tgt)\n iou_score.append(iou_s.cpu().numpy())\n classes_pre = cat[:, 1:6].tolist()\n for c in classes_pre:\n if len(set(c) & set(classes)) == 0:\n iou_score.append(0)\n IoU_scores.append(sum(iou_score)/len(iou_score))\n # print(IoU_scores)\n\n if calPR:\n N_P += cat.size(0)\n N_GT += annot.size(0)\n N_GT_ins += int((annot[:, 5] == 1).sum())\n # if len(cat) == 1:\n # N_P_ins += 1\n # N_TP_ins += 1\n # else:\n N_P_ins += int((cat[:, 10] == 1).sum())\n # print(cat[:, 10], annot[:, 5])\n # print(N_GT_ins)\n for pre in cat:\n for gt in annot:\n s = iou(pre[6:10].unsqueeze(0), gt[:4].unsqueeze(0))\n if s > 0.5:\n N_TP_iou += 1\n if C[int(gt[4])] in C[list(map(int, pre[1:3]))]:\n N_TP += 1\n # if len(cat) != 1:\n if gt[5] == pre[10] and gt[5] == 1:\n N_TP_ins += 1\n \n\n if writePIC:\n annot_labels = annot[:, 4].clone()\n annot_instance = annot[:, 5].clone()\n annot /= scale[j]\n boxes /= scale[j]\n output_image = cv2.imread(os.path.join(opt.data_path, imgPath))\n # print(annot, os.path.join(opt.data_path, imgPath))\n for box_id in range(boxes.shape[0]):\n pred_prob = float(scores[box_id])\n if pred_prob < opt.cls_threshold:\n break\n # pred_label = int(top5_label[box_id][0])\n pred_label = int(instances[box_id, 0])\n xmin, ymin, xmax, ymax = boxes[box_id, :]\n color = colors[pred_label]\n cv2.rectangle(output_image, (xmin, ymin), (xmax, ymax), color, 2)\n text_size = cv2.getTextSize('p: {}'.format(pred_label) + ' : %.2f' % pred_prob, cv2.FONT_HERSHEY_PLAIN, 3, 2)[0]\n\n cv2.rectangle(output_image, (xmin, ymin), (xmin + text_size[0] + 3, ymin + text_size[1] + 4), color, 1)\n cv2.putText(\n output_image, 'p: {}'.format(pred_label) + ' : %.2f' % pred_prob,\n (xmin, ymin + text_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 1,\n color, 2)\n for box_id in range(annot.size(0)):\n # true_label = int(annot_labels[box_id])\n true_label = annot_instance[box_id]\n xmin, ymin, xmax, ymax = annot[box_id, :4]\n cv2.rectangle(output_image, (xmin, ymin), (xmax, ymax), (255, 0, 0), 2)\n text_size = cv2.getTextSize('g: {}'.format(true_label), cv2.FONT_HERSHEY_PLAIN, 3, 2)[0]\n cv2.rectangle(output_image, (xmin, ymax), (xmin + text_size[0] + 3, ymax - text_size[1] + 4), (255, 0, 0), 1)\n cv2.putText(\n output_image, 'g: {}'.format(true_label),\n (xmin, ymax - text_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 1,\n (255, 0, 0), 2)\n cv2.imwrite(\"{}/{}_prediction.jpg\".format(opt.prediction_dir, imgPath.split('/')[-1][:-4]), output_image)\n \n if calIOU:\n print('IoU is '.format(sum(IoU_scores)/len(IoU_scores)))\n if calPR:\n print('*'*100)\n print('bbox 识别率:')\n print('N_P: {}\\tN_GT: {}\\tN_TP_iou: {}\\tN_TP: {}'.format(N_P, N_GT, N_TP_iou, N_TP))\n print('精确率: {}\\t召回率: {}\\t分类准确率: {}'.format(N_TP/N_P, N_TP/N_GT, N_TP/N_TP_iou))\n print('*'*100)\n print('instance 识别率:')\n print('N_P_ins: {}\\tN_GT_ins: {}\\tN_TP_ins: {}'.format(N_P_ins, N_GT_ins, N_TP_ins))\n print('精确率: {}\\t召回率: {}'.format(N_TP_ins/N_P_ins, N_TP_ins/N_GT_ins))\n print('*'*100)\n\nif __name__ == \"__main__\":\n opt = get_args_efficientdet()\n test(opt)\n # import json\n # with open('data/label.json', 'r') as f:\n # d = json.load(f)\n # print(d['index2label'])\n # C = [0, 1, 2, 3, 3, 2, 3, 2, 3, 3, 4, 0, 2, 2, 2, 2, 0, 1, 0, 2, 3, 3, 2]\n # print(len(C))\n" ]
[ [ "torch.mean", "torch.nn.AdaptiveMaxPool2d", "torch.nn.BatchNorm1d", "torch.nn.Sequential", "torch.max", "torch.cat", "torch.load", "torch.randn", "scipy.stats.truncnorm", "torch.nn.Conv2d", "torch.nn.init.constant_", "torch.nn.Sigmoid", "torch.flatten", "torch.nn.MaxPool2d", "torch.nn.AdaptiveAvgPool2d", "torch.no_grad", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ], [ "torch.utils.data.DataLoader", "torch.no_grad", "torch.stack", "numpy.argsort", "torch.argsort", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ajitrajasekharan/bert_mask
[ "33c7067134f2696b849fdb273443306026c5527d" ]
[ "examine_vectors.py" ]
[ "import torch\nfrom transformers import *\nimport pdb\nimport operator\nfrom collections import OrderedDict\nimport sys\n\n# OPTIONAL: if you want to have more information on what's happening, activate the logger as follows\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\n\nPATH='bert-base-cased'\n# Load pre-trained model tokenizer (vocabulary)\ntokenizer = BertTokenizer.from_pretrained(PATH,do_lower_case=False)\nmodel = BertForMaskedLM.from_pretrained(PATH)\nmodel.eval()\n\ndef get_sent():\n print(\"Enter sentence:\")\n sent = input()\n if (not sent.endswith(\".\")):\n print(\"Appending period to do dummy masking\")\n sent = sent + \" .\"\n return '[CLS] ' + sent + '[SEP]'\n\ndef print_tokens(tokenized_text):\n dstr = \"\"\n for i in range(len(tokenized_text)):\n dstr += \" \" + str(i) + \":\"+tokenized_text[i]\n print(dstr)\n print()\n\ndef get_pos():\n while True:\n masked_index = 0\n try:\n masked_index = int(input())\n return masked_index\n except:\n print(\"Enter valid number: (0 to quit)\")\n masked_index = int(input())\n if (masked_index == 0):\n print(\"Quitting\")\n sys.exit()\n return masked_index\n\n\nwhile (True):\n text = get_sent()\n\n tokenized_text = tokenizer.tokenize(text)\n print_tokens(tokenized_text)\n #pdb.set_trace()\n indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)\n\n # Create the segments tensors.\n segments_ids = [0] * len(tokenized_text)\n\n masked_index = len(tokenized_text) - 2\n tokenized_text[masked_index] = \"[MASK]\"\n indexed_tokens[masked_index] = 103\n results_dict = {}\n\n # Convert inputs to PyTorch tensors\n tokens_tensor = torch.tensor([indexed_tokens])\n segments_tensors = torch.tensor([segments_ids])\n\n with torch.no_grad():\n predictions = model(tokens_tensor, segments_tensors)\n while True:\n print_tokens(tokenized_text)\n print(\"Enter any term position neighbor:\")\n masked_index = get_pos()\n results_dict = {}\n for i in range(len(predictions[0][0,masked_index])):\n tok = tokenizer.convert_ids_to_tokens([i])[0]\n results_dict[tok] = float(predictions[0][0,masked_index][i].tolist())\n\n k = 0\n hist_d = {}\n sorted_d = OrderedDict(sorted(results_dict.items(), key=lambda kv: kv[1], reverse=True))\n first = True\n max_val = 0\n for i in sorted_d:\n if (first):\n max_val = sorted_d[i]\n first = False\n val = round(float(sorted_d[i])/max_val,1)\n if (val in hist_d):\n hist_d[val] += 1\n else:\n hist_d[val] = 1\n k += 1\n if (k <= 20):\n print(i,sorted_d[i])\n fp = open(\"top_k.txt\",\"w\")\n hist_d_sorted = OrderedDict(sorted(hist_d.items(), key=lambda kv: kv[0], reverse=False))\n for i in hist_d_sorted:\n fp.write(str(i) + \" \" + str(hist_d_sorted[i]) + \"\\n\")\n fp.close()\n" ]
[ [ "torch.no_grad", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
GodWriter/GAN-Pytorch
[ "42e0657ae4844c9644a2c382de6af977733d9074", "42e0657ae4844c9644a2c382de6af977733d9074" ]
[ "cgan/utils.py", "wgan-gp/train.py" ]
[ "import os\nimport imageio\nimport numpy as np\n\nfrom PIL import Image\nfrom torch.autograd import Variable\nfrom torchvision.utils import save_image\n\n\ndef create_gif(image_path):\n frames = []\n gif_name = os.path.join(\"images\", 'mnist1.gif')\n\n image_list = os.listdir(image_path)\n sorted(image_list)\n\n for image_name in image_list:\n frames.append(imageio.imread(os.path.join(image_path, image_name)))\n\n imageio.mimsave(gif_name, frames, 'GIF', duration=0.1)\n\n\ndef resize_img(path):\n names = os.listdir(path)\n for name in names:\n img_path = os.path.join(path, name)\n img = Image.open(img_path)\n img = img.resize((172, 172))\n img.save(img_path)\n\n\ndef sample_image(opt, n_row, batches_done, generator, FloatTensor, LongTensor):\n z = Variable(FloatTensor(np.random.normal(0, 1, (n_row ** 2, opt.latent_dim))))\n labels = np.array([num for _ in range(n_row) for num in range(n_row)])\n labels = Variable(LongTensor(labels))\n\n gen_imgs = generator(z, labels)\n save_image(gen_imgs.data, \"images/%d.png\" % batches_done, nrow=n_row, normalize=True)\n\n\n\n\nif __name__ == \"__main__\":\n image_path = \"images/example1\"\n resize_img(image_path)\n create_gif(image_path)\n", "import os\nimport numpy as np\n\nimport torch\nimport torch.autograd as autograd\n\nfrom torch.autograd import Variable\nfrom torchvision.utils import save_image\n\nfrom config import parse_args\nfrom dataloader import mnist_loader\nfrom model import Generator, Discriminator\n\n\ndef compute_gradient_penalty(discriminator, real_imgs, gen_imgs, Tensor):\n epsilon = Tensor(np.random.random((real_imgs.size(0), 1, 1, 1)))\n interpolates = (epsilon * real_imgs + ((1 - epsilon) * gen_imgs)).requires_grad_(True)\n fake = Variable(Tensor(real_imgs.shape[0], 1).fill_(1.0), requires_grad=False)\n\n gradients = autograd.grad(outputs=discriminator(interpolates),\n inputs=interpolates,\n grad_outputs=fake,\n create_graph=True,\n retain_graph=True,\n only_inputs=True)[0]\n gradients = gradients.view(gradients.size(0), -1)\n gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean()\n\n return gradient_penalty\n\n\ndef train():\n os.makedirs(\"images\", exist_ok=True)\n os.makedirs(\"checkpoints\", exist_ok=True)\n\n cuda = True if torch.cuda.is_available() else False\n Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor\n\n # get configs and dataloader\n opt = parse_args()\n data_loader = mnist_loader(opt)\n\n # Initialize generator and discriminator\n generator = Generator(opt)\n discriminator = Discriminator(opt)\n\n if cuda:\n generator.cuda()\n discriminator.cuda()\n\n # Optimizers\n optimizer_G = torch.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))\n optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))\n\n for epoch in range(opt.epochs):\n for i, (imgs, _) in enumerate(data_loader):\n\n # Configure input\n z = Variable(Tensor(np.random.normal(0, 1, (imgs.shape[0], opt.latent_dim))))\n gen_imgs = generator(z)\n real_imgs = Variable(imgs.type(Tensor))\n\n # ------------------\n # Train Discriminator\n # ------------------\n\n optimizer_D.zero_grad()\n gradient_penalty = compute_gradient_penalty(discriminator, real_imgs.data, gen_imgs.data, Tensor)\n d_loss = torch.mean(discriminator(gen_imgs)) - torch.mean(discriminator(real_imgs)) + opt.lambda_gp * gradient_penalty\n\n d_loss.backward()\n optimizer_D.step()\n\n # ------------------\n # Train Generator\n # ------------------\n\n if i % opt.n_critic == 0:\n optimizer_G.zero_grad()\n g_loss = -torch.mean(discriminator(generator(z)))\n\n g_loss.backward()\n optimizer_G.step()\n\n # ------------------\n # Log Information\n # ------------------\n\n print(\"[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]\" %\n (epoch, opt.epochs, i, len(data_loader), d_loss.item(), g_loss.item()))\n\n batches_done = epoch * len(data_loader) + i\n if batches_done % opt.sample_interval == 0:\n save_image(gen_imgs.data[:25], \"images/%d.png\" % batches_done, nrow=5, normalize=True)\n\n if batches_done % opt.checkpoint_interval == 0:\n torch.save(generator.state_dict(), \"checkpoints/generator_%d.pth\" % epoch)\n # torch.save(discriminator.state_dict(), \"checkpoints/discriminator_%d.pth\" % epoch)\n\n torch.save(generator.state_dict(), \"checkpoints/generator_done.pth\")\n print(\"Training Process has been Done!\")\n\n\nif __name__ == '__main__':\n train()\n\n\n" ]
[ [ "numpy.random.normal" ], [ "numpy.random.normal", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
isabella232/allsongsconsidered-poll
[ "f4b63effcf57c6b6680eac9f11a55cd0541e358c" ]
[ "scripts/pivot_cluster_day.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport argparse\nimport sys\nimport numpy as np\nimport pandas as pd\n\n\ndef run(args):\n data = pd.read_csv(sys.stdin)\n\n # Find maximum rank value and increase by one to use as a fill_value\n # on the pivot with cluster by day\n # notfound_value = grouped['rank'].max()+1\n\n # #create pivot table and fill non existing with high number i.e:200\n pivot = pd.pivot_table(data,\n values='rank',\n index='Cluster ID',\n columns=['day'],\n fill_value=args.notfound_value,\n aggfunc=np.sum)\n\n # Write output\n pivot.to_csv(sys.stdout)\n\n\nif __name__ == '__main__':\n # Parse command-line arguments.\n parser = argparse.ArgumentParser(\n description=\"Pivot table by cluster and day of the poll\")\n parser.add_argument('--notfound_value',\n type=int,\n help=\"value to assign to N/A values on pivot table\",\n required=True)\n args = parser.parse_args()\n run(args)\n" ]
[ [ "pandas.read_csv", "pandas.pivot_table" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
suhoy901/recommenders
[ "8ec9f1950d694a5aeaa3d463ac23cad661a30a11", "839e0444fcf9f1a085de88417c61f8f938b932c9", "839e0444fcf9f1a085de88417c61f8f938b932c9" ]
[ "reco_utils/recommender/geoimc/geoimc_utils.py", "reco_utils/recommender/rbm/rbm.py", "reco_utils/azureml/azureml_designer_modules/entries/precision_at_k_entry.py" ]
[ "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport numpy as np\nfrom sklearn.decomposition import PCA\n\nfrom reco_utils.dataset.download_utils import maybe_download\nfrom IPython import embed\n\ndef length_normalize(matrix):\n \"\"\"Length normalize the matrix\n\n Args:\n matrix (np.ndarray): Input matrix that needs to be normalized\n\n Returns:\n Normalized matrix\n \"\"\"\n norms = np.sqrt(np.sum(matrix**2, axis=1))\n norms[norms == 0] = 1\n return matrix / norms[:, np.newaxis]\n\n\ndef mean_center(matrix):\n \"\"\"Performs mean centering across axis 0\n\n Args:\n matrix (np.ndarray): Input matrix that needs to be mean centered\n \"\"\"\n avg = np.mean(matrix, axis=0)\n matrix -= avg\n\n\ndef reduce_dims(matrix, target_dim):\n \"\"\"Reduce dimensionality of the data using PCA.\n\n Args:\n matrix (np.ndarray): Matrix of the form (n_sampes, n_features)\n target_dim (uint): Dimension to which n_features should be reduced to.\n\n \"\"\"\n model = PCA(n_components=target_dim)\n model.fit(matrix)\n return model.transform(matrix)\n", "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nimport numpy as np\nimport pandas as pd\nimport math\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport logging\nimport time as tm\n\n\nlog = logging.getLogger(__name__)\n\n\nclass RBM:\n \"\"\"Restricted Boltzmann Machine\"\"\"\n\n def __init__(\n self,\n hidden_units=500,\n keep_prob=0.7,\n init_stdv=0.1,\n learning_rate=0.004,\n minibatch_size=100,\n training_epoch=20,\n display_epoch=10,\n sampling_protocol=[50, 70, 80, 90, 100],\n debug=False,\n with_metrics=False,\n seed=42,\n ):\n \"\"\"Implementation of a multinomial Restricted Boltzmann Machine for collaborative filtering\n in numpy/pandas/tensorflow\n\n Based on the article by Ruslan Salakhutdinov, Andriy Mnih and Geoffrey Hinton\n https://www.cs.toronto.edu/~rsalakhu/papers/rbmcf.pdf\n\n In this implementation we use multinomial units instead of the one-hot-encoded used in\n the paper.This means that the weights are rank 2 (matrices) instead of rank 3 tensors.\n\n Basic mechanics:\n\n 1) A computational graph is created when the RBM class is instantiated;\n For an item based recommender this consists of:\n visible units: The number Nv of visible units equals the number of items\n hidden units : hyperparameter to fix during training\n\n 2) Gibbs Sampling:\n\n 2.1) for each training epoch, the visible units are first clamped on the data\n\n 2.2) The activation probability of the hidden units, given a linear combination of\n the visibles, is evaluated P(h=1|phi_v). The latter is then used to sample the\n value of the hidden units.\n\n 2.3) The probability P(v=l|phi_h) is evaluated, where l=1,..,r are the rates (e.g.\n r=5 for the movielens dataset). In general, this is a multinomial distribution,\n from which we sample the value of v.\n\n 2.4) This step is repeated k times, where k increases as optimization converges. It is\n essential to fix to zero the original unrated items during the all learning process.\n\n 3) Optimization:\n The free energy of the visible units given the hidden is evaluated at the beginning (F_0)\n and after k steps of Bernoulli sampling (F_k). The weights and biases are updated by\n minimizing the differene F_0 - F_k.\n\n 4) Inference:\n Once the joint probability distribution P(v,h) is learned, this is used to generate ratings\n for unrated items for all users\n \"\"\"\n\n # RBM parameters\n self.Nhidden = hidden_units # number of hidden units\n self.keep = keep_prob # keep probability for dropout regularization\n\n # standard deviation used to initialize the weights matrices\n self.stdv = init_stdv\n\n # learning rate used in the update method of the optimizer\n self.learning_rate = learning_rate\n\n # size of the minibatch used in the random minibatches training; setting to 1 correspoNds to\n # stochastic gradient descent, and it is considerably slower.Good performance is achieved\n # for a size of ~100.\n self.minibatch = minibatch_size\n self.epochs = training_epoch + 1 # number of epochs used to train the model\n\n # number of epochs to show the mse error during training\n self.display = display_epoch\n\n # protocol to increase Gibbs sampling's step. Array containing the\n # percentage of the total training epoch when the step increases by 1\n self.sampling_protocol = sampling_protocol\n\n # if true, functions print their control paramters and/or outputs\n self.debug = debug\n\n # if true, compute msre and accuracy during training\n self.with_metrics = with_metrics\n\n # Initialize the start time\n self.start_time = None\n\n # Seed\n self.seed = seed\n np.random.seed(self.seed)\n tf.set_random_seed(self.seed)\n\n log.info(\"TensorFlow version: {}\".format(tf.__version__))\n\n def time(self):\n \"\"\"Time a particular section of the code - call this once to set the state somewhere\n in the code, then call it again to return the elapsed time since last call.\n Call again to set the time and so on...\n\n Returns:\n float: if timer started time in seconds since the last time time function was called\n \"\"\"\n\n if self.start_time is None:\n self.start_time = tm.time()\n return False\n else:\n answer = tm.time() - self.start_time\n # reset state\n self.start_time = None\n return answer\n\n def binomial_sampling(self, pr):\n \"\"\"Binomial sampling of hidden units activations using a rejection method.\n\n Basic mechanics:\n\n 1) Extract a random number from a uniform distribution (g) and compare it with\n the unit's probability (pr)\n\n 2) Choose 0 if pr<g, 1 otherwise. It is convenient to implement this condtion using\n the relu function.\n\n Args:\n pr (tf.Tensor, float32): input conditional probability\n g (np.array, float32): uniform probability used for comparison\n\n Returns:\n tf.Tensor: Float32 tensor of sampled units. The value is 1 if pr>g and 0 otherwise.\n \"\"\"\n\n # sample from a Bernoulli distribution with same dimensions as input distribution\n g = tf.convert_to_tensor(np.random.uniform(size=pr.shape[1]), dtype=tf.float32)\n\n # sample the value of the hidden units\n h_sampled = tf.nn.relu(tf.sign(pr - g))\n\n return h_sampled\n\n def multinomial_sampling(self, pr):\n \"\"\"Multinomial Sampling of ratings\n\n Basic mechanics:\n For r classes, we sample r binomial distributions using the rejection method. This is possible\n since each class is statistically independent from the other. Note that this is the same method\n used in numpy's random.multinomial() function.\n\n 1) extract a size r array of random numbers from a uniform distribution (g). As pr is normalized,\n we need to normalize g as well.\n\n 2) For each user and item, compare pr with the reference distribution. Note that the latter needs\n to be the same for ALL the user/item pairs in the dataset, as by assumptions they are sampled\n from a common distribution.\n\n Args:\n pr (tf.Tensor, float32): a distributions of shape (m, n, r), where m is the number of examples, n the number\n of features and r the number of classes. pr needs to be normalized, i.e. sum_k p(k) = 1 for all m, at fixed n.\n f (tf.Tensor, float32): normalized, uniform probability used for comparison.\n\n Returns:\n tf.Tensor: An (m,n) float32 tensor of sampled rankings from 1 to r.\n \"\"\"\n g = np.random.uniform(size=pr.shape[2]) # sample from a uniform distribution\n f = tf.convert_to_tensor(\n g / g.sum(), dtype=tf.float32\n ) # normalize and convert to tensor\n\n samp = tf.nn.relu(tf.sign(pr - f)) # apply rejection method\n v_samp = tf.cast(\n tf.argmax(samp, axis=2) + 1, \"float32\"\n ) # select sampled element\n\n return v_samp\n\n def multinomial_distribution(self, phi):\n \"\"\"Probability that unit v has value l given phi: P(v=l|phi)\n\n Args:\n phi (tf.Tensor): linear combination of values of the previous layer\n r (float): rating scale, corresponding to the number of classes\n\n Returns:\n tf.Tensor: a tensor of shape (r, m, Nv). This needs to be reshaped as (m, Nv, r) in the last step\n to allow for faster sampling when used in the multinomial function.\n\n \"\"\"\n\n numerator = [\n tf.exp(tf.multiply(tf.constant(k, dtype=\"float32\"), phi))\n for k in range(1, self.ratings + 1)\n ]\n\n denominator = tf.reduce_sum(numerator, axis=0)\n\n prob = tf.div(numerator, denominator)\n\n return tf.transpose(prob, perm=[1, 2, 0])\n\n def free_energy(self, x):\n \"\"\"Free energy of the visible units given the hidden units. Since the sum is over the hidden units'\n states, the functional form of the visible units Free energy is the same as the one for the binary model.\n\n Args:\n x (tf.Tensor): This can be either the sampled value of the visible units (v_k) or the input data\n\n Returns:\n tf.Tensor: Free energy of the model.\n \"\"\"\n\n bias = -tf.reduce_sum(tf.matmul(x, tf.transpose(self.bv)))\n\n phi_x = tf.matmul(x, self.w) + self.bh\n f = -tf.reduce_sum(tf.nn.softplus(phi_x))\n\n F = bias + f # free energy density per training example\n\n return F\n\n def placeholder(self):\n \"\"\"Initialize the placeholders for the visible units\"\"\"\n self.vu = tf.placeholder(shape=[None, self.Nvisible], dtype=\"float32\")\n\n def init_parameters(self):\n \"\"\"Initialize the parameters of the model.\n\n This is a single layer model with two biases. So we have a rectangular matrix w_{ij} and\n two bias vectors to initialize.\n\n Args:\n Nv (int): number of visible units (input layer)\n Nh (int): number of hidden units (latent variables of the model)\n\n Returns:\n tf.Tensor, tf.Tensor, tf.Tensor: It returns 3 tensors. `w` of size (Nv, Nh): correlation matrix initialized \n by sampling from a normal distribution with zero mean and given variance init_stdv. `bv` of size \n (1, Nvisible): visible units' bias, initialized to zero. `bh` of size (1, Nhidden)L hidden units' bias, \n initiliazed to zero.\n \"\"\"\n with tf.variable_scope(\"Network_parameters\"):\n\n self.w = tf.get_variable(\n \"weight\",\n [self.Nvisible, self.Nhidden],\n initializer=tf.random_normal_initializer(\n stddev=self.stdv, seed=self.seed\n ),\n dtype=\"float32\",\n )\n\n self.bv = tf.get_variable(\n \"v_bias\",\n [1, self.Nvisible],\n initializer=tf.zeros_initializer(),\n dtype=\"float32\",\n )\n\n self.bh = tf.get_variable(\n \"h_bias\",\n [1, self.Nhidden],\n initializer=tf.zeros_initializer(),\n dtype=\"float32\",\n )\n\n def sample_hidden_units(self, vv):\n \"\"\"Sampling: In RBM we use Contrastive divergence to sample the parameter space. In order to do that we need\n to initialize the two conditional probabilities:\n\n P(h|phi_v) --> returns the probability that the i-th hidden unit is active\n\n P(v|phi_h) --> returns the probability that the i-th visible unit is active\n\n Sample hidden units given the visibles. This can be thought of as a Forward pass step in a FFN\n\n Args:\n vv (tf.Tensor, float32): visible units\n\n Returns:\n tf.Tensor, tf.Tensor: Two tensors. `phv` is the activation probability of the hidden unit. `h_` is the\n sampled value of the hidden unit from a Bernoulli distributions having success probability `phv`.\n \"\"\"\n\n with tf.name_scope(\"sample_hidden_units\"):\n\n phi_v = tf.matmul(vv, self.w) + self.bh # create a linear combination\n phv = tf.nn.sigmoid(phi_v) # conditional probability of h given v\n phv_reg = tf.nn.dropout(phv, self.keep)\n\n # Sampling\n h_ = self.binomial_sampling(\n phv_reg\n ) # obtain the value of the hidden units via Bernoulli sampling\n\n return phv, h_\n\n def sample_visible_units(self, h):\n \"\"\"Sample the visible units given the hiddens. This can be thought of as a Backward pass in a FFN\n (negative phase). Each visible unit can take values in [1,rating], while the zero is reserved\n for missing data; as such the value of the hidden unit is sampled from a multinomial distribution.\n\n Basic mechanics:\n\n 1) For every training example we first sample Nv Multinomial distributions. The result is of the\n form [0,1,0,0,0,...,0] where the index of the 1 element corresponds to the rth rating. The index\n is extracted using the argmax function and we need to add 1 at the end since array indeces starts\n from 0.\n\n 2) Selects only those units that have been sampled. During the training phase it is important to not\n use the reconstructed inputs, so we beed to enforce a zero value in the reconstructed ratings in\n the same position as the original input.\n\n Args:\n h (tf.Tensor, float32): visible units.\n\n Returns:\n tf.Tensor, tf.Tensor: Two tensors. `pvh` is the activation probability of the visible unit given the hidden.\n `v_` is the sampled value of the visible unit from a Multinomial distributions having success probability \n `pvh`.\n \"\"\"\n\n with tf.name_scope(\"sample_visible_units\"):\n\n phi_h = tf.matmul(h, tf.transpose(self.w)) + self.bv # linear combination\n pvh = self.multinomial_distribution(\n phi_h\n ) # conditional probability of v given h\n\n # Sampling (modify here )\n v_tmp = self.multinomial_sampling(\n pvh\n ) # sample the value of the visible units\n\n mask = tf.equal(self.v, 0) # selects the inactive units in the input vector\n\n v_ = tf.where(\n mask, x=self.v, y=v_tmp\n ) # enforce inactive units in the reconstructed vector\n\n return pvh, v_\n\n def gibbs_sampling(self):\n \"\"\"Gibbs sampling: Determines an estimate of the model configuration via sampling. In the binary\n RBM we need to impose that unseen movies stay as such, i.e. the sampling phase should not modify\n the elements where v=0.\n\n Args:\n k (scalar, integer): iterator. Number of sampling steps.\n v (tf.Tensor, float32): visible units.\n\n Returns:\n tf.Tensor, tf.Tensor: Two tensors of float32. `h_k` is the sampled value of the hidden unit at step k. `v_k`\n is the sampled value of the visible unit at step k.\n \"\"\"\n\n with tf.name_scope(\"gibbs_sampling\"):\n\n self.v_k = (\n self.v\n ) # initialize the value of the visible units at step k=0 on the data\n\n if self.debug:\n print(\"CD step\", self.k)\n\n for i in range(self.k): # k_sampling\n _, h_k = self.sample_hidden_units(self.v_k)\n _, self.v_k = self.sample_visible_units(h_k)\n\n def losses(self, vv):\n \"\"\"Loss functions.\n\n Args:\n v (tf.Tensor, float32): empirical input\n v_k (tf.Tensor, float32): sampled visible units at step k\n\n Returns:\n obj: objective function of Contrastive divergence, that is the difference\n between the free energy clamped on the data (v) and the model Free energy (v_k).\n \"\"\"\n\n with tf.variable_scope(\"losses\"):\n obj = self.free_energy(vv) - self.free_energy(self.v_k)\n\n return obj\n\n def gibbs_protocol(self, i):\n \"\"\"Gibbs protocol.\n\n Basic mechanics:\n\n If the current epoch i is in the interval specified in the training protocol,\n the number of steps in Gibbs sampling (k) is incremented by one and gibbs_sampling is updated\n accordingly.\n\n Args:\n i (int): current epoch in the loop\n \"\"\"\n\n with tf.name_scope(\"gibbs_protocol\"):\n\n epoch_percentage = (\n i / self.epochs\n ) * 100 # current percentage of the total #epochs\n\n if epoch_percentage != 0:\n if (\n epoch_percentage >= self.sampling_protocol[self.l]\n and epoch_percentage <= self.sampling_protocol[self.l + 1]\n ):\n self.k += 1\n self.l += 1\n self.gibbs_sampling()\n\n if self.debug:\n log.info(\"percentage of epochs covered so far %f2\" % (epoch_percentage))\n\n def accuracy(self, vp):\n \"\"\"Train/Test Mean average precision\n\n Evaluates MAP over the train/test set in online mode. Note that this needs to be evaluated on\n the rated items only.\n\n :math:`acc = 1/m \\sum_{mu=1}^{m} \\sum{i=1}^Nv 1/s(i) I(v-vp = 0)_{mu,i}`\n\n where `m = Nusers`, `Nv = number of items = number of visible units` and `s(i)` is the number of non-zero elements \n per row.\n\n Args:\n vp (tf.Tensor, float32): inferred output (Network prediction)\n\n Returns:\n tf.Tensor: accuracy.\n \n \"\"\"\n\n with tf.name_scope(\"accuracy\"):\n\n # 1) define and apply the mask\n mask = tf.not_equal(self.v, 0)\n n_values = tf.reduce_sum(tf.cast(mask, \"float32\"), axis=1)\n\n # 2) Take the difference between the input data and the inferred ones. This value is zero whenever\n # the two values coincides\n vd = tf.where(\n mask, x=tf.abs(tf.subtract(self.v, vp)), y=tf.ones_like(self.v)\n )\n\n # correct values: find the location where v = vp\n corr = tf.cast(tf.equal(vd, 0), \"float32\")\n\n # 3) evaluate the accuracy\n ac_score = tf.reduce_mean(tf.div(tf.reduce_sum(corr, axis=1), n_values))\n\n return ac_score\n\n def rmse(self, vp):\n \"\"\"Root Mean Square Error\n\n Note that this needs to be evaluated on the rated items only\n\n Args:\n vp (tf.Tensor, float32): inferred output (Network prediction)\n\n Returns:\n tf.Tensor: root mean square error.\n\n \"\"\"\n\n with tf.name_scope(\"re\"):\n\n mask = tf.not_equal(self.v, 0) # selects only the rated items\n n_values = tf.reduce_sum(\n tf.cast(mask, \"float32\"), axis=1\n ) # number of rated items\n\n # evaluate the square difference between the inferred and the input data on the rated items\n e = tf.where(\n mask, x=tf.squared_difference(self.v, vp), y=tf.zeros_like(self.v)\n )\n\n # evaluate the msre\n err = tf.sqrt(\n tf.reduce_mean(tf.div(tf.reduce_sum(e, axis=1), n_values)) / 2\n )\n\n return err\n\n def data_pipeline(self):\n \"\"\"Define the data pipeline\"\"\"\n\n # placeholder for the batch_size\n self.batch_size = tf.placeholder(tf.int64)\n\n # Create the data pipeline for faster training\n self.dataset = tf.data.Dataset.from_tensor_slices(self.vu)\n\n self.dataset = self.dataset.shuffle(\n buffer_size=50, reshuffle_each_iteration=True, seed=self.seed\n ) # randomize the batch\n\n self.dataset = self.dataset.batch(batch_size=self.batch_size).repeat()\n\n # define iterator\n self.iter = self.dataset.make_initializable_iterator()\n self.v = self.iter.get_next()\n\n def init_metrics(self):\n \"\"\"Initialize metrics\"\"\"\n\n if self.with_metrics: # if true (default) returns evaluation metrics\n self.Rmse = self.rmse(self.v_k)\n self.Clacc = self.accuracy(self.v_k)\n\n def train_test_precision(self, xtst):\n \"\"\"Evaluates precision on the train and test set\n\n Args:\n xtst (np.array, integer32): the user/affinity matrix for the test set\n\n Returns:\n float, float: precision on the train and test sets.\n \"\"\"\n\n if self.with_metrics:\n\n precision_train = self.sess.run(self.Clacc)\n\n self.sess.run(\n self.iter.initializer,\n feed_dict={self.vu: xtst, self.batch_size: xtst.shape[0]},\n )\n\n precision_test = self.sess.run(self.Clacc)\n\n else:\n precision_train = None\n precision_test = None\n\n return precision_train, precision_test\n\n def display_metrics(self, Rmse_train, precision_train, precision_test):\n \"\"\"Display training/test metrics and plots the rmse error as a function\n of the training epochs\n\n Args:\n Rmse_train (list, float32): per epoch rmse on the train set\n precision_train (float): precision on the train set\n precision_test (float): precision on the test set\n \"\"\"\n\n if self.with_metrics:\n\n # Display training error as a function of epochs\n plt.plot(Rmse_train, label=\"train\")\n plt.ylabel(\"rmse\", size=\"x-large\")\n plt.xlabel(\"epochs\", size=\"x-large\")\n plt.legend(ncol=1)\n\n # Final precision scores\n log.info(\"Train set accuracy %f2\" % precision_train)\n log.info(\"Test set accuracy %f2\" % precision_test)\n\n def generate_graph(self):\n \"\"\"Call the different RBM modules to generate the computational graph\"\"\"\n\n log.info(\"Creating the computational graph\")\n\n self.placeholder() # create the visible units placeholder\n self.data_pipeline() # data_pipeline\n self.init_parameters() # initialize Network parameters\n\n # --------------Initialize protocol for Gibbs sampling------------------\n log.info(\"Initialize Gibbs protocol\")\n self.k = 1 # initialize the G_sampling step\n self.l = 0 # initialize epoch_sample index\n self.gibbs_sampling() # returns the sampled value of the visible units\n\n # ---Instantiate loss function and optimizer----------------------------\n obj = self.losses(self.v) # objective function\n\n rate = (\n self.learning_rate / self.minibatch\n ) # learning rate rescaled by the batch size\n\n self.opt = tf.contrib.optimizer_v2.AdamOptimizer(learning_rate=rate).minimize(\n loss=obj\n ) # Instantiate the optimizer\n\n def init_gpu(self):\n \"\"\"Config GPU memory\"\"\"\n\n self.config_gpu = tf.ConfigProto(\n log_device_placement=True, allow_soft_placement=True\n )\n self.config_gpu.gpu_options.allow_growth = True # dynamic memory allocation\n\n def init_training_session(self, xtr):\n \"\"\"Initialize the TF session on training data\n\n Args:\n xtr (np.array, int32): the user/affinity matrix for the train set\n \"\"\"\n\n init_graph = tf.global_variables_initializer()\n\n # Start TF training session on default graph\n self.sess = tf.Session(config=self.config_gpu)\n self.sess.run(init_graph)\n\n self.sess.run(\n self.iter.initializer,\n feed_dict={self.vu: xtr, self.batch_size: self.minibatch},\n )\n\n def batch_training(self, num_minibatches):\n \"\"\"Perform training over input minibatches. If `self.with_metrics` is False,\n no online metrics are evaluated.\n\n Args:\n num_minibatches (scalar, int32): number of training minibatches\n\n Returns:\n float: training error per single epoch. If `self.with_metrics` is False, this is zero.\n \"\"\"\n\n epoch_tr_err = 0 # initialize the training error for each epoch to zero\n\n if self.with_metrics:\n\n for l in range(num_minibatches): # minibatch loop\n _, batch_err = self.sess.run([self.opt, self.Rmse])\n # average msr error per minibatch\n epoch_tr_err += batch_err / num_minibatches\n\n else:\n for l in range(num_minibatches): # minibatch loop\n _ = self.sess.run(self.opt)\n\n return epoch_tr_err\n\n def fit(self, xtr, xtst):\n \"\"\"Fit method\n\n Training in generative models takes place in two steps:\n\n 1) Gibbs sampling\n 2) Gradient evaluation and parameters update\n\n This estimate is later used in the weight update step by minimizing the distance between the\n model and the empirical free energy. Note that while the unit's configuration space is sampled,\n the weights are determined via maximum likelihood (saddle point).\n\n Main component of the algo; once instantiated, it generates the computational graph and performs\n model training\n\n Args:\n xtr (np.array, integers): the user/affinity matrix for the train set\n xtst (np.array, integers): the user/affinity matrix for the test set\n\n Returns:\n float: elapsed time during training\n \"\"\"\n\n # keep the position of the items in the train set so that they can be optionally exluded from recommendation\n self.seen_mask = np.not_equal(xtr, 0)\n self.time()\n self.ratings = xtr.max() # obtain the rating scale, e.g. 1 to 5\n\n m, self.Nvisible = xtr.shape # m= # users, Nvisible= # items\n num_minibatches = int(m / self.minibatch) # number of minibatches\n\n tf.reset_default_graph()\n\n # ----------------------Initializers-------------------------------------\n self.generate_graph()\n self.init_metrics()\n self.init_gpu()\n self.init_training_session(xtr)\n\n Rmse_train = [] # List to collect the metrics across epochs\n\n # start loop over training epochs\n for i in range(self.epochs):\n\n self.gibbs_protocol(i) # Gibbs sampling update\n epoch_tr_err = self.batch_training(num_minibatches) # model train\n\n if self.with_metrics == True and i % self.display == 0:\n log.info(\"training epoch %i rmse %f\" % (i, epoch_tr_err))\n\n Rmse_train.append(epoch_tr_err) # mse training error per training epoch\n\n # optionally evaluate precision metrics\n precision_train, precision_test = self.train_test_precision(xtst)\n elapsed = self.time()\n\n log.info(\"done training, Training time %f2\" % elapsed)\n\n self.display_metrics(Rmse_train, precision_train, precision_test)\n\n return elapsed\n\n def eval_out(self):\n \"\"\"Implement multinomial sampling from a trained model\"\"\"\n\n # Sampling\n _, h = self.sample_hidden_units(self.vu) # sample h\n\n # sample v\n phi_h = (\n tf.transpose(tf.matmul(self.w, tf.transpose(h))) + self.bv\n ) # linear combination\n pvh = self.multinomial_distribution(\n phi_h\n ) # conditional probability of v given h\n\n v = self.multinomial_sampling(pvh) # sample the value of the visible units\n\n return v, pvh\n\n def recommend_k_items(self, x, top_k=10, remove_seen=True):\n \"\"\"Returns the top-k items ordered by a relevancy score.\n\n Basic mechanics:\n\n The method samples new ratings from the learned joint distribution, together with their\n probabilities. The input x must have the same number of columns as the one used for training\n the model (i.e. the same number of items) but it can have an arbitrary number of rows (users).\n\n A recommendation score is evaluated by taking the element-wise product between the ratings and\n the associated probabilities. For example, we could have the following situation:\n\n .. code-block:: python\n\n rating probability score\n item1 5 0.5 2.5\n item2 4 0.8 3.2\n\n then item2 will be recommended.\n\n Args:\n x (np.array, int32): input user/affinity matrix. Note that this can be a single vector, i.e. the ratings\n of a single user.\n top_k (scalar, int32): the number of items to recommend.\n\n Returns:\n np.array, float: A sparse matrix containing the top_k elements ordered by their score and the time taken \n to recommend k items.\n \"\"\"\n\n self.time()\n # evaluate the ratings and the associated probabilities\n v_, pvh_ = self.eval_out()\n\n # evaluate v_ and pvh_ on the input data\n vp, pvh = self.sess.run([v_, pvh_], feed_dict={self.vu: x})\n # returns only the probabilities for the predicted ratings in vp\n pv = np.max(pvh, axis=2)\n\n # evaluate the score\n score = np.multiply(vp, pv)\n # ----------------------Return the results as a P dataframe------------------------------------\n\n log.info(\"Extracting top %i elements\" % top_k)\n\n if remove_seen:\n # if true, it removes items from the train set by setting them to zero\n vp[self.seen_mask] = 0\n pv[self.seen_mask] = 0\n score[self.seen_mask] = 0\n\n top_items = np.argpartition(-score, range(top_k), axis=1)[\n :, :top_k\n ] # get the top k items\n\n score_c = score.copy() # get a copy of the score matrix\n\n score_c[\n np.arange(score_c.shape[0])[:, None], top_items\n ] = 0 # set to zero the top_k elements\n\n top_scores = score - score_c # set to zeros all elements other then the top_k\n elapsed = self.time()\n\n log.info(\"Done recommending items, time %f2\" % elapsed)\n return top_scores, elapsed\n\n def predict(self, x, maps):\n \"\"\"Returns the inferred ratings. This method is similar to recommend_k_items() with the\n exceptions that it returns all the inferred ratings\n\n Basic mechanics:\n\n The method samples new ratings from the learned joint distribution, together with\n their probabilities. The input x must have the same number of columns as the one used\n for training the model, i.e. the same number of items, but it can have an arbitrary number\n of rows (users).\n\n Args:\n x (np.array, int32): input user/affinity matrix. Note that this can be a single vector, i.e.\n the ratings of a single user.\n\n Returns:\n np.array, float: A matrix with the inferred ratings and the elapsed time for predediction.\n \"\"\"\n\n self.time()\n\n v_, _ = self.eval_out() # evaluate the ratings and the associated probabilities\n vp = self.sess.run(v_, feed_dict={self.vu: x})\n elapsed = self.time()\n\n log.info(\"Done inference, time %f2\" % elapsed)\n\n return vp, elapsed\n", "import argparse\nimport pandas as pd\n\nfrom azureml.core import Run\nfrom azureml.studio.core.logger import module_logger as logger\nfrom azureml.studio.core.data_frame_schema import DataFrameSchema\nfrom azureml.studio.core.io.data_frame_directory import (\n load_data_frame_from_directory,\n save_data_frame_to_directory,\n)\nfrom reco_utils.evaluation.python_evaluation import precision_at_k\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--rating-true\", help=\"True DataFrame.\")\n parser.add_argument(\"--rating-pred\", help=\"Predicted DataFrame.\")\n parser.add_argument(\n \"--col-user\", type=str, help=\"A string parameter with column name for user.\"\n )\n parser.add_argument(\n \"--col-item\", type=str, help=\"A string parameter with column name for item.\"\n )\n parser.add_argument(\n \"--col-rating\", type=str, help=\"A string parameter with column name for rating.\"\n )\n parser.add_argument(\n \"--col-prediction\",\n type=str,\n help=\"A string parameter with column name for prediction.\",\n )\n parser.add_argument(\n \"--relevancy-method\",\n type=str,\n help=\"method for determining relevancy ['top_k', 'by_threshold'].\",\n )\n parser.add_argument(\"--k\", type=int, help=\"number of top k items per user.\")\n parser.add_argument(\n \"--threshold\", type=float, help=\"threshold of top items per user.\"\n )\n parser.add_argument(\"--score-result\", help=\"Result of the computation.\")\n\n args, _ = parser.parse_known_args()\n\n rating_true = load_data_frame_from_directory(args.rating_true).data\n rating_pred = load_data_frame_from_directory(args.rating_pred).data\n\n col_user = args.col_user\n col_item = args.col_item\n col_rating = args.col_rating\n col_prediction = args.col_prediction\n relevancy_method = args.relevancy_method\n k = args.k\n threshold = args.threshold\n\n logger.debug(f\"Received parameters:\")\n logger.debug(f\"User: {col_user}\")\n logger.debug(f\"Item: {col_item}\")\n logger.debug(f\"Rating: {col_rating}\")\n logger.debug(f\"Prediction: {col_prediction}\")\n logger.debug(f\"Relevancy: {relevancy_method}\")\n logger.debug(f\"K: {k}\")\n logger.debug(f\"Threshold: {threshold}\")\n\n logger.debug(f\"Rating True path: {args.rating_true}\")\n logger.debug(f\"Shape of loaded DataFrame: {rating_true.shape}\")\n logger.debug(f\"Rating Pred path: {args.rating_pred}\")\n logger.debug(f\"Shape of loaded DataFrame: {rating_pred.shape}\")\n\n eval_precision = precision_at_k(\n rating_true,\n rating_pred,\n col_user=col_user,\n col_item=col_item,\n col_rating=col_rating,\n col_prediction=col_prediction,\n relevancy_method=relevancy_method,\n k=k,\n threshold=threshold,\n )\n\n logger.debug(f\"Score: {eval_precision}\")\n\n # Log to AzureML dashboard\n run = Run.get_context()\n run.parent.log(\"Precision at {}\".format(k), eval_precision)\n\n score_result = pd.DataFrame({\"precision_at_k\": [eval_precision]})\n save_data_frame_to_directory(\n args.score_result,\n score_result,\n schema=DataFrameSchema.data_frame_to_dict(score_result),\n )\n" ]
[ [ "numpy.sum", "numpy.mean", "sklearn.decomposition.PCA" ], [ "matplotlib.pyplot.legend", "tensorflow.sign", "tensorflow.reduce_sum", "tensorflow.equal", "tensorflow.cast", "matplotlib.pyplot.plot", "numpy.max", "tensorflow.where", "numpy.arange", "tensorflow.subtract", "tensorflow.div", "tensorflow.ConfigProto", "tensorflow.reset_default_graph", "tensorflow.name_scope", "tensorflow.Session", "tensorflow.argmax", "tensorflow.random_normal_initializer", "tensorflow.nn.dropout", "tensorflow.matmul", "tensorflow.nn.sigmoid", "numpy.multiply", "tensorflow.zeros_initializer", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.zeros_like", "matplotlib.pyplot.xlabel", "tensorflow.set_random_seed", "numpy.not_equal", "matplotlib.pyplot.ylabel", "tensorflow.not_equal", "tensorflow.transpose", "tensorflow.constant", "numpy.random.seed", "tensorflow.data.Dataset.from_tensor_slices", "tensorflow.ones_like", "tensorflow.contrib.optimizer_v2.AdamOptimizer", "tensorflow.variable_scope", "numpy.random.uniform", "tensorflow.squared_difference", "tensorflow.nn.softplus" ], [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "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": [] } ]
ANI717/Self_Driving_CV_Repository
[ "27faa8ca86966838998056a42973de292bc380cb", "27faa8ca86966838998056a42973de292bc380cb" ]
[ "deep learning/test/test.py", "deep learning/train/config.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Script to Test Deep Learning Model.\n\nContains a pipeline to test a deep learning model.\n\nRevision History:\n 2021-11-20 (ANI717 - Animesh Bala Ani): Baseline Software.\n\nExample:\n $ python3 test.py\n\n\"\"\"\n\n\n#___Import Modules:\nimport torch\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nimport config\nfrom model import NvidiaNet\nfrom dataset import ANI717Dataset\n\n\n#___Main Method:\ndef main():\n \n # Load Data\n dataset = ANI717Dataset(config.TEST_CSV, config.IMG_SOURCE, transforms=config.TEST_TRANSFORMS)\n loader = DataLoader(dataset, batch_size=1, shuffle=False)\n \n # Initialize Model with Weights\n model = NvidiaNet(in_channels=config.IMG_SHAPE[0]).to(config.DEVICE)\n model.load_state_dict(torch.load(config.MODEL_FILE, map_location=config.DEVICE)[\"state_dict\"])\n model.eval()\n \n # Initialize total correct number and counter\n num_correct = 0.0\n count = 0\n \n # Loop through dataset\n with torch.no_grad():\n \n loop = tqdm(loader, position=0, leave=True)\n for batch_idx, (inputs, z, x) in enumerate(loop):\n \n # Enable GPU support is available\n inputs = inputs.to(config.DEVICE)\n if config.TRAIN_TYPE == 'z':\n targets = z.unsqueeze(1).to(torch.float32).to(config.DEVICE)\n else:\n targets = x.unsqueeze(1).to(torch.float32).to(config.DEVICE)\n \n # Calculate prediction\n predictions = model(inputs)\n \n # Update total correct number and counter\n num_correct += sum(abs(torch.round(targets/config.ERROR_TOLERENCE) - torch.round(predictions/config.ERROR_TOLERENCE)) <= 1).item()\n count += predictions.shape[0]\n \n # Calculate accuracy\n loop.set_postfix(accuracy=100*num_correct/count)\n\n\n#___Driver Program:\nif __name__ == \"__main__\":\n main()\n\n\n# \n# end of file\n\"\"\"ANI717\"\"\"", "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Config File.\n\nContains Hyperparameters and Transformations.\n\nRevision History:\n 2021-11-20 (ANI717 - Animesh Bala Ani): Baseline Software.\n\nExample:\n $ import config\n\n\"\"\"\n\n\n#___Import Modules:\nimport torch\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\n\n\n#___Hyperparameters:\nTRAIN_TYPE = 'z'\n\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nNUM_WORKERS = 1\nPIN_MEMORY = True\n\nIMG_SHAPE = (3, 75, 75) # channels, rows, columns\n\nBATCH_SIZE = 64\nLEARNING_RATE = 1e-4\nNUM_EPOCHS = 150\n\nIMG_SOURCE = '../../dataset/images'\nTRAIN_CSV = '../../dataset/lists/random/train.csv'\nTEST_CSV = '../../dataset/lists/random/test.csv'\nVAL_CSV = '../../dataset/lists/random/val.csv'\n\nLOAD_MODEL = True\nSAVE_MODEL = True\nWRITE_LOG = True\nSAVE_ONNX = True\n\nCHECKPOINT_DIR = \"checkpoints\"\nOUTPUT_DIR = 'output'\nMODEL_FILE = \"checkpoints/epoch_36.pth.tar\"\nONNX_MODEL_FILE = \"checkpoints/epoch_36.onnx\"\n\nERROR_TOLERENCE = 0.1\n\n\n#___Transformations\nTRAIN_TRANSFORMS = A.Compose([\n A.Resize(height=IMG_SHAPE[1], width=IMG_SHAPE[2]),\n A.ColorJitter(p=0.2),\n A.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], max_pixel_value=255.0,),\n ToTensorV2(),])\n\nTEST_TRANSFORMS = A.Compose([\n A.Resize(height=IMG_SHAPE[1], width=IMG_SHAPE[2]),\n A.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], max_pixel_value=255.0,),\n ToTensorV2(),])\n\n\n# \n# end of file\n\"\"\"ANI717\"\"\"" ]
[ [ "torch.no_grad", "torch.round", "torch.utils.data.DataLoader", "torch.load" ], [ "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
datboi223/UnseenObjectClustering
[ "32ec100e7c15478fba5e67509c7bff397e7c885e" ]
[ "lib/datasets/osd_object.py" ]
[ "# Copyright (c) 2020 NVIDIA Corporation. All rights reserved.\n# This work is licensed under the NVIDIA Source Code License - Non-commercial. Full\n# text can be found in LICENSE.md\n\nimport torch\nimport torch.utils.data as data\nimport os, math\nimport sys\nimport time\nimport random\nimport numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\nimport datasets\nimport open3d as o3d\nimport pcl\n\nfrom fcn.config import cfg\nfrom utils.blob import chromatic_transform, add_noise\nfrom utils import mask as util_\n\n\nclass OSDObject(data.Dataset, datasets.imdb):\n def __init__(self, image_set, osd_object_path = None):\n\n self._name = 'osd_object_' + image_set\n self._image_set = image_set\n self._osd_object_path = self._get_default_path() if osd_object_path is None \\\n else osd_object_path\n self._classes_all = ('__background__', 'foreground')\n self._classes = self._classes_all\n self._pixel_mean = torch.tensor(cfg.PIXEL_MEANS / 255.0).float()\n self._width = 640\n self._height = 480\n\n ## TODO\n print('self._osd_object_path = ', self._osd_object_path)\n\n # get all images\n data_path = os.path.join(self._osd_object_path, 'image_color')\n self.image_files = sorted(glob.glob(data_path + '/*.png'))\n\n print('%d images for dataset %s' % (len(self.image_files), self._name))\n self._size = len(self.image_files)\n assert os.path.exists(self._osd_object_path), \\\n 'osd_object path does not exist: {}'.format(self._osd_object_path)\n\n\n def process_label(self, foreground_labels):\n \"\"\" Process foreground_labels\n - Map the foreground_labels to {0, 1, ..., K-1}\n\n @param foreground_labels: a [H x W] numpy array of labels\n\n @return: foreground_labels\n \"\"\"\n # Find the unique (nonnegative) foreground_labels, map them to {0, ..., K-1}\n unique_nonnegative_indices = np.unique(foreground_labels)\n mapped_labels = foreground_labels.copy()\n for k in range(unique_nonnegative_indices.shape[0]):\n mapped_labels[foreground_labels == unique_nonnegative_indices[k]] = k\n foreground_labels = mapped_labels\n return foreground_labels\n\n\n def __getitem__(self, idx):\n\n # BGR image\n filename = self.image_files[idx]\n print('filename = ', filename)\n im = cv2.imread(filename)\n if cfg.TRAIN.CHROMATIC and cfg.MODE == 'TRAIN' and np.random.rand(1) > 0.1:\n im = chromatic_transform(im)\n if cfg.TRAIN.ADD_NOISE and cfg.MODE == 'TRAIN' and np.random.rand(1) > 0.1:\n im = add_noise(im)\n im_tensor = torch.from_numpy(im) / 255.0\n\n im_tensor_bgr = im_tensor.clone()\n im_tensor_bgr = im_tensor_bgr.permute(2, 0, 1)\n\n im_tensor -= self._pixel_mean\n image_blob = im_tensor.permute(2, 0, 1)\n\n # Label\n labels_filename = filename.replace('image_color', 'annotation')\n foreground_labels = util_.imread_indexed(labels_filename)\n foreground_labels = self.process_label(foreground_labels)\n label_blob = torch.from_numpy(foreground_labels).unsqueeze(0)\n\n index = filename.find('OSD')\n sample = {'image_color': image_blob,\n 'image_color_bgr': im_tensor_bgr,\n 'label': label_blob,\n 'filename': filename[index+4:]}\n\n # Depth image\n if cfg.INPUT == 'DEPTH' or cfg.INPUT == 'RGBD':\n pcd_filename = filename.replace('image_color', 'pcd')\n pcd_filename = pcd_filename.replace('png', 'pcd')\n print('pcd_filename = ', pcd_filename)\n pcloud = pcl.load(pcd_filename).to_array()\n pcloud[np.isnan(pcloud)] = 0\n xyz_img = pcloud.reshape((self._height, self._width, 3))\n depth_blob = torch.from_numpy(xyz_img).permute(2, 0, 1)\n sample['depth'] = depth_blob\n\n # # Depth image\n # if cfg.INPUT == 'DEPTH' or cfg.INPUT == 'RGBD':\n # pcd_filename = filename.replace('image_color', 'pcd')\n # pcd_filename = pcd_filename.replace('png', 'pcd')\n\n # # pcl replaced with open3d\n # pcloud = o3d.io.read_point_cloud(pcd_filename)\n # pcloud = np.asarray(pcloud)\n # print(np.isnan(pcloud))\n # pcloud[np.isnan(pcloud)] = 0\n # xyz_img = pcloud.reshape((self._height, self._width, 3))\n # depth_blob = torch.from_numpy(xyz_img).permute(2, 0, 1)\n # sample['depth'] = depth_blob\n\n return sample\n\n\n def __len__(self):\n return self._size\n\n\n def _get_default_path(self):\n \"\"\"\n Return the default path where osd_object is expected to be installed.\n \"\"\"\n return os.path.join(datasets.ROOT_DIR, 'data', 'OSD')\n" ]
[ [ "numpy.unique", "numpy.isnan", "torch.from_numpy", "torch.tensor", "numpy.random.rand" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rupshree1999/Brats2019
[ "715274b4a407f8ca8fa11d2e3743c5ddb328e59a" ]
[ "src/models.py" ]
[ "import tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom tflearn.layers.conv import global_avg_pool\n#######################\n# 3d functions\n#######################\n# convolution\n\n\n# 3D unet graph\ndef unet(inputI, output_channel):\n \"\"\"3D U-net\"\"\"\n phase_flag = 1\n concat_dim = 4\n\n conv1_1 = conv3d(\n input=inputI,\n output_chn=64,\n kernel_size=3,\n stride=1,\n use_bias=False,\n name='conv1')\n # conv1_1 (1, 96, 96, 96, 64)\n conv1_bn = tf.contrib.layers.batch_norm(\n conv1_1,\n decay=0.9,\n updates_collections=None,\n epsilon=1e-5,\n scale=True,\n is_training=phase_flag,\n scope=\"conv1_batch_norm\")\n conv1_relu = tf.nn.relu(conv1_bn, name='conv1_relu')\n\n pool1_in = tf.layers.max_pooling3d(\n inputs=conv1_relu, pool_size=2, strides=2, name='pool1')\n # pool1 (1, 48, 48, 48, 64)\n # pool1_frac = fractal_net(\n # is_global_path_list[0],\n # global_path_list[0],\n # local_path_list[0],\n # self.Blocks,\n # self.Columns)(pool1_in)\n # pool1_old = pool1_in + pool1_frac\n pool1 = pool1_in\n conv2_1 = conv3d(\n input=pool1,\n output_chn=128,\n kernel_size=3,\n stride=1,\n use_bias=False,\n name='conv2')\n # (1, 48, 48, 48, 128)\n conv2_bn = tf.contrib.layers.batch_norm(\n conv2_1,\n decay=0.9,\n updates_collections=None,\n epsilon=1e-5,\n scale=True,\n is_training=phase_flag,\n scope=\"conv2_batch_norm\")\n conv2_relu = tf.nn.relu(conv2_bn, name='conv2_relu')\n\n pool2_in = tf.layers.max_pooling3d(\n inputs=conv2_relu, pool_size=2, strides=2, name='pool2')\n # pool2 (1, 24, 24, 24, 128)\n # pool2_frac = fractal_net(\n # is_global_path_list[1],\n # global_path_list[1],\n # local_path_list[1],\n # self.Blocks,\n # self.Columns)(pool2_in)\n # pool2 = pool2_in + pool2_frac\n pool2 = pool2_in\n\n conv3_1 = conv3d(\n input=pool2,\n output_chn=256,\n kernel_size=3,\n stride=1,\n use_bias=False,\n name='conv3a')\n # (1, 24, 24, 24, 256)\n conv3_1_bn = tf.contrib.layers.batch_norm(\n conv3_1,\n decay=0.9,\n updates_collections=None,\n epsilon=1e-5,\n scale=True,\n is_training=phase_flag,\n scope=\"conv3_1_batch_norm\")\n conv3_1_relu = tf.nn.relu(conv3_1_bn, name='conv3_1_relu')\n conv3_2 = conv3d(\n input=conv3_1_relu,\n output_chn=256,\n kernel_size=3,\n stride=1,\n use_bias=False,\n name='conv3b')\n # (1, 24, 24, 24, 256)\n conv3_2 = conv3_2 + conv3_1\n conv3_2_bn = tf.contrib.layers.batch_norm(\n conv3_2,\n decay=0.9,\n updates_collections=None,\n epsilon=1e-5,\n scale=True,\n is_training=phase_flag,\n scope=\"conv3_2_batch_norm\")\n conv3_2_relu = tf.nn.relu(conv3_2_bn, name='conv3_2_relu')\n\n pool3_in = tf.layers.max_pooling3d(\n inputs=conv3_2_relu, pool_size=2, strides=2, name='pool3')\n # pool3 (1, 12, 12, 12, 256)\n # pool3_frac = fractal_net(\n # is_global_path_list[2],\n # global_path_list[2],\n # local_path_list[2],\n # self.Blocks,\n # self.Columns)(pool3_in)\n pool3 = pool3_in\n # pool3 = pool3_in + pool3_frac\n\n conv4_1 = conv3d(\n input=pool3,\n output_chn=512,\n kernel_size=3,\n stride=1,\n use_bias=False,\n name='conv4a')\n # conv4_1 (1, 12, 12, 12, 512)\n conv4_1_bn = tf.contrib.layers.batch_norm(\n conv4_1,\n decay=0.9,\n updates_collections=None,\n epsilon=1e-5,\n scale=True,\n is_training=phase_flag,\n scope=\"conv4_1_batch_norm\")\n conv4_1_relu = tf.nn.relu(conv4_1_bn, name='conv4_1_relu')\n conv4_2 = conv3d(\n input=conv4_1_relu,\n output_chn=512,\n kernel_size=3,\n stride=1,\n use_bias=False,\n name='conv4b')\n conv4_2 = conv4_2 + conv4_1\n # conv4_2 (1, 12, 12, 12, 512)\n conv4_2_bn = tf.contrib.layers.batch_norm(\n conv4_2,\n decay=0.9,\n updates_collections=None,\n epsilon=1e-5,\n scale=True,\n is_training=phase_flag,\n scope=\"conv4_2_batch_norm\")\n conv4_2_relu = tf.nn.relu(conv4_2_bn, name='conv4_2_relu')\n\n pool4 = tf.layers.max_pooling3d(\n inputs=conv4_2_relu,\n pool_size=2,\n strides=2,\n name='pool4')\n # pool4 (1, 6, 6, 6, 512)\n conv5_1 = conv_bn_relu(\n input=pool4,\n output_chn=512,\n kernel_size=3,\n stride=1,\n use_bias=False,\n is_training=phase_flag,\n name='conv5_1')\n # conv5_1 (1, 6, 6, 6, 512)\n conv5_2 = conv_bn_relu(\n input=conv5_1,\n output_chn=512,\n kernel_size=3,\n stride=1,\n use_bias=False,\n is_training=phase_flag,\n name='conv5_2')\n # conv5_2 (1, 6, 6, 6, 512)\n\n deconv1_1 = deconv_bn_relu(\n input=conv5_2,\n output_chn=512,\n is_training=phase_flag,\n name='deconv1_1')\n # (1, 12, 12, 12, 512)\n\n concat_1 = tf.concat([deconv1_1, conv4_2],\n axis=concat_dim, name='concat_1')\n # (1, 12, 12, 12, 1024)\n\n deconv1_2_in = conv_bn_relu(\n input=concat_1,\n output_chn=256,\n kernel_size=3,\n stride=1,\n use_bias=False,\n is_training=phase_flag,\n name='deconv1_2')\n # deconv1_2_frac = fractal_net(\n # is_global_path_list[3],\n # global_path_list[3],\n # local_path_list[3],\n # self.Blocks,\n # self.Columns)(deconv1_2_in)\n deconv1_2 = deconv1_2_in\n # deconv1_2 = deconv1_2_in + deconv1_2_frac # (1, 12, 12, 12, 256)\n\n deconv2_1 = deconv_bn_relu(\n input=deconv1_2,\n output_chn=256,\n is_training=phase_flag,\n name='deconv2_1')\n\n concat_2 = tf.concat([deconv2_1, conv3_2],\n axis=concat_dim, name='concat_2')\n # deconv2_2 (1, 24, 24, 24, 512)\n deconv2_2_in = conv_bn_relu(\n input=concat_2,\n output_chn=128,\n kernel_size=3,\n stride=1,\n use_bias=False,\n is_training=phase_flag,\n name='deconv2_2')\n # deconv2_2_frac = fractal_net(\n # is_global_path_list[4],\n # global_path_list[4],\n # local_path_list[4],\n # self.Blocks,\n # self.Columns)(deconv2_2_in)\n deconv2_2 = deconv2_2_in\n # deconv2_2 = deconv2_2_in + deconv2_2_frac\n # deconv2_2 (1, 24, 24, 24, 128)\n\n deconv3_1 = deconv_bn_relu(\n input=deconv2_2,\n output_chn=128,\n is_training=phase_flag,\n name='deconv3_1')\n # deconv3_1 (1, 48, 48, 48, 128)\n\n concat_3 = tf.concat([deconv3_1, conv2_1],\n axis=concat_dim, name='concat_3')\n # deconv3_1 (1, 48, 48, 48, 256)\n\n deconv3_2_in = conv_bn_relu(\n input=concat_3,\n output_chn=64,\n kernel_size=3,\n stride=1,\n use_bias=False,\n is_training=phase_flag,\n name='deconv3_2')\n # deconv3_2_frac = fractal_net(\n # is_global_path_list[5],\n # global_path_list[5],\n # local_path_list[5],\n # self.Blocks,\n # self.Columns)(deconv3_2_in)\n deconv3_2 = deconv3_2_in\n # deconv3_2 = deconv3_2_in + deconv3_2_frac\n # deconv3_2 (1, 48, 48, 48, 64)\n\n deconv4_1 = deconv_bn_relu(\n input=deconv3_2,\n output_chn=64,\n is_training=phase_flag,\n name='deconv4_1')\n # deconv4_2 (1, 96, 96, 96, 32)\n\n concat_4 = tf.concat([deconv4_1, conv1_1],\n axis=concat_dim, name='concat_4')\n # deconv4_2 (1, 96, 96, 96, 64)\n deconv4_2 = conv_bn_relu(\n input=concat_4,\n output_chn=32,\n kernel_size=3,\n stride=1,\n use_bias=False,\n is_training=phase_flag,\n name='deconv4_2') # deconv4_2 (1, 96, 96, 96, 32)\n\n pre_pro = conv3d(\n input=deconv4_2,\n output_chn=output_channel,\n kernel_size=1,\n stride=1,\n use_bias=True,\n name='pre_pro')\n # pred_frac = fractal_net(is_global_path_list[3],global_path_list[3],local_path_list[3],self.Blocks,self.Columns)(pre_pro)\n pred_prob = pre_pro # pred_prob (1, 96, 96, 96, 8) Here get the prediction\n\n # ======================For predicition=============================\n # auxiliary prediction 0\n aux0_conv = conv3d(\n input=deconv1_2,\n output_chn=output_channel,\n kernel_size=1,\n stride=1,\n use_bias=True,\n name='aux0_conv') # aux0_conv (1, 12, 12, 12, 8) 8 class output\n aux0_deconv_1 = Deconv3d(\n input=aux0_conv,\n output_chn=output_channel,\n name='aux0_deconv_1') # aux0_deconv_1 (1, 24, 24, 24, 8)\n aux0_deconv_2 = Deconv3d(\n input=aux0_deconv_1,\n output_chn=output_channel,\n name='aux0_deconv_2') # aux0_deconv_2 (1, 48, 48, 48, 8)\n aux0_prob = Deconv3d(\n input=aux0_deconv_2,\n output_chn=output_channel,\n name='aux0_prob') # aux0_prob (1, 96, 96, 96, 8)\n\n # auxiliary prediction 1\n aux1_conv = conv3d(\n input=deconv2_2,\n output_chn=output_channel,\n kernel_size=1,\n stride=1,\n use_bias=True,\n name='aux1_conv') # aux1_conv (1, 24, 24, 24, 8)\n aux1_deconv_1 = Deconv3d(\n input=aux1_conv,\n output_chn=output_channel,\n name='aux1_deconv_1') # aux1_deconv_1 (1, 48, 48, 48, 8)\n aux1_prob = Deconv3d(\n input=aux1_deconv_1,\n output_chn=output_channel,\n name='aux1_prob') # aux1_prob (1, 96, 96, 96, 8)\n\n # auxiliary prediction 2\n aux2_conv = conv3d(\n input=deconv3_2,\n output_chn=output_channel,\n kernel_size=1,\n stride=1,\n use_bias=True,\n name='aux2_conv') # aux2_conv (1, 48, 48, 48, 8)\n aux2_prob = Deconv3d(\n input=aux2_conv,\n output_chn=output_channel,\n name='aux2_prob') # aux2_prob (1, 96, 96, 96, 8)\n\n soft_prob = tf.nn.softmax(pred_prob, name='pred_soft')\n pred_label = tf.argmax(soft_prob, axis=4, name='argmax')\n\n return pred_prob, pred_label, aux0_prob, aux1_prob, aux2_prob\n\ndef unet_resnet(input_pred, input_img, output_channel, stage):\n input_shape = input_img.shape\n input_channel = input_shape.dims[-1].value\n input_pred_softmax = tf.nn.softmax(input_pred, name='softmax_ss' + stage)\n forground_input_pred = tf.expand_dims(input_pred_softmax[:, :, :, :, 1], axis=-1)\n input_concat = tf.concat([forground_input_pred, input_img], axis=-1) # (1, 96, 96, 96, 2)\n\n input_attention = forground_input_pred * input_img # (1, 96, 96, 96, input_channel)\n # conv block1\n conv_bn_1_1 = conv_bn_relu(input=input_attention, output_chn=16, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block1_conv1')\n input_cat = tf.concat([input_attention, input_attention, input_attention, input_attention,\n input_attention, input_attention, input_attention, input_attention], axis=-1)\n # diffirence for odd input or even input\n if input_channel % 2 == 0 or input_channel == 1:\n input_tile = tf.tile(input=input_attention, multiples=[1, 1, 1, 1, int(16/input_channel)], name='tile' + stage)\n else:\n input_tile = tf.tile(input=input_attention, multiples=[1, 1, 1, 1, int(16/(input_channel-1))], name='tile' + stage)\n input_tile = input_tile[:,:,:,:,0:16]\n conv_bn_skip_1_1 = input_tile + conv_bn_1_1\n pool1_1 = tf.layers.max_pooling3d(inputs=conv_bn_skip_1_1, pool_size=2, strides=2, name=stage + 'pool_1_1')\n\n # conv block2\n conv_bn_2_1 = conv_bn_relu(input=pool1_1, output_chn=32, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block2_conv1')\n conv_bn_2_2 = conv_bn_relu(input=conv_bn_2_1, output_chn=32, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block2_conv2')\n pool1_1_cat = tf.concat([pool1_1, pool1_1], axis=-1)\n conv_bn_skip_2_1 = pool1_1_cat + conv_bn_2_2\n pool_2_1 = tf.layers.max_pooling3d(inputs=conv_bn_skip_2_1, pool_size=2, strides=2, name=stage + 'pool2_2')\n\n # conv block3\n conv_bn_3_1 = conv_bn_relu(input=pool_2_1, output_chn=64, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block3_conv1')\n conv_bn_3_2 = conv_bn_relu(input=conv_bn_3_1, output_chn=64, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block3_conv2')\n conv_bn_3_3 = conv_bn_relu(input=conv_bn_3_2, output_chn=64, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block3_conv3')\n pool_2_1_cat = tf.concat([pool_2_1, pool_2_1], axis=-1)\n conv_bn_skip_3_1 = conv_bn_3_3 + pool_2_1_cat\n pool3_1 = tf.layers.max_pooling3d(inputs=conv_bn_skip_3_1, pool_size=2, strides=2, name=stage + 'pool3_1')\n\n # conv block4\n conv_bn_4_1 = conv_bn_relu(input=pool3_1, output_chn=128, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block4_conv1')\n conv_bn_4_2 = conv_bn_relu(input=conv_bn_4_1, output_chn=128, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block4_conv2')\n conv_bn_4_3 = conv_bn_relu(input=conv_bn_4_2, output_chn=128, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block4_conv3')\n pool3_1_cat = tf.concat([pool3_1, pool3_1], axis=-1)\n conv_bn_skip_4_1 = conv_bn_4_3 + pool3_1_cat\n pool4_1 = tf.layers.max_pooling3d(inputs=conv_bn_skip_4_1, pool_size=2, strides=2, name=stage + 'pool4_1')\n\n # conv block5\n conv_bn_5_1 = conv_bn_relu(input=pool4_1, output_chn=256, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block5_conv1')\n conv_bn_5_2 = conv_bn_relu(input=conv_bn_5_1, output_chn=256, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block5_conv2')\n conv_bn_5_3 = conv_bn_relu(input=conv_bn_5_2, output_chn=256, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block5_conv3')\n pool4_1_cat = tf.concat([pool4_1, pool4_1], axis=-1)\n conv_bn_skip_5_1 = conv_bn_5_3 + pool4_1_cat\n\n # upsampling conv block6\n deconv_bn_1_1 = deconv_bn_relu(input=conv_bn_skip_5_1, output_chn=128, is_training=True,\n name=stage + 'deconv_1_1')\n concat1 = tf.concat([deconv_bn_1_1, conv_bn_skip_4_1], axis=-1, name=stage + 'concat1')\n conv_bn_6_1 = conv_bn_relu(input=concat1, output_chn=256, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block6_conv1')\n conv_bn_6_2 = conv_bn_relu(input=conv_bn_6_1, output_chn=256, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block6_conv2')\n conv_bn_6_3 = conv_bn_relu(input=conv_bn_6_2, output_chn=256, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'blovk6_conv3')\n\n deconv_bn_1_1_cat = tf.concat([deconv_bn_1_1, deconv_bn_1_1], axis=-1)\n conv_bn_skip_6_1 = conv_bn_6_3 + deconv_bn_1_1_cat\n\n # conv block7\n deconv_bn_2_1 = deconv_bn_relu(input=conv_bn_skip_6_1, output_chn=64, is_training=True,\n name=stage + 'deconv_2_1')\n concat2 = tf.concat([deconv_bn_2_1, conv_bn_skip_3_1], axis=-1, name=stage + 'concat2')\n conv_bn_7_1 = conv_bn_relu(input=concat2, output_chn=128, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block7_conv1')\n conv_bn_7_2 = conv_bn_relu(input=conv_bn_7_1, output_chn=128, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block7_conv2')\n conv_bn_7_3 = conv_bn_relu(input=conv_bn_7_2, output_chn=128, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block7_conv3')\n deconv_bn_2_1_cat = tf.concat([deconv_bn_2_1, deconv_bn_2_1], axis=-1)\n conv_bn_skip_7_1 = conv_bn_7_3 + deconv_bn_2_1_cat\n\n # conv block8\n deconv_bn_3_1 = deconv_bn_relu(input=conv_bn_skip_7_1, output_chn=32, is_training=True,\n name=stage + 'deconv_3_1')\n concat3 = tf.concat([deconv_bn_3_1, conv_bn_skip_2_1], axis=-1, name=stage + 'concat3')\n conv_bn_8_1 = conv_bn_relu(input=concat3, output_chn=64, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block8_conv1')\n conv_bn_8_2 = conv_bn_relu(input=conv_bn_8_1, output_chn=64, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block8_conv2')\n\n deconv_bn_3_1_cat = tf.concat([deconv_bn_3_1, deconv_bn_3_1], axis=-1)\n conv_bn_skip_8_1 = conv_bn_8_2 + deconv_bn_3_1_cat\n\n # conv block9\n deconv_bn_4_1 = deconv_bn_relu(input=conv_bn_skip_8_1, output_chn=16, is_training=True,\n name=stage + 'deconv_4_1')\n concat4 = tf.concat([deconv_bn_4_1, conv_bn_skip_1_1], axis=-1, name=stage + 'conca4_1')\n conv_bn_9_1 = conv_bn_relu(input=concat4, output_chn=32, kernel_size=3, stride=1, use_bias=False,\n is_training=True, name=stage + 'block9_conv1')\n deconv_bn_4_1_cat = tf.concat([deconv_bn_4_1, deconv_bn_4_1], axis=-1)\n conv_bn_skip_9_1 = conv_bn_9_1 + deconv_bn_4_1_cat\n\n # prediction layer\n pred = conv3d(input=conv_bn_skip_9_1, output_chn=output_channel, kernel_size=1, stride=1, use_bias=True,\n name=stage + 'pred')\n soft_prob_v = tf.nn.softmax(pred, name='pred_soft_v')\n pred_label_v = tf.argmax(soft_prob_v, axis=4, name='argmax_v')\n return pred, pred_label_v\n\ndef conv3d(\n input,\n output_chn,\n kernel_size,\n stride,\n use_bias=False,\n name='conv'):\n return tf.layers.conv3d(\n inputs=input,\n filters=output_chn,\n kernel_size=kernel_size,\n strides=stride,\n padding='same',\n data_format='channels_last',\n kernel_initializer=tf.truncated_normal_initializer(\n 0.0,\n 0.01),\n kernel_regularizer=slim.l2_regularizer(0.0005),\n use_bias=use_bias,\n name=name)\n\n\ndef conv_bn_relu(\n input,\n output_chn,\n kernel_size,\n stride,\n use_bias,\n is_training,\n name):\n with tf.variable_scope(name):\n conv = conv3d(\n input,\n output_chn,\n kernel_size,\n stride,\n use_bias,\n name='conv')\n bn = tf.contrib.layers.batch_norm(\n conv,\n decay=0.9,\n updates_collections=None,\n epsilon=1e-5,\n scale=True,\n is_training=is_training,\n scope=\"batch_norm\")\n relu = tf.nn.relu(bn, name='relu')\n return relu\n\n\n# deconvolution\ndef Deconv3d(input, output_chn, name):\n batch, in_depth, in_height, in_width, in_channels = [\n int(d) for d in input.get_shape()]\n filter = tf.get_variable(\n name + \"/filter\",\n shape=[\n 4,\n 4,\n 4,\n output_chn,\n in_channels],\n dtype=tf.float32,\n initializer=tf.random_normal_initializer(\n 0,\n 0.01),\n regularizer=slim.l2_regularizer(0.0005))\n\n conv = tf.nn.conv3d_transpose(\n value=input,\n filter=filter,\n output_shape=[\n batch,\n in_depth * 2,\n in_height * 2,\n in_width * 2,\n output_chn],\n strides=[\n 1,\n 2,\n 2,\n 2,\n 1],\n padding=\"SAME\",\n name=name)\n return conv\n\n\ndef Unsample(input, output_chn, name):\n batch, in_depth, in_height, in_width, in_channels = [\n int(d) for d in input.get_shape()]\n base = input.shape[-2]\n data = 96 / int(base)\n print(\"base shape\", data)\n filter = tf.get_variable(\n name + \"/filter\",\n shape=[\n 4,\n 4,\n 4,\n output_chn,\n in_channels],\n dtype=tf.float32,\n initializer=tf.random_normal_initializer(\n 0,\n 0.01),\n regularizer=slim.l2_regularizer(0.0005))\n\n conv = tf.nn.conv3d_transpose(\n value=input, filter=filter, output_shape=[\n batch, 96, 96, 96, output_chn], strides=[\n 1, data, data, data, 1], padding=\"SAME\", name=name)\n return conv\n\n\ndef deconv_bn_relu(input, output_chn, is_training, name):\n with tf.variable_scope(name):\n conv = Deconv3d(input, output_chn, name='deconv')\n # with tf.device(\"/cpu:0\"):\n bn = tf.contrib.layers.batch_norm(\n conv,\n decay=0.9,\n updates_collections=None,\n epsilon=1e-5,\n scale=True,\n is_training=is_training,\n scope=\"batch_norm\")\n relu = tf.nn.relu(bn, name='relu')\n return relu\n\n\ndef conv_bn_relu_x3(\n input,\n output_chn,\n kernel_size,\n stride,\n use_bias,\n is_training,\n name):\n with tf.variable_scope(name):\n z = conv_bn_relu(\n input,\n output_chn,\n kernel_size,\n stride,\n use_bias,\n is_training,\n \"dense1\")\n z_out = conv_bn_relu(\n z,\n output_chn,\n kernel_size,\n stride,\n use_bias,\n is_training,\n \"dense2\")\n z_out = conv_bn_relu(\n z_out,\n output_chn,\n kernel_size,\n stride,\n use_bias,\n is_training,\n \"dense3\")\n return z + z_out" ]
[ [ "tensorflow.nn.relu", "tensorflow.nn.softmax", "tensorflow.concat", "tensorflow.layers.max_pooling3d", "tensorflow.contrib.slim.l2_regularizer", "tensorflow.expand_dims", "tensorflow.truncated_normal_initializer", "tensorflow.variable_scope", "tensorflow.contrib.layers.batch_norm", "tensorflow.argmax", "tensorflow.random_normal_initializer", "tensorflow.nn.conv3d_transpose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yisuoyanyudmj/RLs-1
[ "a336b57e804507bca23cbadc3b5af1924c80d942", "a336b57e804507bca23cbadc3b5af1924c80d942" ]
[ "rls/utils/build_networks.py", "rls/memories/replay_buffer.py" ]
[ "\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\n\r\nfrom copy import deepcopy\r\nfrom abc import ABC, abstractmethod\r\nfrom tensorflow.keras import Model as M\r\n\r\nfrom rls.utils.indexs import OutputNetworkType\r\nfrom rls.nn.networks import get_visual_network_from_type\r\nfrom rls.nn.models import get_output_network_from_type\r\nfrom rls.nn.networks import (MultiVectorNetwork,\r\n MultiVisualNetwork,\r\n EncoderNetwork,\r\n MemoryNetwork)\r\nfrom rls.utils.logging_utils import get_logger\r\nlogger = get_logger(__name__)\r\n\r\n\r\nclass RepresentationNetwork(ABC):\r\n\r\n def __init__(self, name: str = 'test'):\r\n self.name = name\r\n self.h_dim = None\r\n\r\n @abstractmethod\r\n def __call__(self):\r\n pass\r\n\r\n @property\r\n @abstractmethod\r\n def trainable_variables(self):\r\n pass\r\n\r\n @property\r\n @abstractmethod\r\n def weights(self):\r\n pass\r\n\r\n @property\r\n @abstractmethod\r\n def _policy_models(self):\r\n pass\r\n\r\n @property\r\n @abstractmethod\r\n def _all_models(self):\r\n pass\r\n\r\n\r\nclass DefaultRepresentationNetwork(RepresentationNetwork):\r\n '''\r\n visual_s -> visual_net -> feat ↘\r\n feat -> encoder_net -> feat ↘ ↗ feat\r\n s -> vector_net -> feat ↗ -> memory_net ->\r\n cell_state ↗ ↘ cell_state\r\n '''\r\n\r\n def __init__(self,\r\n name: str = 'test',\r\n vec_dims=[],\r\n vis_dims=[],\r\n\r\n vector_net_kwargs: dict = {},\r\n visual_net_kwargs: dict = {},\r\n encoder_net_kwargs: dict = {},\r\n memory_net_kwargs: dict = {}):\r\n super().__init__(name)\r\n self.vector_net = MultiVectorNetwork(vec_dims, **vector_net_kwargs)\r\n logger.debug('initialize vector network successfully.')\r\n self.visual_net = MultiVisualNetwork(vis_dims, **visual_net_kwargs)\r\n logger.debug('initialize visual network successfully.')\r\n\r\n encoder_dim = self.vector_net.h_dim + self.visual_net.h_dim\r\n self.encoder_net = EncoderNetwork(encoder_dim, **encoder_net_kwargs)\r\n logger.debug('initialize encoder network successfully.')\r\n\r\n memory_dim = self.encoder_net.h_dim\r\n self.memory_net = MemoryNetwork(memory_dim, **memory_net_kwargs)\r\n logger.debug('initialize memory network successfully.')\r\n\r\n self.h_dim = self.memory_net.h_dim\r\n\r\n def split(self, batch_size, data):\r\n '''TODO: Annotation\r\n params:\r\n batch_size: int\r\n data: [B, x]\r\n '''\r\n if self.memory_net.use_rnn:\r\n data = tf.reshape(data, [batch_size, -1, tf.shape(data)[-1]])\r\n d, d_ = data[:, :-1], data[:, 1:]\r\n d, d_ = tf.reshape(d, [-1, tf.shape(d)[-1]]), tf.reshape(d_, [-1, tf.shape(d_)[-1]])\r\n return d, d_\r\n else:\r\n return tf.split(data, num_or_size_splits=2, axis=0)\r\n\r\n def __call__(self, s, visual_s, cell_state, *, need_split=False):\r\n '''\r\n params:\r\n s: [B*T, x]\r\n visual_s: [B*T, y]\r\n cell_state: Tuple([B, z],)\r\n return:\r\n feat: [B, a]\r\n cell_state: Tuple([B, z],)\r\n '''\r\n batch_size = tf.shape(s)[0]\r\n if self.memory_net.use_rnn:\r\n s = tf.reshape(s, [-1, tf.shape(s)[-1]]) # [B, T+1, N] => [B*(T+1), N]\r\n if self.visual_net.use_visual:\r\n visual_s = tf.reshape(visual_s, [-1, *tf.shape(visual_s)[2:]])\r\n\r\n feat = self.get_encoder_feature(s, visual_s)\r\n if self.memory_net.use_rnn:\r\n # reshape feature from [B*T, x] to [B, T, x]\r\n feat = tf.reshape(feat, (batch_size, -1, tf.shape(feat)[-1]))\r\n feat, cell_state = self.memory_net(feat, *cell_state)\r\n # reshape feature from [B, T, x] to [B*T, x]\r\n feat = tf.reshape(feat, (-1, tf.shape(feat)[-1]))\r\n\r\n if need_split:\r\n feat = self.split(batch_size, feat)\r\n\r\n return feat, cell_state\r\n\r\n def get_vis_feature(self, visual_s):\r\n '''\r\n params:\r\n visual_s: [B, N, H, W, C]\r\n return:\r\n feat: [B, x]\r\n '''\r\n # TODO\r\n viss = [visual_s[:, i] for i in range(visual_s.shape[1])]\r\n return self.visual_net(*viss)\r\n\r\n def get_vec_feature(self, s):\r\n '''\r\n params:\r\n s: [B, x]\r\n return:\r\n feat: [B, y]\r\n '''\r\n return self.vector_net(s)\r\n\r\n def get_encoder_feature(self, s, visual_s):\r\n '''\r\n params:\r\n s: [B, x]\r\n visual_s: [B, y]\r\n return:\r\n feat: [B, z]\r\n '''\r\n\r\n if self.vector_net.use_vector and self.visual_net.use_visual:\r\n feat = self.get_vec_feature(s)\r\n vis_feat = self.get_vis_feature(visual_s)\r\n feat = tf.concat([feat, vis_feat], axis=-1)\r\n elif self.visual_net.use_visual:\r\n vis_feat = self.get_vis_feature(visual_s)\r\n feat = vis_feat\r\n else:\r\n feat = self.get_vec_feature(s)\r\n\r\n encoder_feature = self.encoder_net(feat)\r\n return encoder_feature\r\n\r\n @property\r\n def trainable_variables(self):\r\n tv = []\r\n tv += self.vector_net.trainable_variables\r\n tv += self.visual_net.trainable_variables\r\n tv += self.encoder_net.trainable_variables\r\n tv += self.memory_net.trainable_variables\r\n return tv\r\n\r\n @property\r\n def weights(self):\r\n ws = []\r\n ws += self.vector_net.weights\r\n ws += self.visual_net.weights\r\n ws += self.encoder_net.weights\r\n ws += self.memory_net.weights\r\n return ws\r\n\r\n @property\r\n def _policy_models(self):\r\n models = {}\r\n models.update({self.name + '/' + 'vector_net': self.vector_net})\r\n models.update({self.name + '/' + 'visual_net': self.visual_net})\r\n models.update({self.name + '/' + 'encoder_net': self.encoder_net})\r\n models.update({self.name + '/' + 'memory_net': self.memory_net})\r\n return models\r\n\r\n @property\r\n def _all_models(self):\r\n models = {}\r\n models.update({self.name + '/' + 'vector_net': self.vector_net})\r\n models.update({self.name + '/' + 'visual_net': self.visual_net})\r\n models.update({self.name + '/' + 'encoder_net': self.encoder_net})\r\n models.update({self.name + '/' + 'memory_net': self.memory_net})\r\n return models\r\n\r\n\r\nclass ValueNetwork:\r\n '''\r\n feat -> value_net -> outputs\r\n '''\r\n\r\n def __init__(self,\r\n name: str = 'test',\r\n representation_net: RepresentationNetwork = None,\r\n\r\n value_net_type: OutputNetworkType = None,\r\n value_net_kwargs: dict = {}):\r\n assert value_net_type is not None, 'assert value_net_type is not None'\r\n super().__init__()\r\n self.name = name\r\n self.representation_net = representation_net\r\n if self.representation_net is not None:\r\n self.value_net = get_output_network_from_type(value_net_type)(\r\n vector_dim=self.representation_net.h_dim, **value_net_kwargs)\r\n else:\r\n self.value_net = get_output_network_from_type(value_net_type)(\r\n **value_net_kwargs)\r\n\r\n def __call__(self, s, visual_s, *args, cell_state=(None,), **kwargs):\r\n # feature [B, x]\r\n assert self.representation_net is not None, 'self.representation_net is not None'\r\n feat, cell_state = self.representation_net(s, visual_s, cell_state)\r\n output = self.value_net(feat, *args, **kwargs)\r\n return output, cell_state\r\n\r\n def get_value(self, feat, *args, **kwargs):\r\n output = self.value_net(feat, *args, **kwargs)\r\n return output\r\n\r\n @property\r\n def trainable_variables(self):\r\n tv = self.representation_net.trainable_variables if self.representation_net else []\r\n tv += self.value_net.trainable_variables\r\n return tv\r\n\r\n @property\r\n def weights(self):\r\n ws = self.representation_net.weights if self.representation_net else []\r\n ws += self.value_net.weights\r\n return ws\r\n\r\n @property\r\n def _policy_models(self):\r\n models = self.representation_net._policy_models if self.representation_net else {}\r\n models.update({self.name + '/' + 'value_net': self.value_net})\r\n return models\r\n\r\n @property\r\n def _all_models(self):\r\n models = self.representation_net._all_models if self.representation_net else {}\r\n models.update({self.name + '/' + 'value_net': self.value_net})\r\n return models\r\n\r\n\r\nclass DoubleValueNetwork(ValueNetwork):\r\n '''\r\n ↗ value_net1 -> outputs\r\n feat\r\n ↘ value_net2 -> outputs\r\n '''\r\n\r\n def __init__(self,\r\n name: str = 'test',\r\n representation_net: RepresentationNetwork = None,\r\n\r\n value_net_type: OutputNetworkType = None,\r\n value_net_kwargs: dict = {}):\r\n super().__init__(name, representation_net, value_net_type, value_net_kwargs)\r\n if self.representation_net is not None:\r\n self.value_net2 = get_output_network_from_type(value_net_type)(\r\n vector_dim=self.representation_net.h_dim, **value_net_kwargs)\r\n else:\r\n self.value_net2 = get_output_network_from_type(value_net_type)(\r\n **value_net_kwargs)\r\n\r\n def __call__(self, s, visual_s, *args, cell_state=(None,), **kwargs):\r\n # feature [B, x]\r\n feat, cell_state = self.representation_net(s, visual_s, cell_state)\r\n output = self.value_net(feat, *args, **kwargs)\r\n output2 = self.value_net2(feat, *args, **kwargs)\r\n return output, output2, cell_state\r\n\r\n def get_value(self, feat, *args, **kwargs):\r\n output = self.value_net(feat, *args, **kwargs)\r\n output2 = self.value_net2(feat, *args, **kwargs)\r\n return output, output2\r\n\r\n def get_min(self, *args, **kwargs):\r\n return tf.minimum(*self.get_value(*args, **kwargs))\r\n\r\n def get_max(self, *args, **kwargs):\r\n return tf.maximum(*self.get_value(*args, **kwargs))\r\n\r\n @property\r\n def trainable_variables(self):\r\n return super().trainable_variables + self.value_net2.trainable_variables\r\n\r\n @property\r\n def weights(self):\r\n return super().weights + self.value_net2.weights\r\n\r\n @property\r\n def _all_models(self):\r\n models = super()._all_models\r\n models.update({self.name + '/' + 'value_net2': self.value_net2})\r\n return models\r\n\r\n\r\nclass ACNetwork(ValueNetwork):\r\n '''\r\n ↗ policy_net -> outputs\r\n feat\r\n ↘ value_net -> outputs\r\n '''\r\n\r\n def __init__(self,\r\n name: str = 'test',\r\n representation_net: RepresentationNetwork = None,\r\n\r\n policy_net_type: OutputNetworkType = None,\r\n policy_net_kwargs: dict = {},\r\n\r\n value_net_type: OutputNetworkType = None,\r\n value_net_kwargs: dict = {}):\r\n\r\n super().__init__(name, representation_net, value_net_type, value_net_kwargs)\r\n if self.representation_net is not None:\r\n self.policy_net = get_output_network_from_type(policy_net_type)(\r\n vector_dim=self.representation_net.h_dim, **policy_net_kwargs)\r\n else:\r\n self.policy_net = get_output_network_from_type(policy_net_type)(\r\n **policy_net_kwargs)\r\n\r\n def __call__(self, s, visual_s, *args, cell_state=(None,), **kwargs):\r\n # feature [B, x]\r\n feat, cell_state = self.representation_net(s, visual_s, cell_state)\r\n output = self.policy_net(feat, *args, **kwargs)\r\n return output, cell_state\r\n\r\n @property\r\n def actor_trainable_variables(self):\r\n return self.policy_net.trainable_variables\r\n\r\n @property\r\n def critic_trainable_variables(self):\r\n return super().trainable_variables\r\n\r\n @property\r\n def weights(self):\r\n return super().weights + self.policy_net.weights\r\n\r\n @property\r\n def _policy_models(self):\r\n '''重载'''\r\n models = super()._policy_models\r\n models.update({self.name + '/' + 'policy_net': self.policy_net})\r\n return models\r\n\r\n @property\r\n def _all_models(self):\r\n models = super()._all_models\r\n models.update({self.name + '/' + 'policy_net': self.policy_net})\r\n return models\r\n\r\n\r\nclass ACCNetwork(ACNetwork):\r\n '''\r\n Use for PD-DDPG\r\n\r\n ↗ policy_net -> outputs\r\n feat -> value_net -> outputs\r\n ↘ value_net2 -> outputs\r\n '''\r\n\r\n def __init__(self,\r\n name: str = 'test',\r\n representation_net: RepresentationNetwork = None,\r\n\r\n policy_net_type: OutputNetworkType = None,\r\n policy_net_kwargs: dict = {},\r\n\r\n value_net_type: OutputNetworkType = None,\r\n value_net_kwargs: dict = {},\r\n\r\n value_net2_type: OutputNetworkType = None,\r\n value_net2_kwargs: dict = {}):\r\n\r\n super().__init__(name, representation_net,\r\n policy_net_type, policy_net_kwargs,\r\n value_net_type, value_net_kwargs)\r\n if self.representation_net is not None:\r\n self.value_net2 = get_output_network_from_type(value_net2_type)(\r\n vector_dim=self.representation_net.h_dim, **value_net2_kwargs)\r\n else:\r\n self.value_net2 = get_output_network_from_type(value_net2_type)(\r\n **value_net2_kwargs)\r\n\r\n @property\r\n def critic_trainable_variables(self):\r\n return super().critic_trainable_variables + self.value_net2.trainable_variables\r\n\r\n @property\r\n def value_net_trainable_variables(self):\r\n return super().critic_trainable_variables\r\n\r\n @property\r\n def value_net2_trainable_variables(self):\r\n return self.value_net2.trainable_variables\r\n\r\n @property\r\n def weights(self):\r\n return super().weights + self.value_net2.weights\r\n\r\n @property\r\n def _all_models(self):\r\n models = super()._all_models\r\n models.update({self.name + '/' + 'value_net2': self.value_net2})\r\n return models\r\n\r\n\r\nclass ADoubleCNetwork(ACNetwork):\r\n '''\r\n\r\n ↗ policy_net -> outputs\r\n feat -> value_net -> outputs\r\n ↘ value_net2 -> outputs\r\n '''\r\n\r\n def __init__(self,\r\n name: str = 'test',\r\n representation_net: RepresentationNetwork = None,\r\n\r\n policy_net_type: OutputNetworkType = None,\r\n policy_net_kwargs: dict = {},\r\n\r\n value_net_type: OutputNetworkType = None,\r\n value_net_kwargs: dict = {}):\r\n super().__init__(name, representation_net,\r\n policy_net_type, policy_net_kwargs,\r\n value_net_type, value_net_kwargs)\r\n if self.representation_net is not None:\r\n self.value_net2 = get_output_network_from_type(value_net_type)(\r\n vector_dim=self.representation_net.h_dim, **value_net_kwargs)\r\n else:\r\n self.value_net2 = get_output_network_from_type(value_net_type)(\r\n **value_net_kwargs)\r\n\r\n def get_value(self, feat, *args, **kwargs):\r\n output = self.value_net(feat, *args, **kwargs)\r\n output2 = self.value_net2(feat, *args, **kwargs)\r\n return output, output2\r\n\r\n def get_min(self, *args, **kwargs):\r\n return tf.minimum(*self.get_value(*args, **kwargs))\r\n\r\n def get_max(self, *args, **kwargs):\r\n return tf.maximum(*self.get_value(*args, **kwargs))\r\n\r\n @property\r\n def critic_trainable_variables(self):\r\n return super().trainable_variables + self.value_net2.trainable_variables\r\n\r\n @property\r\n def weights(self):\r\n return super().weights + self.value_net2.weights\r\n\r\n @property\r\n def _all_models(self):\r\n models = super()._all_models\r\n models.update({self.name + '/' + 'value_net2': self.value_net2})\r\n return models\r\n", "#!/usr/bin/env python3\n# encoding: utf-8\n\nimport sys\nimport numpy as np\nimport tensorflow as tf\n\nfrom abc import ABC, abstractmethod\nfrom typing import (Any,\n NoReturn,\n Union,\n List,\n Tuple,\n Optional)\n\nfrom rls.memories.sum_tree import Sum_Tree\n\n# [s, visual_s, a, r, s_, visual_s_, done] must be this format.\n\n\nclass ReplayBuffer(ABC):\n def __init__(self,\n batch_size: int,\n capacity: int):\n assert isinstance(batch_size, int) and batch_size >= 0, 'batch_size must be int and larger than 0'\n assert isinstance(capacity, int) and capacity >= 0, 'capacity must be int and larger than 0'\n self.batch_size = batch_size\n self.capacity = capacity\n self._size = 0\n\n def reset(self):\n self._size = 0\n\n @abstractmethod\n def sample(self) -> Any:\n pass\n\n @abstractmethod\n def add(self, *args) -> Any:\n pass\n\n def is_empty(self) -> bool:\n return self._size == 0\n\n def update(self, *args) -> Any:\n pass\n\n\nclass ExperienceReplay(ReplayBuffer):\n def __init__(self,\n batch_size: int,\n capacity: int):\n super().__init__(batch_size, capacity)\n self._data_pointer = 0\n self._buffer = np.empty(capacity, dtype=object)\n\n def add(self, *args) -> NoReturn:\n '''\n change [s, s],[a, a],[r, r] to [s, a, r],[s, a, r] and store every item in it.\n '''\n [self._store_op(data) for data in zip(*args)]\n\n def _store_op(self, data: Union[List, np.ndarray]) -> NoReturn:\n self._buffer[self._data_pointer] = data\n self.update_rb_after_add()\n\n def sample(self) -> List[np.ndarray]:\n '''\n change [[s, a, r],[s, a, r]] to [[s, s],[a, a],[r, r]]\n '''\n n_sample = self.batch_size if self.is_lg_batch_size else self._size\n t = np.random.choice(self._buffer[:self._size], size=n_sample, replace=False)\n return [np.asarray(e) for e in zip(*t)]\n\n def get_all(self) -> List[np.ndarray]:\n return [np.asarray(e) for e in zip(*self._buffer[:self._size])]\n\n def update_rb_after_add(self) -> NoReturn:\n self._data_pointer += 1\n if self._data_pointer >= self.capacity: # replace when exceed the capacity\n self._data_pointer = 0\n if self._size < self.capacity:\n self._size += 1\n\n @property\n def is_full(self) -> bool:\n return self._size == self.capacity\n\n @property\n def size(self) -> int:\n return self._size\n\n @property\n def is_lg_batch_size(self) -> bool:\n return self._size > self.batch_size\n\n @property\n def show_rb(self) -> NoReturn:\n print('RB size: ', self._size)\n print('RB capacity: ', self.capacity)\n print(self._buffer[:, np.newaxis])\n\n\nclass PrioritizedExperienceReplay(ReplayBuffer):\n '''\n This PER will introduce some bias, 'cause when the experience with the minimum probability has been collected, the min_p that be updated may become inaccuracy.\n '''\n\n def __init__(self,\n batch_size: int,\n capacity: int,\n max_train_step: int,\n alpha: float,\n beta: float,\n epsilon: float,\n global_v: bool):\n '''\n inputs:\n max_train_step: use for calculating the decay interval of beta\n alpha: control sampling rule, alpha -> 0 means uniform sampling, alpha -> 1 means complete td_error sampling\n beta: control importance sampling ratio, beta -> 0 means no IS, beta -> 1 means complete IS.\n epsilon: a small positive number that prevents td-error of 0 from never being replayed.\n global_v: whether using the global\n '''\n assert epsilon > 0, 'epsilon must larger than zero'\n super().__init__(batch_size, capacity)\n self.tree = Sum_Tree(capacity)\n self.alpha = alpha\n self.beta = self.init_beta = beta\n self.beta_interval = (1. - beta) / max_train_step\n self.epsilon = epsilon\n self.IS_w = 1 # weights of variables by using Importance Sampling\n self.global_v = global_v\n self.reset()\n\n def reset(self):\n self.tree.reset()\n super().reset()\n self.beta = self.init_beta\n self.min_p = sys.maxsize\n self.max_p = np.power(self.epsilon, self.alpha)\n\n def add(self, *args) -> NoReturn:\n '''\n input: [ss, visual_ss, as, rs, s_s, visual_s_s, dones]\n '''\n self.add_batch(list(zip(*args)))\n # [self._store_op(data) for data in zip(*args)]\n\n def _store_op(self, data: Union[List, np.ndarray]) -> NoReturn:\n self.tree.add(self.max_p, data)\n if self._size < self.capacity:\n self._size += 1\n\n def add_batch(self, data: List) -> NoReturn:\n data = list(data)\n num = len(data)\n self.tree.add_batch(np.full(num, self.max_p), data)\n self._size = min(self._size + num, self.capacity)\n\n def apex_add_batch(self, td_error, *args):\n data = list(zip(*args))\n num = len(data)\n prios = np.power(np.abs(td_error) + self.epsilon, self.alpha)\n self.tree.add_batch(prios, data)\n self._size = min(self._size + num, self.capacity)\n\n def sample(self, return_index: bool = False) -> Union[List, Tuple]:\n '''\n output: weights, [ss, visual_ss, as, rs, s_s, visual_s_s, dones]\n '''\n n_sample = self.batch_size if self.is_lg_batch_size else self._size\n all_intervals = np.linspace(0, self.tree.total, n_sample + 1)\n ps = np.random.uniform(all_intervals[:-1], all_intervals[1:])\n idxs, data_indx, p, data = self.tree.get_batch_parallel(ps)\n self.last_indexs = idxs\n _min_p = self.min_p if self.global_v and self.min_p < sys.maxsize else p.min()\n self.IS_w = np.power(_min_p / p, self.beta)\n if return_index:\n return data, idxs\n else:\n return data\n\n def get_all(self, return_index: bool = False):\n idxs, data_indx, p, data = self.tree.get_all()\n self.last_indexs = idxs\n _min_p = self.min_p if self.global_v and self.min_p < sys.maxsize else p.min()\n self.IS_w = np.power(_min_p / p, self.beta)\n if return_index:\n return data, idxs\n else:\n return data\n\n def get_all_exps(self):\n return self.tree.get_all_exps()\n\n @property\n def is_lg_batch_size(self) -> bool:\n return self._size > self.batch_size\n\n def update(self,\n priority: Union[List, np.ndarray],\n index: Optional[Union[List, np.ndarray]] = None) -> NoReturn:\n '''\n input: priorities\n '''\n assert hasattr(priority, '__len__'), 'priority must have attribute of len()'\n idxs = index if index is not None else self.last_indexs\n assert len(priority) == len(idxs), 'length between priority and last_indexs must equal'\n self.beta = min(self.beta + self.beta_interval, 1.)\n priority = np.power(np.abs(priority) + self.epsilon, self.alpha)\n self.min_p = min(self.min_p, priority.min())\n self.max_p = max(self.max_p, priority.max())\n self.tree._updatetree_batch(idxs, priority)\n # [self.tree._updatetree(idx, p) for idx, p in zip(idxs, priority)]\n\n def get_IS_w(self) -> np.ndarray:\n return self.IS_w\n\n @property\n def size(self) -> int:\n return self._size\n\n\nclass NStepWrapper:\n def __init__(self,\n buffer: ReplayBuffer,\n gamma: float,\n n: int,\n agents_num: int):\n '''\n gamma: discount factor\n n: n step\n agents_num: batch experience\n '''\n self.buffer = buffer\n self.n = n\n self.gamma = gamma\n self.agents_num = agents_num\n self.queue = [[] for _ in range(agents_num)]\n\n def add(self, *args) -> NoReturn:\n '''\n change [s, s],[a, a],[r, r] to [s, a, r],[s, a, r] and store every item in it.\n '''\n [self._per_store(i, list(data)) for i, data in enumerate(zip(*args))]\n\n def _per_store(self, i: int, data: List) -> NoReturn:\n '''\n data:\n 0 s -7\n 1 visual_s -6\n 2 a -5\n 3 r -4\n 4 s_ -3\n 5 visual_s_ -2\n 6 done -1\n '''\n q = self.queue[i]\n if len(q) == 0: # 如果Nstep临时经验池为空,就直接添加\n q.append(data)\n return\n if (q[-1][4] != data[0]).any() or (q[-1][5] != data[1]).any(): # 如果截断了,非常规done,把Nstep临时经验池中已存在的经验都存进去,临时经验池清空\n if len(q) == self.n:\n self._store_op(q.pop(0))\n else:\n q.clear() # 保证经验池中不存在不足N长度的序列,有done的除外,因为(1-done)为0,导致gamma的次方计算不准确也没有关系。\n q.append(data)\n return\n\n if len(q) == self.n: # 如果Nstep临时经验池满了,就把最早的一条经验存到经验池\n self._store_op(q.pop(0))\n _len = len(q)\n for j in range(_len): # 然后再存入一条最新的经验到Nstep临时经验池\n q[j][3] += data[3] * (self.gamma ** (_len - j))\n q[j][4:] = data[4:]\n q.append(data)\n if data[6]: # done or not # 如果新数据是done,就清空临时经验池\n while q: # (1-done)会清零不正确的n-step\n self._store_op(q.pop())\n\n def __getattr__(self, name):\n return getattr(self.buffer, name)\n\n\nclass NStepExperienceReplay(NStepWrapper):\n '''\n Replay Buffer + NStep\n [s, visual_s, a, r, s_, visual_s_, done] must be this format.\n '''\n\n def __init__(self,\n batch_size: int,\n capacity: int,\n gamma: float,\n n: int,\n agents_num: int):\n super().__init__(\n buffer=ExperienceReplay(batch_size, capacity),\n gamma=gamma, n=n, agents_num=agents_num\n )\n\n\nclass NStepPrioritizedExperienceReplay(NStepWrapper):\n '''\n PER + NStep\n [s, visual_s, a, r, s_, visual_s_, done] must be this format.\n '''\n\n def __init__(self,\n batch_size: int,\n capacity: int,\n max_train_step: int,\n alpha: float,\n beta: float,\n epsilon: float,\n global_v: bool,\n gamma: float,\n n: int,\n agents_num: int):\n super().__init__(\n buffer=PrioritizedExperienceReplay(batch_size, capacity, max_train_step, alpha, beta, epsilon, global_v),\n gamma=gamma, n=n, agents_num=agents_num\n )\n\n\nclass EpisodeExperienceReplay(ReplayBuffer):\n\n def __init__(self,\n batch_size: int,\n capacity: int,\n agents_num: int,\n burn_in_time_step: int,\n train_time_step: int):\n super().__init__(batch_size, capacity)\n self.agents_num = agents_num\n self.burn_in_time_step = burn_in_time_step\n self.train_time_step = train_time_step\n self.timestep = burn_in_time_step + train_time_step\n self.queue = [[] for _ in range(agents_num)]\n self._data_pointer = 0\n self._buffer = np.empty(capacity, dtype=object)\n\n def add(self, *args) -> NoReturn:\n '''\n change [s, s],[a, a],[r, r] to [s, a, r],[s, a, r] and store every item in it.\n '''\n [self._per_store(i, list(data)) for i, data in enumerate(zip(*args))]\n\n def _per_store(self, i: int, data: List) -> NoReturn:\n '''\n data:\n 0 s -7\n 1 visual_s -6\n 2 a -5\n 3 r -4\n 4 s_ -3\n 5 visual_s_ -2\n 6 done -1\n 7 other -\n '''\n q = self.queue[i]\n if len(q) == 0:\n q.append(data)\n return\n if (q[-1][4] != data[0]).any() or (q[-1][5] != data[1]).any():\n self._store_op(q.copy())\n q.clear()\n q.append(data)\n return\n if data[6]:\n q.append(data)\n self._store_op(q.copy())\n q.clear()\n return\n q.append(data)\n\n def _store_op(self, data: List) -> NoReturn:\n self._buffer[self._data_pointer] = data\n self.update_rb_after_add()\n\n def update_rb_after_add(self) -> NoReturn:\n self._data_pointer += 1\n if self._data_pointer >= self.capacity: # replace when exceed the capacity\n self._data_pointer = 0\n if self._size < self.capacity:\n self._size += 1\n\n def sample(self) -> List[List[Union[np.ndarray, tf.Tensor]]]:\n '''\n data:\n 0 s -7\n 1 visual_s -6\n 2 a -5\n 3 r -4\n 4 s_ -3\n 5 visual_s_ -2\n 6 done -1\n 7 other -\n [B, (s, a, r, s', d)] => [B*time_step, N]\n '''\n n_sample = self.batch_size if self.is_lg_batch_size else self._size\n trajs = np.random.choice(self._buffer[:self._size], size=n_sample, replace=False) # 选n_sample条轨迹\n experience_type_num = len(trajs[0][0]) # 获取经验的类型种类 , 如 <s, a, r> 即为3\n\n def truncate(traj):\n idx = np.random.randint(max(1, len(traj) - self.timestep + 1)) # [min, max)\n return traj[idx:idx + self.timestep]\n\n truncated_trajs = list(map(truncate, trajs))\n\n data_list = [[] for _ in range(experience_type_num)] # [s, visual_s, a, r, s_, visual_s_, done, others...]\n for traj in truncated_trajs: # traj即为1条轨迹 [(s,a,r,s_,done), (s,a,r,s_,done),...]\n data = [exps for exps in zip(*traj)] # s [T, N], s_ [T, N]\n [dl.append(exps) for dl, exps in zip(data_list, data)] # [B, T, NStep]\n\n def f(v, l): # [B, T, N]\n return lambda x: tf.keras.preprocessing.sequence.pad_sequences(x, padding='pre', dtype='float32', value=v, maxlen=l, truncating='pre')\n data_list[:6] = map(f(v=0., l=self.timestep), data_list[:6]) # [B, T, N]\n data_list[6] = f(v=1., l=self.timestep)(data_list[6]) # done [B, T, N]\n if experience_type_num > 7:\n data_list[7:] = map(f(v=0., l=self.timestep), data_list[7:]) # padding 后的 [B, T, N]\n\n self.burn_in_states = list(map(lambda x: x[:, :self.burn_in_time_step], data_list[:2]))\n data_list = list(map(lambda x: x[:, self.burn_in_time_step:], data_list)) # s: [B, T, N]\n\n data_list[2] = data_list[2].reshape(n_sample * self.train_time_step, -1) # a: [B*T, N]\n data_list[3] = data_list[3].reshape(-1, 1) # a: [B*T, 1]\n data_list[6:] = map(lambda x: x.reshape(-1, x.shape[-1]), data_list[6:])\n return data_list\n\n def get_burn_in_states(self) -> Tuple:\n s, visual_s = self.burn_in_states\n return s, visual_s\n\n @property\n def is_full(self) -> bool:\n return self._size == self.capacity\n\n @property\n def size(self) -> int:\n return self._size\n\n @property\n def is_lg_batch_size(self) -> bool:\n return self._size > self.batch_size\n\n @property\n def show_rb(self) -> NoReturn:\n print('RB size: ', self._size)\n print('RB capacity: ', self.capacity)\n print(self._buffer)\n\n\nif __name__ == \"__main__\":\n buff = EpisodeExperienceReplay(4, 10, 2)\n\n s = [np.zeros(2), np.ones(2)]\n visual_s = [np.zeros(2), np.ones(2)]\n a = [np.zeros(2), np.ones(2)]\n r = [np.array([1]), np.array([1])]\n s_ = [np.zeros(2), np.ones(2)]\n visual_s_ = [np.zeros(2), np.ones(2)]\n done = [np.array([False]), np.array([False])]\n done_ = [np.array([True]), np.array([True])]\n done1 = [np.array([False]), np.array([True])]\n done2 = [np.array([True]), np.array([False])]\n\n buff.add(s, visual_s, a, r, s_, visual_s_, done)\n buff.add(s, visual_s, a, r, s_, visual_s_, done)\n buff.add(s, visual_s, a, r, s_, visual_s_, done)\n buff.add(s, visual_s, a, r, s_, visual_s_, done1) # done 1, 4\n buff.add(s, visual_s, a, r, s_, visual_s_, done2) # done 2, 5\n buff.add(s, visual_s, a, r, s_, visual_s_, done)\n buff.add(s, visual_s, a, r, s_, visual_s_, done)\n buff.add(s, visual_s, a, r, s_, visual_s_, done_) # done 3, 4 done 4, 3\n # print(buff._buffer[1])\n # buff.show_rb\n # buff.sample()\n" ]
[ [ "tensorflow.split", "tensorflow.concat", "tensorflow.shape" ], [ "numpy.abs", "numpy.linspace", "numpy.power", "numpy.random.choice", "numpy.asarray", "numpy.ones", "numpy.full", "numpy.random.uniform", "tensorflow.keras.preprocessing.sequence.pad_sequences", "numpy.array", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.2", "2.3", "2.4", "2.5", "2.6" ] } ]
EelcoHoogendoorn/Numpy_arraysetops_EP
[ "84dc8114bf8a79c3acb3f7f59128247b9fc97243" ]
[ "numpy_indexed/grouping.py" ]
[ "\"\"\"grouping module\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom builtins import *\n\nimport itertools\n\nimport numpy as np\nfrom numpy_indexed.index import as_index\nimport numpy_indexed as npi\n\n__author__ = \"Eelco Hoogendoorn\"\n__license__ = \"LGPL\"\n__email__ = \"[email protected]\"\n\n\nclass GroupBy(object):\n \"\"\"\n GroupBy class\n\n contains an index of keys, and extends the index functionality with grouping-specific functionality\n \"\"\"\n\n def __init__(self, keys, axis=0):\n \"\"\"\n Parameters\n ----------\n keys : indexable object\n sequence of keys to group by\n axis : int, optional\n axis to regard as the key-sequence, in case keys is multi-dimensional\n\n See Also\n --------\n numpy_indexed.as_index : for information regarding the casting rules to a valid Index object\n \"\"\"\n self.index = as_index(keys, axis)\n\n #forward interesting/'public' index properties\n @property\n def unique(self):\n \"\"\"unique keys\"\"\"\n return self.index.unique\n @property\n def count(self):\n \"\"\"count of each unique key\"\"\"\n return self.index.count\n @property\n def inverse(self):\n \"\"\"mapping such that unique[inverse]==keys\"\"\"\n return self.index.inverse\n @property\n def groups(self):\n \"\"\"int, number of groups formed by the keys\"\"\"\n return self.index.groups\n\n #some different methods of chopping up a set of values by key\n def split_iterable_as_iterable(self, values):\n \"\"\"Group iterable into iterables, in the order of the keys\n\n Parameters\n ----------\n values : iterable of length equal to keys\n iterable of values to be grouped\n\n Yields\n ------\n iterable of items in values\n\n Notes\n -----\n Memory consumption depends on the amount of sorting required\n Worst case, if index.sorter[-1] = 0, we need to consume the entire value iterable,\n before we can start yielding any output\n But to the extent that the keys are already sorted, the grouping is lazy\n \"\"\"\n values = iter(enumerate(values))\n cache = dict()\n def get_value(ti):\n try:\n return cache.pop(ti)\n except:\n while True:\n i, v = next(values)\n if i==ti:\n return v\n cache[i] = v\n s = iter(self.index.sorter)\n for c in self.count:\n yield (get_value(i) for i in itertools.islice(s, int(c)))\n\n def split_iterable_as_unordered_iterable(self, values):\n \"\"\"Group iterable into iterables, without regard for the ordering of self.index.unique\n key-group tuples are yielded as soon as they are complete\n\n Parameters\n ----------\n values : iterable of length equal to keys\n iterable of values to be grouped\n\n Yields\n ------\n tuple of key, and a list of corresponding items in values\n\n Notes\n -----\n This approach is lazy, insofar as grouped values are close in their iterable\n \"\"\"\n from collections import defaultdict\n cache = defaultdict(list)\n count = self.count\n unique = self.unique\n key = (lambda i: unique[i]) if isinstance(unique, np.ndarray) else (lambda i: tuple(c[i] for c in unique))\n for i,v in zip(self.inverse, values):\n cache[i].append(v)\n if len(cache[i]) == count[i]:\n yield key(i), cache.pop(i)\n\n def split_sequence_as_iterable(self, values):\n \"\"\"Group sequence into iterables\n\n Parameters\n ----------\n values : iterable of length equal to keys\n iterable of values to be grouped\n\n Yields\n ------\n iterable of items in values\n\n Notes\n -----\n This is the preferred method if values has random access, but we dont want it completely in memory.\n Like a big memory mapped file, for instance\n \"\"\"\n print(self.count)\n s = iter(self.index.sorter)\n for c in self.count:\n yield (values[i] for i in itertools.islice(s, int(c)))\n\n def split_array_as_array(self, values):\n \"\"\"Group ndarray into ndarray by means of reshaping\n\n Parameters\n ----------\n values : ndarray_like, [index.size, ...]\n\n Returns\n -------\n ndarray, [groups, group_size, ...]\n values grouped by key\n\n Raises\n ------\n AssertionError\n This operation is only possible if index.uniform==True\n \"\"\"\n if not self.index.uniform:\n raise ValueError(\"Array can only be split as array if all groups have the same size\")\n values = np.asarray(values)\n values = values[self.index.sorter]\n return values.reshape(self.groups, -1, *values.shape[1:])\n\n def split_array_as_list(self, values):\n \"\"\"Group values as a list of arrays, or a jagged-array\n\n Parameters\n ----------\n values : ndarray, [keys, ...]\n\n Returns\n -------\n list of length self.groups of ndarray, [key_count, ...]\n \"\"\"\n values = np.asarray(values)\n values = values[self.index.sorter]\n return np.split(values, self.index.slices[1:-1], axis=0)\n\n def split(self, values):\n \"\"\"some sensible defaults\"\"\"\n try:\n return self.split_array_as_array(values)\n except:\n # FIXME: change to iter in python 3?\n return self.split_array_as_list(values)\n\n def __call__(self, values):\n \"\"\"not sure how i feel about this. explicit is better than implict?\"\"\"\n return self.unique, self.split(values)\n\n\n # ufunc based reduction methods. should they return unique keys by default?\n def reduce(self, values, operator=np.add, axis=0, dtype=None):\n \"\"\"Reduce the values over identical key groups, using the given ufunc\n reduction is over the first axis, which should have elements corresponding to the keys\n all other axes are treated indepenently for the sake of this reduction\n\n Parameters\n ----------\n values : ndarray, [keys, ...]\n values to perform reduction over\n operator : numpy.ufunc\n a numpy ufunc, such as np.add or np.sum\n axis : int, optional\n the axis to reduce over\n dtype : output dtype\n\n Returns\n -------\n ndarray, [groups, ...]\n values reduced by operator over the key-groups\n \"\"\"\n values = np.take(values, self.index.sorter, axis=axis)\n return operator.reduceat(values, self.index.start, axis=axis, dtype=dtype)\n\n\n def sum(self, values, axis=0, dtype=None):\n \"\"\"compute the sum over each group\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to sum per group\n axis : int, optional\n alternative reduction axis for values\n dtype : output dtype\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n values = np.asarray(values)\n return self.unique, self.reduce(values, axis=axis, dtype=dtype)\n\n def prod(self, values, axis=0, dtype=None):\n \"\"\"compute the product over each group\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to multiply per group\n axis : int, optional\n alternative reduction axis for values\n dtype : output dtype\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n values = np.asarray(values)\n return self.unique, self.reduce(values, axis=axis, dtype=dtype, operator=np.multiply)\n\n def mean(self, values, axis=0, weights=None, dtype=None):\n \"\"\"compute the mean over each group\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to take average of per group\n axis : int, optional\n alternative reduction axis for values\n weights : ndarray, [keys, ...], optional\n weight to use for each value\n dtype : output dtype\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n values = np.asarray(values)\n if weights is None:\n result = self.reduce(values, axis=axis, dtype=dtype)\n shape = [1] * values.ndim\n shape[axis] = self.groups\n weights = self.count.reshape(shape)\n else:\n weights = np.asarray(weights)\n result = self.reduce(values * weights, axis=axis, dtype=dtype)\n weights = self.reduce(weights, axis=axis, dtype=dtype)\n return self.unique, result / weights\n\n def var(self, values, axis=0, weights=None, dtype=None):\n \"\"\"compute the variance over each group\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to take variance of per group\n axis : int, optional\n alternative reduction axis for values\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n values = np.asarray(values)\n unique, mean = self.mean(values, axis, weights, dtype)\n err = values - mean.take(self.inverse, axis)\n\n if weights is None:\n shape = [1] * values.ndim\n shape[axis] = self.groups\n group_weights = self.count.reshape(shape)\n var = self.reduce(err ** 2, axis=axis, dtype=dtype)\n else:\n weights = np.asarray(weights)\n group_weights = self.reduce(weights, axis=axis, dtype=dtype)\n var = self.reduce(weights * err ** 2, axis=axis, dtype=dtype)\n\n return unique, var / group_weights\n\n def std(self, values, axis=0, weights=None, dtype=None):\n \"\"\"standard deviation over each group\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to take standard deviation of per group\n axis : int, optional\n alternative reduction axis for values\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n unique, var = self.var(values, axis, weights, dtype)\n return unique, np.sqrt(var)\n\n def median(self, values, axis=0, average=True):\n \"\"\"compute the median value over each group.\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to compute the median of per group\n axis : int, optional\n alternative reduction axis for values\n average : bool, optional\n when average is true, the average of the two central values is taken for groups with an even key-count\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n mid_2 = self.index.start + self.index.stop\n hi = (mid_2 ) // 2\n lo = (mid_2 - 1) // 2\n\n #need this indirection for lex-index compatibility\n sorted_group_rank_per_key = self.index.sorted_group_rank_per_key\n\n def median1d(slc):\n #place values at correct keys; preconditions the upcoming lexsort\n slc = slc[self.index.sorter]\n #refine value sorting within each keygroup\n sorter = np.lexsort((slc, sorted_group_rank_per_key))\n slc = slc[sorter]\n return (slc[lo]+slc[hi]) / 2 if average else slc[hi]\n\n values = np.asarray(values)\n if values.ndim>1: #is trying to skip apply_along_axis somewhat premature optimization?\n values = np.apply_along_axis(median1d, axis, values)\n else:\n values = median1d(values)\n return self.unique, values\n\n def mode(self, values, weights=None):\n \"\"\"compute the mode within each group.\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to compute the mode of per group\n weights : array_like, [keys], float, optional\n optional weight associated with each entry in values\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n if weights is None:\n unique, weights = npi.count((self.index.sorted_group_rank_per_key, values))\n else:\n unique, weights = npi.group_by((self.index.sorted_group_rank_per_key, values)).sum(weights)\n\n x, bin = npi.group_by(unique[0]).argmax(weights)\n return x, unique[1][bin]\n\n def min(self, values, axis=0):\n \"\"\"return the minimum within each group\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to take minimum of per group\n axis : int, optional\n alternative reduction axis for values\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n values = np.asarray(values)\n return self.unique, self.reduce(values, np.minimum, axis)\n\n def max(self, values, axis=0):\n \"\"\"return the maximum within each group\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to take maximum of per group\n axis : int, optional\n alternative reduction axis for values\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n values = np.asarray(values)\n return self.unique, self.reduce(values, np.maximum, axis)\n\n def first(self, values, axis=0):\n \"\"\"return values at first occurance of its associated key\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to pick the first value of per group\n axis : int, optional\n alternative reduction axis for values\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n values = np.asarray(values)\n return self.unique, np.take(values, self.index.sorter[self.index.start], axis)\n\n def last(self, values, axis=0):\n \"\"\"return values at last occurance of its associated key\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to pick the last value of per group\n axis : int, optional\n alternative reduction axis for values\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...]\n value array, reduced over groups\n \"\"\"\n values = np.asarray(values)\n return self.unique, np.take(values, self.index.sorter[self.index.stop-1], axis)\n\n def any(self, values, axis=0):\n \"\"\"compute if any item evaluates to true in each group\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to take boolean predicate over per group\n axis : int, optional\n alternative reduction axis for values\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...], np.bool\n value array, reduced over groups\n \"\"\"\n values = np.asarray(values)\n if not values.dtype == np.bool:\n values = values != 0\n return self.unique, self.reduce(values, axis=axis) > 0\n\n def all(self, values, axis=0):\n \"\"\"compute if all items evaluates to true in each group\n\n Parameters\n ----------\n values : array_like, [keys, ...]\n values to take boolean predicate over per group\n axis : int, optional\n alternative reduction axis for values\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n reduced : ndarray, [groups, ...], np.bool\n value array, reduced over groups\n \"\"\"\n values = np.asarray(values)\n return self.unique, self.reduce(values, axis=axis, operator=np.multiply) != 0\n\n def argmin(self, values):\n \"\"\"return the index into values corresponding to the minimum value of the group\n\n Parameters\n ----------\n values : array_like, [keys]\n values to pick the argmin of per group\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n argmin : ndarray, [groups]\n index into value array, representing the argmin per group\n \"\"\"\n keys, minima = self.min(values)\n minima = minima[self.inverse]\n # select the first occurence of the minimum in each group\n index = as_index((self.inverse, values == minima))\n return keys, index.sorter[index.start[-self.groups:]]\n\n def argmax(self, values):\n \"\"\"return the index into values corresponding to the maximum value of the group\n\n Parameters\n ----------\n values : array_like, [keys]\n values to pick the argmax of per group\n\n Returns\n -------\n unique: ndarray, [groups]\n unique keys\n argmax : ndarray, [groups]\n index into value array, representing the argmax per group\n \"\"\"\n keys, maxima = self.max(values)\n maxima = maxima[self.inverse]\n # select the first occurence of the maximum in each group\n index = as_index((self.inverse, values == maxima))\n return keys, index.sorter[index.start[-self.groups:]]\n\n #implement iter interface? could simply do zip( group_by(keys)(values)), no?\n\n\ndef group_by(keys, values=None, reduction=None, axis=0):\n \"\"\"construct a grouping object on the given keys, optionally performing the given reduction on the given values\n\n Parameters\n ----------\n keys : indexable object\n keys to group by\n values : array_like, optional\n sequence of values, of the same length as keys\n if a reduction function is provided, the given values are reduced by key\n if no reduction is provided, the given values are grouped and split by key\n reduction : lambda, optional\n reduction function to apply to the values in each group\n axis : int, optional\n axis to regard as the key-sequence, in case keys is multi-dimensional\n\n Returns\n -------\n iterable\n if values is None, a GroupBy object of the given keys object\n if reduction is None, an tuple of a sequence of unique keys and a sequence of grouped values\n else, a sequence of tuples of unique keys and reductions of values over that key-group\n\n See Also\n --------\n numpy_indexed.as_index : for information regarding the casting rules to a valid Index object\n \"\"\"\n g = GroupBy(keys, axis)\n if values is None:\n return g\n groups = g.split(values)\n if reduction is None:\n return g.unique, groups\n return [(key, reduction(group)) for key, group in zip(g.unique, groups)]\n\n\n__all__ = ['group_by']\n" ]
[ [ "numpy.split", "numpy.take", "numpy.sqrt", "numpy.asarray", "numpy.lexsort", "numpy.apply_along_axis" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
eddylamhw/trAIner24
[ "ac7cf1b95a2ecdfc44d11451984b016524ed7657" ]
[ "utils/lib_classifier.py" ]
[ "'''\nThis script includes:\n\n1. ClassifierOfflineTrain\n This is for offline training. The input data are the processed features.\n2. class ClassifierOnlineTest(object)\n This is for online testing. The input data are the raw skeletons.\n It uses FeatureGenerator to extract features,\n and then use ClassifierOfflineTrain to recognize the action.\n Notice, this model is only for recognizing the action of one person.\n \nTODO: Add more comments to this function.\n'''\n\nimport numpy as np\nimport sys\nimport os\nimport pickle\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom collections import deque\nimport cv2\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.datasets import make_moons, make_circles, make_classification\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom sklearn.decomposition import PCA\n\nif True:\n import sys\n import os\n ROOT = os.path.dirname(os.path.abspath(__file__))+\"/../\"\n sys.path.append(ROOT)\n\n from utils.lib_feature_proc import FeatureGenerator\n\n\n# -- Settings\nNUM_FEATURES_FROM_PCA = 50\n\n# -- Classes\n\n\nclass ClassifierOfflineTrain(object):\n ''' The classifer for offline training.\n The input features to this classifier are already \n processed by `class FeatureGenerator`.\n '''\n\n def __init__(self):\n self._init_all_models()\n\n # self.clf = self._choose_model(\"Nearest Neighbors\")\n # self.clf = self._choose_model(\"Linear SVM\")\n # self.clf = self._choose_model(\"RBF SVM\")\n # self.clf = self._choose_model(\"Gaussian Process\")\n # self.clf = self._choose_model(\"Decision Tree\")\n # self.clf = self._choose_model(\"Random Forest\")\n self.clf = self._choose_model(\"Neural Net\")\n\n def predict(self, X):\n ''' Predict the class index of the feature X '''\n Y_predict = self.clf.predict(self.pca.transform(X))\n return Y_predict\n\n def predict_and_evaluate(self, te_X, te_Y):\n ''' Test model on test set and obtain accuracy '''\n te_Y_predict = self.predict(te_X)\n N = len(te_Y)\n n = sum(te_Y_predict == te_Y)\n accu = n / N\n return accu, te_Y_predict\n\n def train(self, X, Y):\n ''' Train model. The result is saved into self.clf '''\n n_components = min(NUM_FEATURES_FROM_PCA, X.shape[1])\n self.pca = PCA(n_components=n_components, whiten=True)\n self.pca.fit(X)\n # print(\"Sum eig values:\", np.sum(self.pca.singular_values_))\n print(\"Sum eig values:\", np.sum(self.pca.explained_variance_ratio_))\n X_new = self.pca.transform(X)\n print(\"After PCA, X.shape = \", X_new.shape)\n self.clf.fit(X_new, Y)\n\n def _choose_model(self, name):\n self.model_name = name\n idx = self.names.index(name)\n return self.classifiers[idx]\n\n def _init_all_models(self):\n self.names = [\"Nearest Neighbors\", \"Linear SVM\", \"RBF SVM\", \"Gaussian Process\",\n \"Decision Tree\", \"Random Forest\", \"Neural Net\", \"AdaBoost\",\n \"Naive Bayes\", \"QDA\"]\n self.model_name = None\n self.classifiers = [\n KNeighborsClassifier(5),\n SVC(kernel=\"linear\", C=10.0),\n SVC(gamma=0.01, C=1.0, verbose=True),\n GaussianProcessClassifier(1.0 * RBF(1.0)),\n DecisionTreeClassifier(max_depth=5),\n RandomForestClassifier(\n max_depth=30, n_estimators=100, max_features=\"auto\"),\n MLPClassifier((20, 30, 40)), # Neural Net\n AdaBoostClassifier(),\n GaussianNB(),\n QuadraticDiscriminantAnalysis()]\n\n def _predict_proba(self, X):\n ''' Predict the probability of feature X belonging to each of the class Y[i] '''\n Y_probs = self.clf.predict_proba(self.pca.transform(X))\n return Y_probs # np.array with a length of len(classes)\n\n\nclass ClassifierOnlineTest(object):\n ''' Classifier for online inference.\n The input data to this classifier is the raw skeleton data, so they\n are processed by `class FeatureGenerator` before sending to the\n self.model trained by `class ClassifierOfflineTrain`. \n '''\n\n def __init__(self, model_path, action_labels, window_size, human_id=0):\n\n # -- Settings\n self.human_id = human_id\n with open(model_path, 'rb') as f:\n self.model = pickle.load(f)\n if self.model is None:\n print(\"my Error: failed to load model\")\n assert False\n self.action_labels = action_labels\n self.THRESHOLD_SCORE_FOR_DISP = 0.5\n\n # -- Time serials storage\n self.feature_generator = FeatureGenerator(window_size)\n self.reset()\n\n def reset(self):\n self.feature_generator.reset()\n self.scores_hist = deque()\n self.scores = None\n\n def predict(self, skeleton):\n ''' Predict the class (string) of the input raw skeleton '''\n LABEL_UNKNOWN = \"\"\n is_features_good, features = self.feature_generator.add_cur_skeleton(\n skeleton)\n\n if is_features_good:\n # convert to 2d array\n features = features.reshape(-1, features.shape[0])\n\n curr_scores = self.model._predict_proba(features)[0]\n self.scores = self.smooth_scores(curr_scores)\n\n if self.scores.max() < self.THRESHOLD_SCORE_FOR_DISP: # If lower than threshold, bad\n prediced_label = LABEL_UNKNOWN\n else:\n predicted_idx = self.scores.argmax()\n prediced_label = self.action_labels[predicted_idx]\n else:\n prediced_label = LABEL_UNKNOWN\n return prediced_label\n\n def smooth_scores(self, curr_scores):\n ''' Smooth the current prediction score\n by taking the average with previous scores\n '''\n self.scores_hist.append(curr_scores)\n DEQUE_MAX_SIZE = 2\n if len(self.scores_hist) > DEQUE_MAX_SIZE:\n self.scores_hist.popleft()\n\n if 1: # Use sum\n score_sums = np.zeros((len(self.action_labels),))\n for score in self.scores_hist:\n score_sums += score\n score_sums /= len(self.scores_hist)\n print(\"\\nMean score:\\n\", score_sums)\n return score_sums\n\n else: # Use multiply\n score_mul = np.ones((len(self.action_labels),))\n for score in self.scores_hist:\n score_mul *= score\n return score_mul\n\n def draw_scores_onto_image(self, img_disp):\n if self.scores is None:\n return\n\n for i in range(len(self.action_labels)):\n\n FONT_SIZE = 0.6\n TXT_X = 20\n TXT_Y = 150 + i*30\n COLOR_INTENSITY = 255\n\n #if i == -1:\n # s = \"{}\".format(self.human_id)\n #else:\n #label = self.action_labels[i]\n #s = \"{:<5}: {:.2f}\".format(label, self.scores[i])\n #COLOR_INTENSITY *= (0.0 + 1.0 * self.scores[i])**0.5\n if i!=-1:\n label = self.action_labels[i]\n s = \"{:<5}: {:.2f}\".format(label, self.scores[i])\n COLOR_INTENSITY *= (0.0 + 1.0 * self.scores[i])**0.5\n\n\n cv2.putText(img_disp, text=s, org=(TXT_X, TXT_Y),\n fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=FONT_SIZE,\n color=(0, 0, int(COLOR_INTENSITY)), thickness=2)\n" ]
[ [ "sklearn.neural_network.MLPClassifier", "sklearn.naive_bayes.GaussianNB", "sklearn.ensemble.RandomForestClassifier", "sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis", "sklearn.neighbors.KNeighborsClassifier", "sklearn.tree.DecisionTreeClassifier", "sklearn.ensemble.AdaBoostClassifier", "sklearn.svm.SVC", "sklearn.gaussian_process.kernels.RBF", "sklearn.decomposition.PCA", "numpy.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tjcorona/PyFR
[ "a72b41580043bb001e5a9e6bb79a0e305d48e052", "a72b41580043bb001e5a9e6bb79a0e305d48e052" ]
[ "pyfr/writers/paraview.py", "pyfr/plugins/catalyst.py" ]
[ "# -*- coding: utf-8 -*-\n\n\"\"\"Converts .pyfr[m, s] files to a Paraview VTK UnstructuredGrid File\"\"\"\n\nfrom collections import defaultdict\nimport os\n\nimport numpy as np\n\nfrom pyfr.shapes import BaseShape\nfrom pyfr.util import subclass_where\nfrom pyfr.writers import BaseWriter\n\n\nclass ParaviewWriter(BaseWriter):\n # Supported file types and extensions\n name = 'paraview'\n extn = ['.vtu', '.pvtu']\n\n def __init__(self, args):\n super().__init__(args)\n\n self.dtype = np.dtype(args.precision).type\n self.divisor = args.divisor or self.cfg.getint('solver', 'order')\n\n def _get_npts_ncells_nnodes(self, mk):\n m_inf = self.mesh_inf[mk]\n\n # Get the shape and sub division classes\n shapecls = subclass_where(BaseShape, name=m_inf[0])\n subdvcls = subclass_where(BaseShapeSubDiv, name=m_inf[0])\n\n # Number of vis points\n npts = shapecls.nspts_from_order(self.divisor + 1)*m_inf[1][1]\n\n # Number of sub cells and nodes\n ncells = len(subdvcls.subcells(self.divisor))*m_inf[1][1]\n nnodes = len(subdvcls.subnodes(self.divisor))*m_inf[1][1]\n\n return npts, ncells, nnodes\n\n def _get_array_attrs(self, mk=None):\n dtype = 'Float32' if self.dtype == np.float32 else 'Float64'\n dsize = np.dtype(self.dtype).itemsize\n\n ndims = self.ndims\n vvars = self.elementscls.visvarmap[ndims]\n\n names = ['', 'connectivity', 'offsets', 'types']\n types = [dtype, 'Int32', 'Int32', 'UInt8']\n comps = ['3', '', '', '']\n\n for fname, varnames in vvars.items():\n names.append(fname.capitalize())\n types.append(dtype)\n comps.append(str(len(varnames)))\n\n # If a mesh has been given the compute the sizes\n if mk:\n npts, ncells, nnodes = self._get_npts_ncells_nnodes(mk)\n nb = npts*dsize\n\n sizes = [3*nb, 4*nnodes, 4*ncells, ncells]\n sizes.extend(len(varnames)*nb for varnames in vvars.values())\n\n return names, types, comps, sizes\n else:\n return names, types, comps\n\n def write_out(self):\n name, extn = os.path.splitext(self.outf)\n parallel = extn == '.pvtu'\n\n parts = defaultdict(list)\n for mk, sk in zip(self.mesh_inf, self.soln_inf):\n prt = mk.split('_')[-1]\n pfn = '{0}_{1}.vtu'.format(name, prt) if parallel else self.outf\n\n parts[pfn].append((mk, sk))\n\n write_s_to_fh = lambda s: fh.write(s.encode('utf-8'))\n\n for pfn, misil in parts.items():\n with open(pfn, 'wb') as fh:\n write_s_to_fh('<?xml version=\"1.0\" ?>\\n<VTKFile '\n 'byte_order=\"LittleEndian\" '\n 'type=\"UnstructuredGrid\" '\n 'version=\"0.1\">\\n<UnstructuredGrid>\\n')\n\n # Running byte-offset for appended data\n off = 0\n\n # Header\n for mk, sk in misil:\n off = self._write_serial_header(fh, mk, off)\n\n write_s_to_fh('</UnstructuredGrid>\\n'\n '<AppendedData encoding=\"raw\">\\n_')\n\n # Data\n for mk, sk in misil:\n self._write_data(fh, mk, sk)\n\n write_s_to_fh('\\n</AppendedData>\\n</VTKFile>')\n\n if parallel:\n with open(self.outf, 'wb') as fh:\n write_s_to_fh('<?xml version=\"1.0\" ?>\\n<VTKFile '\n 'byte_order=\"LittleEndian\" '\n 'type=\"PUnstructuredGrid\" '\n 'version=\"0.1\">\\n<PUnstructuredGrid>\\n')\n\n # Header\n self._write_parallel_header(fh)\n\n # Constitutent pieces\n for pfn in parts:\n write_s_to_fh('<Piece Source=\"{0}\"/>\\n'\n .format(os.path.basename(pfn)))\n\n write_s_to_fh('</PUnstructuredGrid>\\n</VTKFile>\\n')\n\n\n def _write_darray(self, array, vtuf, dtype):\n array = array.astype(dtype)\n\n np.uint32(array.nbytes).tofile(vtuf)\n array.tofile(vtuf)\n\n def _write_serial_header(self, vtuf, mk, off):\n names, types, comps, sizes = self._get_array_attrs(mk)\n npts, ncells = self._get_npts_ncells_nnodes(mk)[:2]\n\n write_s = lambda s: vtuf.write(s.encode('utf-8'))\n write_s('<Piece NumberOfPoints=\"{0}\" NumberOfCells=\"{1}\">\\n'\n .format(npts, ncells))\n write_s('<Points>\\n')\n\n # Write vtk DaraArray headers\n for i, (n, t, c, s) in enumerate(zip(names, types, comps, sizes)):\n write_s('<DataArray Name=\"{0}\" type=\"{1}\" '\n 'NumberOfComponents=\"{2}\" '\n 'format=\"appended\" offset=\"{3}\"/>\\n'\n .format(n, t, c, off))\n\n off += 4 + s\n\n # Write ends/starts of vtk file objects\n if i == 0:\n write_s('</Points>\\n<Cells>\\n')\n elif i == 3:\n write_s('</Cells>\\n<PointData>\\n')\n\n # Write end of vtk element data\n write_s('</PointData>\\n</Piece>\\n')\n\n # Return the current offset\n return off\n\n def _write_parallel_header(self, vtuf):\n names, types, comps = self._get_array_attrs()\n\n write_s = lambda s: vtuf.write(s.encode('utf-8'))\n write_s('<PPoints>\\n')\n\n # Write vtk DaraArray headers\n for i, (n, t, s) in enumerate(zip(names, types, comps)):\n write_s('<PDataArray Name=\"{0}\" type=\"{1}\" '\n 'NumberOfComponents=\"{2}\"/>\\n'.format(n, t, s))\n\n if i == 0:\n write_s('</PPoints>\\n<PCells>\\n')\n elif i == 3:\n write_s('</PCells>\\n<PPointData>\\n')\n\n write_s('</PPointData>\\n')\n\n def _write_data(self, vtuf, mk, sk):\n name = self.mesh_inf[mk][0]\n mesh = self.mesh[mk]\n soln = self.soln[sk]\n\n # Get the shape and sub division classes\n shapecls = subclass_where(BaseShape, name=name)\n subdvcls = subclass_where(BaseShapeSubDiv, name=name)\n\n # Dimensions\n nspts, neles = mesh.shape[:2]\n\n # Sub divison points inside of a standard element\n svpts = shapecls.std_ele(self.divisor)\n nsvpts = len(svpts)\n\n # Shape\n soln_b = shapecls(nspts, self.cfg)\n\n # Generate the operator matrices\n mesh_vtu_op = soln_b.sbasis.nodal_basis_at(svpts)\n soln_vtu_op = soln_b.ubasis.nodal_basis_at(svpts)\n\n # Calculate node locations of vtu elements\n vpts = np.dot(mesh_vtu_op, mesh.reshape(nspts, -1))\n vpts = vpts.reshape(nsvpts, -1, self.ndims)\n\n # Calculate solution at node locations of vtu elements\n vsol = np.dot(soln_vtu_op, soln.reshape(-1, self.nvars*neles))\n vsol = vsol.reshape(nsvpts, self.nvars, -1).swapaxes(0, 1)\n\n # Append dummy z dimension for points in 2D\n if self.ndims == 2:\n vpts = np.pad(vpts, [(0, 0), (0, 0), (0, 1)], 'constant')\n\n # Write element node locations to file\n self._write_darray(vpts.swapaxes(0, 1), vtuf, self.dtype)\n\n # Perform the sub division\n nodes = subdvcls.subnodes(self.divisor)\n\n # Prepare vtu cell arrays\n vtu_con = np.tile(nodes, (neles, 1))\n vtu_con += (np.arange(neles)*nsvpts)[:, None]\n\n # Generate offset into the connectivity array\n vtu_off = np.tile(subdvcls.subcelloffs(self.divisor), (neles, 1))\n vtu_off += (np.arange(neles)*len(nodes))[:, None]\n\n # Tile vtu cell type numbers\n vtu_typ = np.tile(subdvcls.subcelltypes(self.divisor), neles)\n\n # Write vtu node connectivity, connectivity offsets and cell types\n self._write_darray(vtu_con, vtuf, np.int32)\n self._write_darray(vtu_off, vtuf, np.int32)\n self._write_darray(vtu_typ, vtuf, np.uint8)\n\n # Primitive and visualisation variable maps\n privarmap = self.elementscls.privarmap[self.ndims]\n visvarmap = self.elementscls.visvarmap[self.ndims]\n\n # Convert from conservative to primitive variables\n vsol = np.array(self.elementscls.conv_to_pri(vsol, self.cfg))\n\n # Write out the various fields\n for vnames in visvarmap.values():\n ix = [privarmap.index(vn) for vn in vnames]\n\n self._write_darray(vsol[ix].T, vtuf, self.dtype)\n\n\nclass BaseShapeSubDiv(object):\n vtk_types = dict(tri=5, quad=9, tet=10, pyr=14, pri=13, hex=12)\n vtk_nodes = dict(tri=3, quad=4, tet=4, pyr=5, pri=6, hex=8)\n\n @classmethod\n def subcells(cls, n):\n pass\n\n @classmethod\n def subcelloffs(cls, n):\n return np.cumsum([cls.vtk_nodes[t] for t in cls.subcells(n)])\n\n @classmethod\n def subcelltypes(cls, n):\n return np.array([cls.vtk_types[t] for t in cls.subcells(n)])\n\n @classmethod\n def subnodes(cls, n):\n pass\n\n\nclass TensorProdShapeSubDiv(BaseShapeSubDiv):\n @classmethod\n def subnodes(cls, n):\n conbase = np.array([0, 1, n + 2, n + 1])\n\n # Extend quad mapping to hex mapping\n if cls.ndim == 3:\n conbase = np.hstack((conbase, conbase + (1 + n)**2))\n\n # Calculate offset of each subdivided element's nodes\n nodeoff = np.zeros((n,)*cls.ndim)\n for dim, off in enumerate(np.ix_(*(range(n),)*cls.ndim)):\n nodeoff += off*(n + 1)**dim\n\n # Tile standard element node ordering mapping, then apply offsets\n internal_con = np.tile(conbase, (n**cls.ndim, 1))\n internal_con += nodeoff.T.flatten()[:, None]\n\n return np.hstack(internal_con)\n\n\nclass QuadShapeSubDiv(TensorProdShapeSubDiv):\n name = 'quad'\n ndim = 2\n\n @classmethod\n def subcells(cls, n):\n return ['quad']*(n**2)\n\n\nclass HexShapeSubDiv(TensorProdShapeSubDiv):\n name = 'hex'\n ndim = 3\n\n @classmethod\n def subcells(cls, n):\n return ['hex']*(n**3)\n\n\nclass TriShapeSubDiv(BaseShapeSubDiv):\n name = 'tri'\n\n @classmethod\n def subcells(cls, n):\n return ['tri']*(n**2)\n\n @classmethod\n def subnodes(cls, n):\n conlst = []\n\n for row in range(n, 0, -1):\n # Lower and upper indices\n l = (n - row)*(n + row + 3) // 2\n u = l + row + 1\n\n # Base offsets\n off = [l, l + 1, u, u + 1, l + 1, u]\n\n # Generate current row\n subin = np.ravel(np.arange(row - 1)[..., None] + off)\n subex = [ix + row - 1 for ix in off[:3]]\n\n # Extent list\n conlst.extend([subin, subex])\n\n return np.hstack(conlst)\n\n\nclass TetShapeSubDiv(BaseShapeSubDiv):\n name = 'tet'\n\n @classmethod\n def subcells(cls, nsubdiv):\n return ['tet']*(nsubdiv**3)\n\n @classmethod\n def subnodes(cls, nsubdiv):\n conlst = []\n jump = 0\n\n for n in range(nsubdiv, 0, -1):\n for row in range(n, 0, -1):\n # Lower and upper indices\n l = (n - row)*(n + row + 3) // 2 + jump\n u = l + row + 1\n\n # Lower and upper for one row up\n ln = (n + 1)*(n + 2) // 2 + l - n + row\n un = ln + row\n\n rowm1 = np.arange(row - 1)[..., None]\n\n # Base offsets\n offs = [(l, l + 1, u, ln), (l + 1, u, ln, ln + 1),\n (u, u + 1, ln + 1, un), (u, ln, ln + 1, un),\n (l + 1, u, u+1, ln + 1), (u + 1, ln + 1, un, un + 1)]\n\n # Current row\n conlst.extend(rowm1 + off for off in offs[:-1])\n conlst.append(rowm1[:-1] + offs[-1])\n conlst.append([ix + row - 1 for ix in offs[0]])\n\n jump += (n + 1)*(n + 2) // 2\n\n return np.hstack(np.ravel(c) for c in conlst)\n\n\nclass PriShapeSubDiv(BaseShapeSubDiv):\n name = 'pri'\n\n @classmethod\n def subcells(cls, n):\n return ['pri']*(n**3)\n\n @classmethod\n def subnodes(cls, n):\n # Triangle connectivity\n tcon = TriShapeSubDiv.subnodes(n).reshape(-1, 3)\n\n # Layer these rows of triangles to define prisms\n loff = (n + 1)*(n + 2) // 2\n lcon = [[tcon + i*loff, tcon + (i + 1)*loff] for i in range(n)]\n\n return np.hstack(np.hstack(l).flat for l in lcon)\n\n\nclass PyrShapeSubDiv(BaseShapeSubDiv):\n name = 'pyr'\n\n @classmethod\n def subcells(cls, n):\n cells = []\n\n for i in range(n, 0, -1):\n cells += ['pyr']*(i**2 + (i - 1)**2)\n cells += ['tet']*(2*i*(i - 1))\n\n return cells\n\n @classmethod\n def subnodes(cls, nsubdiv):\n lcon = []\n\n # Quad connectivity\n qcon = [QuadShapeSubDiv.subnodes(n + 1).reshape(-1, 4)\n for n in range(nsubdiv)]\n\n # Simple functions\n def _row_in_quad(n, a=0, b=0):\n return np.array([(n*i + j, n*i + j + 1)\n for i in range(a, n + b)\n for j in range(n - 1)])\n\n def _col_in_quad(n, a=0, b=0):\n return np.array([(n*i + j, n*(i + 1) + j)\n for i in range(n - 1)\n for j in range(a, n + b)])\n\n u = 0\n for n in range(nsubdiv, 0, -1):\n l = u\n u += (n + 1)**2\n\n lower_quad = qcon[n - 1] + l\n upper_pts = np.arange(n**2) + u\n\n # First set of pyramids\n lcon.append([lower_quad, upper_pts])\n\n if n > 1:\n upper_quad = qcon[n - 2] + u\n lower_pts = np.hstack(range(k*(n + 1)+1, (k + 1)*n + k)\n for k in range(1, n)) + l\n\n # Second set of pyramids\n lcon.append([upper_quad[:, ::-1], lower_pts])\n\n lower_row = _row_in_quad(n + 1, 1, -1) + l\n lower_col = _col_in_quad(n + 1, 1, -1) + l\n\n upper_row = _row_in_quad(n) + u\n upper_col = _col_in_quad(n) + u\n\n # Tetrahedra\n lcon.append([lower_col, upper_row])\n lcon.append([lower_row[:, ::-1], upper_col])\n\n return np.hstack(np.column_stack(l).flat for l in lcon)\n", "# -*- coding: utf-8 -*-\n\nfrom ctypes import *\nfrom mpi4py import MPI\nimport numpy as np\nfrom pyfr.plugins.base import BasePlugin\nfrom pyfr.ctypesutil import load_library\nfrom pyfr.shapes import BaseShape\nfrom pyfr.util import proxylist, subclass_where\nimport os\n\n# Contains relevant data pertaining to all instances of a single cell type\nclass MeshDataForCellType(Structure):\n _fields_ = [\n ('nVerticesPerCell', c_int),\n ('nCells', c_int),\n\n ('vertices', c_void_p),\n\n ('nSubdividedCells', c_int),\n\n ('con', c_void_p),\n ('off', c_void_p),\n ('type', c_void_p)\n ]\n\nclass SolutionDataForCellType(Structure):\n _fields_ = [\n ('ldim', c_int),\n ('lsdim', c_int),\n ('soln', c_void_p)\n ]\n\nclass CatalystData(Structure):\n _fields_ = [\n ('nCellTypes', c_int),\n ('meshData', POINTER(MeshDataForCellType)),\n ('solutionData', POINTER(SolutionDataForCellType))\n ]\n\n\nclass CatalystPlugin(BasePlugin):\n name = 'catalyst'\n systems = ['euler', 'navier-stokes']\n\n def __init__(self, intg, *args, **kwargs):\n super().__init__(intg, *args, **kwargs)\n\n self.divisor = self.cfg.getint(self.cfgsect, 'divisor', 3)\n self.nsteps = self.cfg.getint(self.cfgsect, 'nsteps')\n outputfile = self.cfg.get(self.cfgsect, 'outputfile')\n c_outputfile = create_string_buffer(bytes(outputfile, encoding='utf_8'))\n# hostname = self.cfg.get(self.cfgsect, 'hostname')\n hostname = os.environ.get('PYFR_CLIENT_HOSTNAME', '')\n c_hostname = create_string_buffer(bytes(hostname, encoding='utf_8'))\n port = self.cfg.getint(self.cfgsect, 'port');\n prec = self.cfg.get('backend', 'precision', 'double')\n if prec == 'double':\n self.catalyst = load_library('pyfr_catalyst_fp64')\n else:\n self.catalyst = load_library('pyfr_catalyst_fp32')\n\n ###################\n\n self.backend = backend = intg.backend\n self.mesh = intg.system.mesh\n\n # Amount of subdivision to perform\n# comm = MPI.COMM_WORLD\n# self.divisor = comm.Get_size()\n\n # Allocate a queue on the backend\n self._queue = backend.queue()\n\n # Solution arrays\n self.eles_scal_upts_inb = inb = intg.system.eles_scal_upts_inb\n\n # Prepare the mesh data and solution data\n meshData, solnData, kerns = [], [], []\n for etype, solnmat in zip(intg.system.ele_types, inb):\n p, solnop = self._prepare_vtu(etype, intg.rallocs.prank)\n\n # Allocate on the backend\n vismat = backend.matrix((p.nVerticesPerCell, self.nvars, p.nCells),\n tags={'align'})\n solnop = backend.const_matrix(solnop)\n backend.commit()\n\n # Populate the soln field and dimension info\n s = SolutionDataForCellType(ldim = vismat.leaddim,\n lsdim = vismat.leadsubdim,\n soln = vismat.data)\n\n # Prepare the matrix multiplication kernel\n k = backend.kernel('mul', solnop, solnmat, out=vismat)\n\n # Append\n meshData.append(p)\n solnData.append(s)\n kerns.append(k)\n\n # Save the pieces\n catalystData = []\n catalystData.append(\n CatalystData(nCellTypes = len(meshData),\n meshData = (MeshDataForCellType*len(meshData))(*meshData),\n solutionData = (SolutionDataForCellType*len(solnData))(*solnData)))\n self._catalystData = (CatalystData*len(catalystData))(*catalystData)\n\n # Wrap the kernels in a proxy list\n self._interpolate_upts = proxylist(kerns)\n\n # Finally, initialize Catalyst\n self._data = self.catalyst.CatalystInitialize(c_hostname,\n port,\n c_outputfile,\n self._catalystData)\n\n def _prepare_vtu(self, etype, part):\n from pyfr.writers.paraview import BaseShapeSubDiv\n\n mesh = self.mesh['spt_{0}_p{1}'.format(etype, part)]\n\n # Get the shape and sub division classes\n shapecls = subclass_where(BaseShape, name=etype)\n subdvcls = subclass_where(BaseShapeSubDiv, name=etype)\n\n # Dimensions\n # tjc: nspts: number of points in the element type\n # tjc: neles: number of elements of this type\n nspts, neles = mesh.shape[:2]\n\n # Sub divison points inside of a standard element\n svpts = shapecls.std_ele(self.divisor)\n nsvpts = len(svpts)\n\n # Shape\n soln_b = shapecls(nspts, self.cfg)\n\n # Generate the operator matrices\n mesh_vtu_op = soln_b.sbasis.nodal_basis_at(svpts)\n soln_vtu_op = soln_b.ubasis.nodal_basis_at(svpts)\n\n # Calculate node locations of vtu elements\n vpts = np.dot(mesh_vtu_op, mesh.reshape(nspts, -1))\n vpts = vpts.reshape(nsvpts, -1, self.ndims)\n\n # Append dummy z dimension for points in 2D\n if self.ndims == 2:\n vpts = np.pad(vpts, [(0, 0), (0, 0), (0, 1)], 'constant')\n\n # Reorder and cast\n vpts = vpts.swapaxes(0, 1).astype(self.backend.fpdtype, order='C')\n\n # Perform the sub division\n nodes = subdvcls.subnodes(self.divisor)\n\n # Prepare vtu cell arrays\n vtu_con = np.tile(nodes, (neles, 1))\n vtu_con += (np.arange(neles)*nsvpts)[:, None]\n vtu_con = vtu_con.astype(np.int32, order='C')\n\n # Generate offset into the connectivity array\n vtu_off = np.tile(subdvcls.subcelloffs(self.divisor), (neles, 1))\n vtu_off += (np.arange(neles)*len(nodes))[:, None]\n vtu_off = vtu_off.astype(np.int32, order='C')\n\n # Tile vtu cell type numbers\n vtu_typ = np.tile(subdvcls.subcelltypes(self.divisor), neles)\n vtu_typ = vtu_typ.astype(np.uint8, order='C')\n\n # Construct the meshDataForCellType\n meshDataForCellType = \\\n MeshDataForCellType(nVerticesPerCell=nsvpts,\n nCells=neles,\n vertices=vpts.ctypes.data_as(c_void_p),\n nSubdividedCells=len(vtu_typ),\n con=vtu_con.ctypes.data,\n off=vtu_off.ctypes.data,\n type=vtu_typ.ctypes.data)\n\n # Retain the underlying NumPy objects\n meshDataForCellType._vpts = vpts\n meshDataForCellType._vtu_con = vtu_con\n meshDataForCellType._vtu_off = vtu_off\n meshDataForCellType._vtu_typ = vtu_typ\n\n return meshDataForCellType, soln_vtu_op\n\n def __call__(self, intg):\n if np.isclose(intg.tcurr,intg.tend):\n\n # Configure the input bank\n self.eles_scal_upts_inb.active = intg._idxcurr\n\n # Interpolate to the vis points\n self._queue % self._interpolate_upts()\n\n self.catalyst.CatalystCoProcess(c_double(intg.tcurr),intg.nacptsteps,self._data,c_bool(True))\n self.catalyst.CatalystFinalize(self._data)\n return\n\n if intg.nacptsteps % self.nsteps:\n return\n\n # Configure the input bank\n self.eles_scal_upts_inb.active = intg._idxcurr\n\n # Interpolate to the vis points\n self._queue % self._interpolate_upts()\n\n self.catalyst.CatalystCoProcess(c_double(intg.tcurr),intg.nacptsteps,self._data)\n" ]
[ [ "numpy.hstack", "numpy.pad", "numpy.uint32", "numpy.arange", "numpy.tile", "numpy.dtype", "numpy.column_stack", "numpy.ravel", "numpy.array", "numpy.zeros" ], [ "numpy.arange", "numpy.pad", "numpy.tile", "numpy.isclose" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
couyang24/general_learning-tiffany
[ "fa358e6f3b14386519295a8959ad02512f92fb95" ]
[ "Titanic/analysis/colab_titanic_main.py" ]
[ "# <a href=\"https://colab.research.google.com/github/couyang24/general_learning-tiffany/blob/master/Titanic/analysis/colab_titanic_main.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n\n# Need to mount Drive on or upload kaggle.json\n\nfrom google.colab import drive\n\ndrive.mount(\"/content/drive\")\n\n# !mkdir ~/.kaggle/\n\n# !cp drive/My\\ Drive/input/kaggle.json ~/.kaggle/\n\n# !kaggle competitions download -c titanic\n\n# Load Package\n# import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport featuretools\n\nimport featuretools as ft\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.impute import SimpleImputer, MissingIndicator\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.preprocessing import (\n OneHotEncoder,\n StandardScaler,\n LabelEncoder,\n OrdinalEncoder,\n)\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.model_selection import cross_val_score, RandomizedSearchCV\n\n# Load data\ntrain_df = pd.read_csv(\"train.csv\")\ntest_df = pd.read_csv(\"test.csv\")\n\n# Save data\ntarget = train_df[[\"Survived\"]]\nsubmission = test_df[[\"PassengerId\"]]\n\n# Join and Clean\ncombine = pd.concat([train_df, test_df])\n\n# EDA\ncombine.info()\n\ncombine.columns\n\nmapping = {\n \"Mlle\": \"Miss\",\n \"Major\": \"Mr\",\n \"Col\": \"Mr\",\n \"Sir\": \"Mr\",\n \"Don\": \"Mr\",\n \"Mme\": \"Miss\",\n \"Jonkheer\": \"Mr\",\n \"Lady\": \"Mrs\",\n \"Capt\": \"Mr\",\n \"Countess\": \"Mrs\",\n \"Ms\": \"Miss\",\n \"Dona\": \"Mrs\",\n}\n\ncombine[\"Title\"] = combine.Name.apply(\n lambda x: x.split(\".\")[0].split(\",\")[1].strip()\n).replace(mapping)\n\ncombine.drop([\"Cabin\", \"Ticket\", \"Name\"], axis=1, inplace=True)\n\n# +\n# combine['Sex2'] = combine['Sex'].apply(lambda x: 0 if x=='female' else 1)\n\n# +\n# class ModifiedLabelEncoder(LabelEncoder):\n\n# def fit_transform(self, y, *args, **kwargs):\n# return super().fit_transform(y)\n\n# def transform(self, y, *args, **kwargs):\n# return super().transform(y)\n\n# +\ncategorical_transformer = Pipeline(\n steps=[\n (\"imputer\", SimpleImputer(strategy=\"most_frequent\")),\n (\"encode\", OrdinalEncoder()),\n ]\n)\n\nnumeric_transformer = Pipeline([(\"imputer\", SimpleImputer(strategy=\"median\")),])\n# -\n\ncombine[[\"Sex\", \"Embarked\", \"Title\"]] = categorical_transformer.fit_transform(\n combine[[\"Sex\", \"Embarked\", \"Title\"]]\n)\n\ncombine[[\"Age\", \"Fare\"]] = numeric_transformer.fit_transform(combine[[\"Age\", \"Fare\"]])\n\n# +\nes = ft.EntitySet(id=\"titanic_data\")\n\nes = es.entity_from_dataframe(\n entity_id=\"combine\",\n dataframe=combine.drop([\"Survived\"], axis=1),\n variable_types={\n \"Embarked\": ft.variable_types.Categorical,\n \"Sex\": ft.variable_types.Boolean,\n \"Title\": ft.variable_types.Categorical,\n },\n index=\"PassengerId\",\n)\n\nes\n# -\n\nes = es.normalize_entity(\n base_entity_id=\"combine\", new_entity_id=\"Embarked\", index=\"Embarked\"\n)\nes = es.normalize_entity(base_entity_id=\"combine\", new_entity_id=\"Sex\", index=\"Sex\")\nes = es.normalize_entity(base_entity_id=\"combine\", new_entity_id=\"Title\", index=\"Title\")\nes = es.normalize_entity(\n base_entity_id=\"combine\", new_entity_id=\"Pclass\", index=\"Pclass\"\n)\nes = es.normalize_entity(base_entity_id=\"combine\", new_entity_id=\"Parch\", index=\"Parch\")\nes = es.normalize_entity(base_entity_id=\"combine\", new_entity_id=\"SibSp\", index=\"SibSp\")\nes\n\nprimitives = ft.list_primitives()\npd.options.display.max_colwidth = 100\nprimitives[primitives[\"type\"] == \"aggregation\"].head(\n primitives[primitives[\"type\"] == \"aggregation\"].shape[0]\n)\n\nprimitives[primitives[\"type\"] == \"transform\"].head(\n primitives[primitives[\"type\"] == \"transform\"].shape[0]\n)\n\nfeatures, feature_names = ft.dfs(\n entityset=es,\n target_entity=\"combine\",\n # trans_primitives=['subtract_numeric', 'add_numeric', 'divide_numeric', 'multiply_numeric'],\n max_depth=2,\n)\n\nfeature_names\n\nlen(feature_names)\n\nfeatures.isnull().sum()\n\n\nclass RemoveLowInfo(BaseEstimator, TransformerMixin):\n def __init__(self, threshold):\n self.threshold = threshold\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n df = X.copy()\n keep = [\n column\n for column in df.columns\n if df[column].value_counts(normalize=True).reset_index(drop=True)[0]\n < self.threshold\n ]\n return df[keep]\n\n\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler, FunctionTransformer\n\nimpute_median = FunctionTransformer(lambda x: x.fillna(x.median()), validate=False)\n\nnormalize = FunctionTransformer(lambda x: (x - x.mean()) / x.std(), validate=False)\n\nfrom sklearn.decomposition import PCA\n\ntransformer = Pipeline(\n [\n (\"imputer\", impute_median),\n (\"removelowinfo\", RemoveLowInfo(threshold=0.95)),\n (\"scaler\", normalize),\n ]\n)\n\nclean_features = transformer.fit_transform(features)\n\n# !pip install catboost\n\nfrom sklearn.linear_model import LogisticRegression, SGDClassifier\nfrom sklearn.ensemble import (\n RandomForestClassifier,\n GradientBoostingClassifier,\n AdaBoostClassifier,\n BaggingClassifier,\n VotingClassifier,\n)\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.decomposition import PCA\nimport xgboost as xgb\nimport lightgbm as lgb\nimport catboost as cgb\n\n# +\nmethods = [\n (\"logistic\", LogisticRegression(solver=\"lbfgs\")),\n # ('sgd', SGDClassifier()),\n (\"tree\", DecisionTreeClassifier()),\n (\"bag\", BaggingClassifier()),\n (\"xgb\", xgb.XGBClassifier(max_depth=3)),\n (\"lgb\", lgb.LGBMClassifier(max_depth=3)),\n # ('cgb', cgb.CatBoostClassifier(max_depth=3,silent=True)),\n (\"ada\", AdaBoostClassifier()),\n (\"gbm\", GradientBoostingClassifier()),\n (\"rf\", RandomForestClassifier(n_estimators=100)),\n # ('svc', LinearSVC()),\n # ('rbf', SVC()),\n (\"nb\", Pipeline([(\"pca\", PCA()), (\"gnb\", GaussianNB())])),\n (\"nn\", MLPClassifier()),\n (\"knn\", KNeighborsClassifier()),\n]\n\n\nensemble = VotingClassifier(\n methods,\n voting=\"soft\",\n # weights=[1,1,1,1,2,2,1,1],\n # flatten_transform=True,\n)\n\nclf = Pipeline(\n [\n # ('transformer', transformer),\n (\"ensemble\", ensemble),\n ]\n)\n\nclf.fit(clean_features.iloc[: train_df.shape[0], :], target)\n# -\n\nsubmission[\"Survived\"] = pd.DataFrame(\n clf.predict(clean_features.iloc[train_df.shape[0] :, :])\n)\n\nprint(submission.dtypes)\n\nsubmission.to_csv(\"titanic_submission.csv\", index=False)\n" ]
[ [ "sklearn.neural_network.MLPClassifier", "sklearn.ensemble.BaggingClassifier", "pandas.concat", "pandas.read_csv", "sklearn.naive_bayes.GaussianNB", "sklearn.linear_model.LogisticRegression", "sklearn.ensemble.RandomForestClassifier", "sklearn.impute.SimpleImputer", "sklearn.pipeline.Pipeline", "sklearn.ensemble.VotingClassifier", "sklearn.neighbors.KNeighborsClassifier", "sklearn.tree.DecisionTreeClassifier", "sklearn.ensemble.AdaBoostClassifier", "sklearn.preprocessing.OrdinalEncoder", "sklearn.ensemble.GradientBoostingClassifier", "sklearn.decomposition.PCA" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
ahmedtolan23/NER-with-bilstm-CRF-CNN
[ "29db9f2e357fc4112f9b5752f8ec604e4b9a04b0" ]
[ "models/BiLSTM.py" ]
[ "\"\"\"\n FILE : BiLSTM.py\n FUNCTION : None\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nimport random\nfrom DataUtils.Common import *\nfrom models.initialize import *\nfrom models.modelHelp import prepare_pack_padded_sequence\ntorch.manual_seed(seed_num)\nrandom.seed(seed_num)\n\n\nclass BiLSTM(nn.Module):\n \"\"\"\n BiLSTM\n \"\"\"\n\n def __init__(self, **kwargs):\n super(BiLSTM, self).__init__()\n for k in kwargs:\n self.__setattr__(k, kwargs[k])\n\n V = self.embed_num\n D = self.embed_dim\n C = self.label_num\n paddingId = self.paddingId\n\n self.embed = nn.Embedding(V, D, padding_idx=paddingId)\n\n if self.pretrained_embed:\n self.embed.weight.data.copy_(self.pretrained_weight)\n else:\n init_embedding(self.embed.weight)\n\n self.dropout_embed = nn.Dropout(self.dropout_emb)\n self.dropout = nn.Dropout(self.dropout)\n\n self.bilstm = nn.LSTM(input_size=D, hidden_size=self.lstm_hiddens, num_layers=self.lstm_layers,\n bidirectional=True, batch_first=True, bias=True)\n\n self.linear = nn.Linear(in_features=self.lstm_hiddens * 2, out_features=C, bias=True)\n init_linear(self.linear)\n\n def forward(self, word, sentence_length):\n \"\"\"\n :param word:\n :param sentence_length:\n :param desorted_indices:\n :return:\n \"\"\"\n word, sentence_length, desorted_indices = prepare_pack_padded_sequence(word, sentence_length, device=self.device)\n x = self.embed(word) # (N,W,D)\n x = self.dropout_embed(x)\n packed_embed = pack_padded_sequence(x, sentence_length, batch_first=True)\n x, _ = self.bilstm(packed_embed)\n x, _ = pad_packed_sequence(x, batch_first=True)\n x = x[desorted_indices]\n x = self.dropout(x)\n x = torch.tanh(x)\n logit = self.linear(x)\n return logit\n\n\nclass BiLSTM(nn.Module):\n def __init__(self, vocab_size, emb_size, hidden_size, out_size):\n \"\"\":\n vocab_size:\n emb_size:\n hidden_size:\n out_size:\n \"\"\"\n super(BiLSTM, self).__init__()\n self.embedding = nn.Embedding(vocab_size, emb_size)\n self.bilstm = nn.LSTM(emb_size, hidden_size,\n batch_first=True,\n bidirectional=True)\n\n self.lin = nn.Linear(2*hidden_size, out_size)\n\n def forward(self, sents_tensor, lengths):\n emb = self.embedding(sents_tensor) # [B, L, emb_size]\n\n packed = pack_padded_sequence(emb, lengths, batch_first=True)\n rnn_out, _ = self.bilstm(packed)\n # rnn_out:[B, L, hidden_size*2]\n rnn_out, _ = pad_packed_sequence(rnn_out, batch_first=True)\n\n scores = self.lin(rnn_out) # [B, L, out_size]\n\n return scores\n\n def test(self, sents_tensor, lengths, _):\n logits = self.forward(sents_tensor, lengths) # [B, L, out_size]\n _, batch_tagids = torch.max(logits, dim=2)\n\n return batch_tagids\n" ]
[ [ "torch.nn.Dropout", "torch.max", "torch.nn.LSTM", "torch.manual_seed", "torch.nn.Embedding", "torch.nn.utils.rnn.pack_padded_sequence", "torch.tanh", "torch.nn.Linear", "torch.nn.utils.rnn.pad_packed_sequence" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yijunyu/demo-fast
[ "11c0c84081a3181494b9c469bda42a313c457ad2", "11c0c84081a3181494b9c469bda42a313c457ad2", "11c0c84081a3181494b9c469bda42a313c457ad2" ]
[ "datasets/tensorflow-1.0.1/tensorflow/python/ops/rnn.py", "datasets/tensorflow-1.0.1/tensorflow/python/debug/lib/stepper_test.py", "datasets/tensorflow-1.0.1/tensorflow/python/framework/function.py" ]
[ "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"RNN helpers for TensorFlow models.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import rnn_cell_impl\nfrom tensorflow.python.ops import tensor_array_ops\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.util import nest\n\n\n# pylint: disable=protected-access\n_state_size_with_prefix = rnn_cell_impl._state_size_with_prefix\n# pylint: enable=protected-access\n\n\ndef _infer_state_dtype(explicit_dtype, state):\n \"\"\"Infer the dtype of an RNN state.\n\n Args:\n explicit_dtype: explicitly declared dtype or None.\n state: RNN's hidden state. Must be a Tensor or a nested iterable containing\n Tensors.\n\n Returns:\n dtype: inferred dtype of hidden state.\n\n Raises:\n ValueError: if `state` has heterogeneous dtypes or is empty.\n \"\"\"\n if explicit_dtype is not None:\n return explicit_dtype\n elif nest.is_sequence(state):\n inferred_dtypes = [element.dtype for element in nest.flatten(state)]\n if not inferred_dtypes:\n raise ValueError(\"Unable to infer dtype from empty state.\")\n all_same = all([x == inferred_dtypes[0] for x in inferred_dtypes])\n if not all_same:\n raise ValueError(\n \"State has tensors of different inferred_dtypes. Unable to infer a \"\n \"single representative dtype.\")\n return inferred_dtypes[0]\n else:\n return state.dtype\n\n\ndef _on_device(fn, device):\n \"\"\"Build the subgraph defined by lambda `fn` on `device` if it's not None.\"\"\"\n if device:\n with ops.device(device):\n return fn()\n else:\n return fn()\n\n\n# pylint: disable=unused-argument\ndef _rnn_step(\n time, sequence_length, min_sequence_length, max_sequence_length,\n zero_output, state, call_cell, state_size, skip_conditionals=False):\n \"\"\"Calculate one step of a dynamic RNN minibatch.\n\n Returns an (output, state) pair conditioned on the sequence_lengths.\n When skip_conditionals=False, the pseudocode is something like:\n\n if t >= max_sequence_length:\n return (zero_output, state)\n if t < min_sequence_length:\n return call_cell()\n\n # Selectively output zeros or output, old state or new state depending\n # on if we've finished calculating each row.\n new_output, new_state = call_cell()\n final_output = np.vstack([\n zero_output if time >= sequence_lengths[r] else new_output_r\n for r, new_output_r in enumerate(new_output)\n ])\n final_state = np.vstack([\n state[r] if time >= sequence_lengths[r] else new_state_r\n for r, new_state_r in enumerate(new_state)\n ])\n return (final_output, final_state)\n\n Args:\n time: Python int, the current time step\n sequence_length: int32 `Tensor` vector of size [batch_size]\n min_sequence_length: int32 `Tensor` scalar, min of sequence_length\n max_sequence_length: int32 `Tensor` scalar, max of sequence_length\n zero_output: `Tensor` vector of shape [output_size]\n state: Either a single `Tensor` matrix of shape `[batch_size, state_size]`,\n or a list/tuple of such tensors.\n call_cell: lambda returning tuple of (new_output, new_state) where\n new_output is a `Tensor` matrix of shape `[batch_size, output_size]`.\n new_state is a `Tensor` matrix of shape `[batch_size, state_size]`.\n state_size: The `cell.state_size` associated with the state.\n skip_conditionals: Python bool, whether to skip using the conditional\n calculations. This is useful for `dynamic_rnn`, where the input tensor\n matches `max_sequence_length`, and using conditionals just slows\n everything down.\n\n Returns:\n A tuple of (`final_output`, `final_state`) as given by the pseudocode above:\n final_output is a `Tensor` matrix of shape [batch_size, output_size]\n final_state is either a single `Tensor` matrix, or a tuple of such\n matrices (matching length and shapes of input `state`).\n\n Raises:\n ValueError: If the cell returns a state tuple whose length does not match\n that returned by `state_size`.\n \"\"\"\n\n # Convert state to a list for ease of use\n flat_state = nest.flatten(state)\n flat_zero_output = nest.flatten(zero_output)\n\n def _copy_one_through(output, new_output):\n copy_cond = (time >= sequence_length)\n return _on_device(\n lambda: array_ops.where(copy_cond, output, new_output),\n device=new_output.op.device)\n\n def _copy_some_through(flat_new_output, flat_new_state):\n # Use broadcasting select to determine which values should get\n # the previous state & zero output, and which values should get\n # a calculated state & output.\n flat_new_output = [\n _copy_one_through(zero_output, new_output)\n for zero_output, new_output in zip(flat_zero_output, flat_new_output)]\n flat_new_state = [\n _copy_one_through(state, new_state)\n for state, new_state in zip(flat_state, flat_new_state)]\n return flat_new_output + flat_new_state\n\n def _maybe_copy_some_through():\n \"\"\"Run RNN step. Pass through either no or some past state.\"\"\"\n new_output, new_state = call_cell()\n\n nest.assert_same_structure(state, new_state)\n\n flat_new_state = nest.flatten(new_state)\n flat_new_output = nest.flatten(new_output)\n return control_flow_ops.cond(\n # if t < min_seq_len: calculate and return everything\n time < min_sequence_length, lambda: flat_new_output + flat_new_state,\n # else copy some of it through\n lambda: _copy_some_through(flat_new_output, flat_new_state))\n\n # TODO(ebrevdo): skipping these conditionals may cause a slowdown,\n # but benefits from removing cond() and its gradient. We should\n # profile with and without this switch here.\n if skip_conditionals:\n # Instead of using conditionals, perform the selective copy at all time\n # steps. This is faster when max_seq_len is equal to the number of unrolls\n # (which is typical for dynamic_rnn).\n new_output, new_state = call_cell()\n nest.assert_same_structure(state, new_state)\n new_state = nest.flatten(new_state)\n new_output = nest.flatten(new_output)\n final_output_and_state = _copy_some_through(new_output, new_state)\n else:\n empty_update = lambda: flat_zero_output + flat_state\n final_output_and_state = control_flow_ops.cond(\n # if t >= max_seq_len: copy all state through, output zeros\n time >= max_sequence_length, empty_update,\n # otherwise calculation is required: copy some or all of it through\n _maybe_copy_some_through)\n\n if len(final_output_and_state) != len(flat_zero_output) + len(flat_state):\n raise ValueError(\"Internal error: state and output were not concatenated \"\n \"correctly.\")\n final_output = final_output_and_state[:len(flat_zero_output)]\n final_state = final_output_and_state[len(flat_zero_output):]\n\n for output, flat_output in zip(final_output, flat_zero_output):\n output.set_shape(flat_output.get_shape())\n for substate, flat_substate in zip(final_state, flat_state):\n substate.set_shape(flat_substate.get_shape())\n\n final_output = nest.pack_sequence_as(\n structure=zero_output, flat_sequence=final_output)\n final_state = nest.pack_sequence_as(\n structure=state, flat_sequence=final_state)\n\n return final_output, final_state\n\n\ndef _reverse_seq(input_seq, lengths):\n \"\"\"Reverse a list of Tensors up to specified lengths.\n\n Args:\n input_seq: Sequence of seq_len tensors of dimension (batch_size, n_features)\n or nested tuples of tensors.\n lengths: A `Tensor` of dimension batch_size, containing lengths for each\n sequence in the batch. If \"None\" is specified, simply reverses\n the list.\n\n Returns:\n time-reversed sequence\n \"\"\"\n if lengths is None:\n return list(reversed(input_seq))\n\n flat_input_seq = tuple(nest.flatten(input_) for input_ in input_seq)\n\n flat_results = [[] for _ in range(len(input_seq))]\n for sequence in zip(*flat_input_seq):\n input_shape = tensor_shape.unknown_shape(\n ndims=sequence[0].get_shape().ndims)\n for input_ in sequence:\n input_shape.merge_with(input_.get_shape())\n input_.set_shape(input_shape)\n\n # Join into (time, batch_size, depth)\n s_joined = array_ops.stack(sequence)\n\n # TODO(schuster, ebrevdo): Remove cast when reverse_sequence takes int32\n if lengths is not None:\n lengths = math_ops.to_int64(lengths)\n\n # Reverse along dimension 0\n s_reversed = array_ops.reverse_sequence(s_joined, lengths, 0, 1)\n # Split again into list\n result = array_ops.unstack(s_reversed)\n for r, flat_result in zip(result, flat_results):\n r.set_shape(input_shape)\n flat_result.append(r)\n\n results = [nest.pack_sequence_as(structure=input_, flat_sequence=flat_result)\n for input_, flat_result in zip(input_seq, flat_results)]\n return results\n\n\ndef bidirectional_dynamic_rnn(cell_fw, cell_bw, inputs, sequence_length=None,\n initial_state_fw=None, initial_state_bw=None,\n dtype=None, parallel_iterations=None,\n swap_memory=False, time_major=False, scope=None):\n \"\"\"Creates a dynamic version of bidirectional recurrent neural network.\n\n Similar to the unidirectional case above (rnn) but takes input and builds\n independent forward and backward RNNs. The input_size of forward and\n backward cell must match. The initial state for both directions is zero by\n default (but can be set optionally) and no intermediate states are ever\n returned -- the network is fully unrolled for the given (passed in)\n length(s) of the sequence(s) or completely unrolled if length(s) is not\n given.\n\n Args:\n cell_fw: An instance of RNNCell, to be used for forward direction.\n cell_bw: An instance of RNNCell, to be used for backward direction.\n inputs: The RNN inputs.\n If time_major == False (default), this must be a tensor of shape:\n `[batch_size, max_time, input_size]`.\n If time_major == True, this must be a tensor of shape:\n `[max_time, batch_size, input_size]`.\n [batch_size, input_size].\n sequence_length: An int32/int64 vector, size `[batch_size]`,\n containing the actual lengths for each of the sequences.\n initial_state_fw: (optional) An initial state for the forward RNN.\n This must be a tensor of appropriate type and shape\n `[batch_size, cell_fw.state_size]`.\n If `cell_fw.state_size` is a tuple, this should be a tuple of\n tensors having shapes `[batch_size, s] for s in cell_fw.state_size`.\n initial_state_bw: (optional) Same as for `initial_state_fw`, but using\n the corresponding properties of `cell_bw`.\n dtype: (optional) The data type for the initial states and expected output.\n Required if initial_states are not provided or RNN states have a\n heterogeneous dtype.\n parallel_iterations: (Default: 32). The number of iterations to run in\n parallel. Those operations which do not have any temporal dependency\n and can be run in parallel, will be. This parameter trades off\n time for space. Values >> 1 use more memory but take less time,\n while smaller values use less memory but computations take longer.\n swap_memory: Transparently swap the tensors produced in forward inference\n but needed for back prop from GPU to CPU. This allows training RNNs\n which would typically not fit on a single GPU, with very minimal (or no)\n performance penalty.\n time_major: The shape format of the `inputs` and `outputs` Tensors.\n If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`.\n If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.\n Using `time_major = True` is a bit more efficient because it avoids\n transposes at the beginning and end of the RNN calculation. However,\n most TensorFlow data is batch-major, so by default this function\n accepts input and emits output in batch-major form.\n dtype: (optional) The data type for the initial state. Required if\n either of the initial states are not provided.\n scope: VariableScope for the created subgraph; defaults to\n \"bidirectional_rnn\"\n\n Returns:\n A tuple (outputs, output_states) where:\n outputs: A tuple (output_fw, output_bw) containing the forward and\n the backward rnn output `Tensor`.\n If time_major == False (default),\n output_fw will be a `Tensor` shaped:\n `[batch_size, max_time, cell_fw.output_size]`\n and output_bw will be a `Tensor` shaped:\n `[batch_size, max_time, cell_bw.output_size]`.\n If time_major == True,\n output_fw will be a `Tensor` shaped:\n `[max_time, batch_size, cell_fw.output_size]`\n and output_bw will be a `Tensor` shaped:\n `[max_time, batch_size, cell_bw.output_size]`.\n It returns a tuple instead of a single concatenated `Tensor`, unlike\n in the `bidirectional_rnn`. If the concatenated one is preferred,\n the forward and backward outputs can be concatenated as\n `tf.concat(outputs, 2)`.\n output_states: A tuple (output_state_fw, output_state_bw) containing\n the forward and the backward final states of bidirectional rnn.\n\n Raises:\n TypeError: If `cell_fw` or `cell_bw` is not an instance of `RNNCell`.\n \"\"\"\n\n # pylint: disable=protected-access\n if not isinstance(cell_fw, rnn_cell_impl._RNNCell):\n raise TypeError(\"cell_fw must be an instance of RNNCell\")\n if not isinstance(cell_bw, rnn_cell_impl._RNNCell):\n raise TypeError(\"cell_bw must be an instance of RNNCell\")\n # pylint: enable=protected-access\n\n with vs.variable_scope(scope or \"bidirectional_rnn\"):\n # Forward direction\n with vs.variable_scope(\"fw\") as fw_scope:\n output_fw, output_state_fw = dynamic_rnn(\n cell=cell_fw, inputs=inputs, sequence_length=sequence_length,\n initial_state=initial_state_fw, dtype=dtype,\n parallel_iterations=parallel_iterations, swap_memory=swap_memory,\n time_major=time_major, scope=fw_scope)\n\n # Backward direction\n if not time_major:\n time_dim = 1\n batch_dim = 0\n else:\n time_dim = 0\n batch_dim = 1\n\n with vs.variable_scope(\"bw\") as bw_scope:\n inputs_reverse = array_ops.reverse_sequence(\n input=inputs, seq_lengths=sequence_length,\n seq_dim=time_dim, batch_dim=batch_dim)\n tmp, output_state_bw = dynamic_rnn(\n cell=cell_bw, inputs=inputs_reverse, sequence_length=sequence_length,\n initial_state=initial_state_bw, dtype=dtype,\n parallel_iterations=parallel_iterations, swap_memory=swap_memory,\n time_major=time_major, scope=bw_scope)\n\n output_bw = array_ops.reverse_sequence(\n input=tmp, seq_lengths=sequence_length,\n seq_dim=time_dim, batch_dim=batch_dim)\n\n outputs = (output_fw, output_bw)\n output_states = (output_state_fw, output_state_bw)\n\n return (outputs, output_states)\n\n\ndef dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None,\n dtype=None, parallel_iterations=None, swap_memory=False,\n time_major=False, scope=None):\n \"\"\"Creates a recurrent neural network specified by RNNCell `cell`.\n\n This function is functionally identical to the function `rnn` above, but\n performs fully dynamic unrolling of `inputs`.\n\n Unlike `rnn`, the input `inputs` is not a Python list of `Tensors`, one for\n each frame. Instead, `inputs` may be a single `Tensor` where\n the maximum time is either the first or second dimension (see the parameter\n `time_major`). Alternatively, it may be a (possibly nested) tuple of\n Tensors, each of them having matching batch and time dimensions.\n The corresponding output is either a single `Tensor` having the same number\n of time steps and batch size, or a (possibly nested) tuple of such tensors,\n matching the nested structure of `cell.output_size`.\n\n The parameter `sequence_length` is optional and is used to copy-through state\n and zero-out outputs when past a batch element's sequence length. So it's more\n for correctness than performance, unlike in rnn().\n\n Args:\n cell: An instance of RNNCell.\n inputs: The RNN inputs.\n\n If `time_major == False` (default), this must be a `Tensor` of shape:\n `[batch_size, max_time, ...]`, or a nested tuple of such\n elements.\n\n If `time_major == True`, this must be a `Tensor` of shape:\n `[max_time, batch_size, ...]`, or a nested tuple of such\n elements.\n\n This may also be a (possibly nested) tuple of Tensors satisfying\n this property. The first two dimensions must match across all the inputs,\n but otherwise the ranks and other shape components may differ.\n In this case, input to `cell` at each time-step will replicate the\n structure of these tuples, except for the time dimension (from which the\n time is taken).\n\n The input to `cell` at each time step will be a `Tensor` or (possibly\n nested) tuple of Tensors each with dimensions `[batch_size, ...]`.\n\n sequence_length: (optional) An int32/int64 vector sized `[batch_size]`.\n initial_state: (optional) An initial state for the RNN.\n If `cell.state_size` is an integer, this must be\n a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.\n If `cell.state_size` is a tuple, this should be a tuple of\n tensors having shapes `[batch_size, s] for s in cell.state_size`.\n dtype: (optional) The data type for the initial state and expected output.\n Required if initial_state is not provided or RNN state has a heterogeneous\n dtype.\n parallel_iterations: (Default: 32). The number of iterations to run in\n parallel. Those operations which do not have any temporal dependency\n and can be run in parallel, will be. This parameter trades off\n time for space. Values >> 1 use more memory but take less time,\n while smaller values use less memory but computations take longer.\n swap_memory: Transparently swap the tensors produced in forward inference\n but needed for back prop from GPU to CPU. This allows training RNNs\n which would typically not fit on a single GPU, with very minimal (or no)\n performance penalty.\n time_major: The shape format of the `inputs` and `outputs` Tensors.\n If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`.\n If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`.\n Using `time_major = True` is a bit more efficient because it avoids\n transposes at the beginning and end of the RNN calculation. However,\n most TensorFlow data is batch-major, so by default this function\n accepts input and emits output in batch-major form.\n scope: VariableScope for the created subgraph; defaults to \"rnn\".\n\n Returns:\n A pair (outputs, state) where:\n\n outputs: The RNN output `Tensor`.\n\n If time_major == False (default), this will be a `Tensor` shaped:\n `[batch_size, max_time, cell.output_size]`.\n\n If time_major == True, this will be a `Tensor` shaped:\n `[max_time, batch_size, cell.output_size]`.\n\n Note, if `cell.output_size` is a (possibly nested) tuple of integers\n or `TensorShape` objects, then `outputs` will be a tuple having the\n same structure as `cell.output_size`, containing Tensors having shapes\n corresponding to the shape data in `cell.output_size`.\n\n state: The final state. If `cell.state_size` is an int, this\n will be shaped `[batch_size, cell.state_size]`. If it is a\n `TensorShape`, this will be shaped `[batch_size] + cell.state_size`.\n If it is a (possibly nested) tuple of ints or `TensorShape`, this will\n be a tuple having the corresponding shapes.\n\n Raises:\n TypeError: If `cell` is not an instance of RNNCell.\n ValueError: If inputs is None or an empty list.\n \"\"\"\n\n # pylint: disable=protected-access\n if not isinstance(cell, rnn_cell_impl._RNNCell):\n raise TypeError(\"cell must be an instance of RNNCell\")\n # pylint: enable=protected-access\n\n # By default, time_major==False and inputs are batch-major: shaped\n # [batch, time, depth]\n # For internal calculations, we transpose to [time, batch, depth]\n flat_input = nest.flatten(inputs)\n\n if not time_major:\n # (B,T,D) => (T,B,D)\n flat_input = tuple(array_ops.transpose(input_, [1, 0, 2])\n for input_ in flat_input)\n\n parallel_iterations = parallel_iterations or 32\n if sequence_length is not None:\n sequence_length = math_ops.to_int32(sequence_length)\n if sequence_length.get_shape().ndims not in (None, 1):\n raise ValueError(\n \"sequence_length must be a vector of length batch_size, \"\n \"but saw shape: %s\" % sequence_length.get_shape())\n sequence_length = array_ops.identity( # Just to find it in the graph.\n sequence_length, name=\"sequence_length\")\n\n # Create a new scope in which the caching device is either\n # determined by the parent scope, or is set to place the cached\n # Variable using the same placement as for the rest of the RNN.\n with vs.variable_scope(scope or \"rnn\") as varscope:\n if varscope.caching_device is None:\n varscope.set_caching_device(lambda op: op.device)\n input_shape = tuple(array_ops.shape(input_) for input_ in flat_input)\n batch_size = input_shape[0][1]\n\n for input_ in input_shape:\n if input_[1].get_shape() != batch_size.get_shape():\n raise ValueError(\"All inputs should have the same batch size\")\n\n if initial_state is not None:\n state = initial_state\n else:\n if not dtype:\n raise ValueError(\"If no initial_state is provided, dtype must be.\")\n state = cell.zero_state(batch_size, dtype)\n\n def _assert_has_shape(x, shape):\n x_shape = array_ops.shape(x)\n packed_shape = array_ops.stack(shape)\n return control_flow_ops.Assert(\n math_ops.reduce_all(math_ops.equal(x_shape, packed_shape)),\n [\"Expected shape for Tensor %s is \" % x.name,\n packed_shape, \" but saw shape: \", x_shape])\n\n if sequence_length is not None:\n # Perform some shape validation\n with ops.control_dependencies(\n [_assert_has_shape(sequence_length, [batch_size])]):\n sequence_length = array_ops.identity(\n sequence_length, name=\"CheckSeqLen\")\n\n inputs = nest.pack_sequence_as(structure=inputs, flat_sequence=flat_input)\n\n (outputs, final_state) = _dynamic_rnn_loop(\n cell,\n inputs,\n state,\n parallel_iterations=parallel_iterations,\n swap_memory=swap_memory,\n sequence_length=sequence_length,\n dtype=dtype)\n\n # Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth].\n # If we are performing batch-major calculations, transpose output back\n # to shape [batch, time, depth]\n if not time_major:\n # (T,B,D) => (B,T,D)\n flat_output = nest.flatten(outputs)\n flat_output = [array_ops.transpose(output, [1, 0, 2])\n for output in flat_output]\n outputs = nest.pack_sequence_as(\n structure=outputs, flat_sequence=flat_output)\n\n return (outputs, final_state)\n\n\ndef _dynamic_rnn_loop(cell,\n inputs,\n initial_state,\n parallel_iterations,\n swap_memory,\n sequence_length=None,\n dtype=None):\n \"\"\"Internal implementation of Dynamic RNN.\n\n Args:\n cell: An instance of RNNCell.\n inputs: A `Tensor` of shape [time, batch_size, input_size], or a nested\n tuple of such elements.\n initial_state: A `Tensor` of shape `[batch_size, state_size]`, or if\n `cell.state_size` is a tuple, then this should be a tuple of\n tensors having shapes `[batch_size, s] for s in cell.state_size`.\n parallel_iterations: Positive Python int.\n swap_memory: A Python boolean\n sequence_length: (optional) An `int32` `Tensor` of shape [batch_size].\n dtype: (optional) Expected dtype of output. If not specified, inferred from\n initial_state.\n\n Returns:\n Tuple `(final_outputs, final_state)`.\n final_outputs:\n A `Tensor` of shape `[time, batch_size, cell.output_size]`. If\n `cell.output_size` is a (possibly nested) tuple of ints or `TensorShape`\n objects, then this returns a (possibly nsted) tuple of Tensors matching\n the corresponding shapes.\n final_state:\n A `Tensor`, or possibly nested tuple of Tensors, matching in length\n and shapes to `initial_state`.\n\n Raises:\n ValueError: If the input depth cannot be inferred via shape inference\n from the inputs.\n \"\"\"\n state = initial_state\n assert isinstance(parallel_iterations, int), \"parallel_iterations must be int\"\n\n state_size = cell.state_size\n\n flat_input = nest.flatten(inputs)\n flat_output_size = nest.flatten(cell.output_size)\n\n # Construct an initial output\n input_shape = array_ops.shape(flat_input[0])\n time_steps = input_shape[0]\n batch_size = input_shape[1]\n\n inputs_got_shape = tuple(input_.get_shape().with_rank_at_least(3)\n for input_ in flat_input)\n\n const_time_steps, const_batch_size = inputs_got_shape[0].as_list()[:2]\n\n for shape in inputs_got_shape:\n if not shape[2:].is_fully_defined():\n raise ValueError(\n \"Input size (depth of inputs) must be accessible via shape inference,\"\n \" but saw value None.\")\n got_time_steps = shape[0].value\n got_batch_size = shape[1].value\n if const_time_steps != got_time_steps:\n raise ValueError(\n \"Time steps is not the same for all the elements in the input in a \"\n \"batch.\")\n if const_batch_size != got_batch_size:\n raise ValueError(\n \"Batch_size is not the same for all the elements in the input.\")\n\n # Prepare dynamic conditional copying of state & output\n def _create_zero_arrays(size):\n size = _state_size_with_prefix(size, prefix=[batch_size])\n return array_ops.zeros(\n array_ops.stack(size), _infer_state_dtype(dtype, state))\n\n flat_zero_output = tuple(_create_zero_arrays(output)\n for output in flat_output_size)\n zero_output = nest.pack_sequence_as(structure=cell.output_size,\n flat_sequence=flat_zero_output)\n\n if sequence_length is not None:\n min_sequence_length = math_ops.reduce_min(sequence_length)\n max_sequence_length = math_ops.reduce_max(sequence_length)\n\n time = array_ops.constant(0, dtype=dtypes.int32, name=\"time\")\n\n with ops.name_scope(\"dynamic_rnn\") as scope:\n base_name = scope\n\n def _create_ta(name, dtype):\n return tensor_array_ops.TensorArray(dtype=dtype,\n size=time_steps,\n tensor_array_name=base_name + name)\n\n output_ta = tuple(_create_ta(\"output_%d\" % i,\n _infer_state_dtype(dtype, state))\n for i in range(len(flat_output_size)))\n input_ta = tuple(_create_ta(\"input_%d\" % i, flat_input[0].dtype)\n for i in range(len(flat_input)))\n\n input_ta = tuple(ta.unstack(input_)\n for ta, input_ in zip(input_ta, flat_input))\n\n def _time_step(time, output_ta_t, state):\n \"\"\"Take a time step of the dynamic RNN.\n\n Args:\n time: int32 scalar Tensor.\n output_ta_t: List of `TensorArray`s that represent the output.\n state: nested tuple of vector tensors that represent the state.\n\n Returns:\n The tuple (time + 1, output_ta_t with updated flow, new_state).\n \"\"\"\n\n input_t = tuple(ta.read(time) for ta in input_ta)\n # Restore some shape information\n for input_, shape in zip(input_t, inputs_got_shape):\n input_.set_shape(shape[1:])\n\n input_t = nest.pack_sequence_as(structure=inputs, flat_sequence=input_t)\n call_cell = lambda: cell(input_t, state)\n\n if sequence_length is not None:\n (output, new_state) = _rnn_step(\n time=time,\n sequence_length=sequence_length,\n min_sequence_length=min_sequence_length,\n max_sequence_length=max_sequence_length,\n zero_output=zero_output,\n state=state,\n call_cell=call_cell,\n state_size=state_size,\n skip_conditionals=True)\n else:\n (output, new_state) = call_cell()\n\n # Pack state if using state tuples\n output = nest.flatten(output)\n\n output_ta_t = tuple(\n ta.write(time, out) for ta, out in zip(output_ta_t, output))\n\n return (time + 1, output_ta_t, new_state)\n\n _, output_final_ta, final_state = control_flow_ops.while_loop(\n cond=lambda time, *_: time < time_steps,\n body=_time_step,\n loop_vars=(time, output_ta, state),\n parallel_iterations=parallel_iterations,\n swap_memory=swap_memory)\n\n # Unpack final output if not using output tuples.\n final_outputs = tuple(ta.stack() for ta in output_final_ta)\n\n # Restore some shape information\n for output, output_size in zip(final_outputs, flat_output_size):\n shape = _state_size_with_prefix(\n output_size, prefix=[const_time_steps, const_batch_size])\n output.set_shape(shape)\n\n final_outputs = nest.pack_sequence_as(\n structure=cell.output_size, flat_sequence=final_outputs)\n\n return (final_outputs, final_state)\n\n\ndef raw_rnn(cell, loop_fn,\n parallel_iterations=None, swap_memory=False, scope=None):\n \"\"\"Creates an `RNN` specified by RNNCell `cell` and loop function `loop_fn`.\n\n **NOTE: This method is still in testing, and the API may change.**\n\n This function is a more primitive version of `dynamic_rnn` that provides\n more direct access to the inputs each iteration. It also provides more\n control over when to start and finish reading the sequence, and\n what to emit for the output.\n\n For example, it can be used to implement the dynamic decoder of a seq2seq\n model.\n\n Instead of working with `Tensor` objects, most operations work with\n `TensorArray` objects directly.\n\n The operation of `raw_rnn`, in pseudo-code, is basically the following:\n\n ```python\n time = tf.constant(0, dtype=tf.int32)\n (finished, next_input, initial_state, _, loop_state) = loop_fn(\n time=time, cell_output=None, cell_state=None, loop_state=None)\n emit_ta = TensorArray(dynamic_size=True, dtype=initial_state.dtype)\n state = initial_state\n while not all(finished):\n (output, cell_state) = cell(next_input, state)\n (next_finished, next_input, next_state, emit, loop_state) = loop_fn(\n time=time + 1, cell_output=output, cell_state=cell_state,\n loop_state=loop_state)\n # Emit zeros and copy forward state for minibatch entries that are finished.\n state = tf.where(finished, state, next_state)\n emit = tf.where(finished, tf.zeros_like(emit), emit)\n emit_ta = emit_ta.write(time, emit)\n # If any new minibatch entries are marked as finished, mark these.\n finished = tf.logical_or(finished, next_finished)\n time += 1\n return (emit_ta, state, loop_state)\n ```\n\n with the additional properties that output and state may be (possibly nested)\n tuples, as determined by `cell.output_size` and `cell.state_size`, and\n as a result the final `state` and `emit_ta` may themselves be tuples.\n\n A simple implementation of `dynamic_rnn` via `raw_rnn` looks like this:\n\n ```python\n inputs = tf.placeholder(shape=(max_time, batch_size, input_depth),\n dtype=tf.float32)\n sequence_length = tf.placeholder(shape=(batch_size,), dtype=tf.int32)\n inputs_ta = tf.TensorArray(dtype=tf.float32, size=max_time)\n inputs_ta = inputs_ta.unstack(inputs)\n\n cell = tf.contrib.rnn.LSTMCell(num_units)\n\n def loop_fn(time, cell_output, cell_state, loop_state):\n emit_output = cell_output # == None for time == 0\n if cell_output is None: # time == 0\n next_cell_state = cell.zero_state(batch_size, tf.float32)\n else:\n next_cell_state = cell_state\n elements_finished = (time >= sequence_length)\n finished = tf.reduce_all(elements_finished)\n next_input = tf.cond(\n finished,\n lambda: tf.zeros([batch_size, input_depth], dtype=tf.float32),\n lambda: inputs_ta.read(time))\n next_loop_state = None\n return (elements_finished, next_input, next_cell_state,\n emit_output, next_loop_state)\n\n outputs_ta, final_state, _ = raw_rnn(cell, loop_fn)\n outputs = outputs_ta.stack()\n ```\n\n Args:\n cell: An instance of RNNCell.\n loop_fn: A callable that takes inputs\n `(time, cell_output, cell_state, loop_state)`\n and returns the tuple\n `(finished, next_input, next_cell_state, emit_output, next_loop_state)`.\n Here `time` is an int32 scalar `Tensor`, `cell_output` is a\n `Tensor` or (possibly nested) tuple of tensors as determined by\n `cell.output_size`, and `cell_state` is a `Tensor`\n or (possibly nested) tuple of tensors, as determined by the `loop_fn`\n on its first call (and should match `cell.state_size`).\n The outputs are: `finished`, a boolean `Tensor` of\n shape `[batch_size]`, `next_input`: the next input to feed to `cell`,\n `next_cell_state`: the next state to feed to `cell`,\n and `emit_output`: the output to store for this iteration.\n\n Note that `emit_output` should be a `Tensor` or (possibly nested)\n tuple of tensors with shapes and structure matching `cell.output_size`\n and `cell_output` above. The parameter `cell_state` and output\n `next_cell_state` may be either a single or (possibly nested) tuple\n of tensors. The parameter `loop_state` and\n output `next_loop_state` may be either a single or (possibly nested) tuple\n of `Tensor` and `TensorArray` objects. This last parameter\n may be ignored by `loop_fn` and the return value may be `None`. If it\n is not `None`, then the `loop_state` will be propagated through the RNN\n loop, for use purely by `loop_fn` to keep track of its own state.\n The `next_loop_state` parameter returned may be `None`.\n\n The first call to `loop_fn` will be `time = 0`, `cell_output = None`,\n `cell_state = None`, and `loop_state = None`. For this call:\n The `next_cell_state` value should be the value with which to initialize\n the cell's state. It may be a final state from a previous RNN or it\n may be the output of `cell.zero_state()`. It should be a\n (possibly nested) tuple structure of tensors.\n If `cell.state_size` is an integer, this must be\n a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`.\n If `cell.state_size` is a `TensorShape`, this must be a `Tensor` of\n appropriate type and shape `[batch_size] + cell.state_size`.\n If `cell.state_size` is a (possibly nested) tuple of ints or\n `TensorShape`, this will be a tuple having the corresponding shapes.\n The `emit_output` value may be either `None` or a (possibly nested)\n tuple structure of tensors, e.g.,\n `(tf.zeros(shape_0, dtype=dtype_0), tf.zeros(shape_1, dtype=dtype_1))`.\n If this first `emit_output` return value is `None`,\n then the `emit_ta` result of `raw_rnn` will have the same structure and\n dtypes as `cell.output_size`. Otherwise `emit_ta` will have the same\n structure, shapes (prepended with a `batch_size` dimension), and dtypes\n as `emit_output`. The actual values returned for `emit_output` at this\n initializing call are ignored. Note, this emit structure must be\n consistent across all time steps.\n\n parallel_iterations: (Default: 32). The number of iterations to run in\n parallel. Those operations which do not have any temporal dependency\n and can be run in parallel, will be. This parameter trades off\n time for space. Values >> 1 use more memory but take less time,\n while smaller values use less memory but computations take longer.\n swap_memory: Transparently swap the tensors produced in forward inference\n but needed for back prop from GPU to CPU. This allows training RNNs\n which would typically not fit on a single GPU, with very minimal (or no)\n performance penalty.\n scope: VariableScope for the created subgraph; defaults to \"rnn\".\n\n Returns:\n A tuple `(emit_ta, final_state, final_loop_state)` where:\n\n `emit_ta`: The RNN output `TensorArray`.\n If `loop_fn` returns a (possibly nested) set of Tensors for\n `emit_output` during initialization, (inputs `time = 0`,\n `cell_output = None`, and `loop_state = None`), then `emit_ta` will\n have the same structure, dtypes, and shapes as `emit_output` instead.\n If `loop_fn` returns `emit_output = None` during this call,\n the structure of `cell.output_size` is used:\n If `cell.output_size` is a (possibly nested) tuple of integers\n or `TensorShape` objects, then `emit_ta` will be a tuple having the\n same structure as `cell.output_size`, containing TensorArrays whose\n elements' shapes correspond to the shape data in `cell.output_size`.\n\n `final_state`: The final cell state. If `cell.state_size` is an int, this\n will be shaped `[batch_size, cell.state_size]`. If it is a\n `TensorShape`, this will be shaped `[batch_size] + cell.state_size`.\n If it is a (possibly nested) tuple of ints or `TensorShape`, this will\n be a tuple having the corresponding shapes.\n\n `final_loop_state`: The final loop state as returned by `loop_fn`.\n\n Raises:\n TypeError: If `cell` is not an instance of RNNCell, or `loop_fn` is not\n a `callable`.\n \"\"\"\n\n # pylint: disable=protected-access\n if not isinstance(cell, rnn_cell_impl._RNNCell):\n raise TypeError(\"cell must be an instance of RNNCell\")\n # pylint: enable=protected-access\n if not callable(loop_fn):\n raise TypeError(\"loop_fn must be a callable\")\n\n parallel_iterations = parallel_iterations or 32\n\n # Create a new scope in which the caching device is either\n # determined by the parent scope, or is set to place the cached\n # Variable using the same placement as for the rest of the RNN.\n with vs.variable_scope(scope or \"rnn\") as varscope:\n if varscope.caching_device is None:\n varscope.set_caching_device(lambda op: op.device)\n\n time = constant_op.constant(0, dtype=dtypes.int32)\n (elements_finished, next_input, initial_state, emit_structure,\n init_loop_state) = loop_fn(\n time, None, None, None) # time, cell_output, cell_state, loop_state\n flat_input = nest.flatten(next_input)\n\n # Need a surrogate loop state for the while_loop if none is available.\n loop_state = (init_loop_state if init_loop_state is not None\n else constant_op.constant(0, dtype=dtypes.int32))\n\n input_shape = [input_.get_shape() for input_ in flat_input]\n static_batch_size = input_shape[0][0]\n\n for input_shape_i in input_shape:\n # Static verification that batch sizes all match\n static_batch_size.merge_with(input_shape_i[0])\n\n batch_size = static_batch_size.value\n if batch_size is None:\n batch_size = array_ops.shape(flat_input[0])[0]\n\n nest.assert_same_structure(initial_state, cell.state_size)\n state = initial_state\n flat_state = nest.flatten(state)\n flat_state = [ops.convert_to_tensor(s) for s in flat_state]\n state = nest.pack_sequence_as(structure=state,\n flat_sequence=flat_state)\n\n if emit_structure is not None:\n flat_emit_structure = nest.flatten(emit_structure)\n flat_emit_size = [emit.get_shape() for emit in flat_emit_structure]\n flat_emit_dtypes = [emit.dtype for emit in flat_emit_structure]\n else:\n emit_structure = cell.output_size\n flat_emit_size = nest.flatten(emit_structure)\n flat_emit_dtypes = [flat_state[0].dtype] * len(flat_emit_size)\n\n flat_emit_ta = [\n tensor_array_ops.TensorArray(\n dtype=dtype_i, dynamic_size=True, size=0, name=\"rnn_output_%d\" % i)\n for i, dtype_i in enumerate(flat_emit_dtypes)]\n emit_ta = nest.pack_sequence_as(structure=emit_structure,\n flat_sequence=flat_emit_ta)\n flat_zero_emit = [\n array_ops.zeros(\n _state_size_with_prefix(size_i, prefix=[batch_size]),\n dtype_i)\n for size_i, dtype_i in zip(flat_emit_size, flat_emit_dtypes)]\n zero_emit = nest.pack_sequence_as(structure=emit_structure,\n flat_sequence=flat_zero_emit)\n\n def condition(unused_time, elements_finished, *_):\n return math_ops.logical_not(math_ops.reduce_all(elements_finished))\n\n def body(time, elements_finished, current_input,\n emit_ta, state, loop_state):\n \"\"\"Internal while loop body for raw_rnn.\n\n Args:\n time: time scalar.\n elements_finished: batch-size vector.\n current_input: possibly nested tuple of input tensors.\n emit_ta: possibly nested tuple of output TensorArrays.\n state: possibly nested tuple of state tensors.\n loop_state: possibly nested tuple of loop state tensors.\n\n Returns:\n Tuple having the same size as Args but with updated values.\n \"\"\"\n (next_output, cell_state) = cell(current_input, state)\n\n nest.assert_same_structure(state, cell_state)\n nest.assert_same_structure(cell.output_size, next_output)\n\n next_time = time + 1\n (next_finished, next_input, next_state, emit_output,\n next_loop_state) = loop_fn(\n next_time, next_output, cell_state, loop_state)\n\n nest.assert_same_structure(state, next_state)\n nest.assert_same_structure(current_input, next_input)\n nest.assert_same_structure(emit_ta, emit_output)\n\n # If loop_fn returns None for next_loop_state, just reuse the\n # previous one.\n loop_state = loop_state if next_loop_state is None else next_loop_state\n\n def _copy_some_through(current, candidate):\n \"\"\"Copy some tensors through via array_ops.where.\"\"\"\n current_flat = nest.flatten(current)\n candidate_flat = nest.flatten(candidate)\n # pylint: disable=g-long-lambda,cell-var-from-loop\n result_flat = [\n _on_device(\n lambda: array_ops.where(\n elements_finished, current_i, candidate_i),\n device=candidate_i.op.device)\n for (current_i, candidate_i) in zip(current_flat, candidate_flat)]\n # pylint: enable=g-long-lambda,cell-var-from-loop\n return nest.pack_sequence_as(\n structure=current, flat_sequence=result_flat)\n\n emit_output = _copy_some_through(zero_emit, emit_output)\n next_state = _copy_some_through(state, next_state)\n\n emit_output_flat = nest.flatten(emit_output)\n emit_ta_flat = nest.flatten(emit_ta)\n\n elements_finished = math_ops.logical_or(elements_finished, next_finished)\n\n emit_ta_flat = [\n ta.write(time, emit)\n for (ta, emit) in zip(emit_ta_flat, emit_output_flat)]\n\n emit_ta = nest.pack_sequence_as(\n structure=emit_structure, flat_sequence=emit_ta_flat)\n\n return (next_time, elements_finished, next_input,\n emit_ta, next_state, loop_state)\n\n returned = control_flow_ops.while_loop(\n condition, body, loop_vars=[\n time, elements_finished, next_input,\n emit_ta, state, loop_state],\n parallel_iterations=parallel_iterations,\n swap_memory=swap_memory)\n\n (emit_ta, final_state, final_loop_state) = returned[-3:]\n\n if init_loop_state is None:\n final_loop_state = None\n\n return (emit_ta, final_state, final_loop_state)\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\"\"\"Unit tests of the tfdbg Stepper.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.client import session\nfrom tensorflow.python.debug.lib.stepper import NodeStepper\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.training import gradient_descent\n\n\nclass StepperTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self.a = variables.Variable(2.0, name=\"a\")\n self.b = variables.Variable(3.0, name=\"b\")\n\n self.c = math_ops.multiply(self.a, self.b, name=\"c\") # Should be 6.0.\n self.d = math_ops.multiply(self.a, self.a, name=\"d\") # Should be 4.0.\n\n self.e = math_ops.multiply(self.d, self.c, name=\"e\") # Should be 24.0.\n\n self.f_y = constant_op.constant(0.30, name=\"f_y\")\n self.f = math_ops.div(self.b, self.f_y, name=\"f\") # Should be 10.0.\n\n # The there nodes x, y and z form a graph with \"cross-links\" in. I.e., x\n # and y are both direct inputs to z, but x is also a direct input to y.\n self.x = variables.Variable(2.0, name=\"x\") # Should be 2.0\n self.y = math_ops.negative(self.x, name=\"y\") # Should be -2.0.\n\n self.z = math_ops.multiply(self.x, self.y, name=\"z\") # Should be -4.0.\n\n self.sess = session.Session()\n self.sess.run(variables.global_variables_initializer())\n\n self.sess = session.Session()\n self.sess.run(variables.global_variables_initializer())\n\n def tearDown(self):\n ops.reset_default_graph()\n\n def testContToFetchNotInTransitiveClosureShouldError(self):\n stepper = NodeStepper(self.sess, \"e:0\")\n\n sorted_nodes = stepper.sorted_nodes()\n self.assertEqual(7, len(sorted_nodes))\n self.assertLess(sorted_nodes.index(\"a\"), sorted_nodes.index(\"a/read\"))\n self.assertLess(sorted_nodes.index(\"b\"), sorted_nodes.index(\"b/read\"))\n self.assertLess(sorted_nodes.index(\"a\"), sorted_nodes.index(\"c\"))\n self.assertLess(sorted_nodes.index(\"b\"), sorted_nodes.index(\"c\"))\n self.assertLess(sorted_nodes.index(\"a\"), sorted_nodes.index(\"d\"))\n self.assertLess(sorted_nodes.index(\"d\"), sorted_nodes.index(\"e\"))\n self.assertLess(sorted_nodes.index(\"c\"), sorted_nodes.index(\"e\"))\n\n self.assertSetEqual(\n {\"e:0\", \"d:0\", \"c:0\", \"a/read:0\", \"b/read:0\", \"b:0\", \"a:0\"},\n set(stepper.closure_elements()))\n\n with self.assertRaisesRegexp(\n ValueError,\n \"Target \\\"f:0\\\" is not in the transitive closure for the fetch of the \"\n \"stepper\"):\n stepper.cont(\"f:0\")\n\n def testContToNodeNameShouldReturnTensorvalue(self):\n stepper = NodeStepper(self.sess, \"e:0\")\n\n cont_result = stepper.cont(\"c\")\n self.assertAllClose(6.0, cont_result)\n\n def testUsingNamesNotUsingIntermediateTensors(self):\n stepper = NodeStepper(self.sess, \"e:0\")\n\n # The first cont() call should have used no feeds.\n result = stepper.cont(\"c:0\")\n self.assertAllClose(6.0, result)\n self.assertEqual({}, stepper.last_feed_types())\n\n # The second cont() call should have used the tensor handle from the\n # previous cont() call.\n result = stepper.cont(\"e:0\")\n self.assertAllClose(24.0, result)\n self.assertEqual({\n \"c:0\": NodeStepper.FEED_TYPE_HANDLE\n }, stepper.last_feed_types())\n\n def testUsingNodesNotUsingIntermediateTensors(self):\n stepper = NodeStepper(self.sess, self.e)\n\n # There should be no handles before any cont() calls.\n self.assertEqual([], stepper.handle_names())\n self.assertSetEqual(set(), stepper.handle_node_names())\n\n # Before the cont() call, the stepper should not have access to the value\n # of c:0.\n with self.assertRaisesRegexp(\n ValueError,\n \"This stepper instance does not have access to the value of tensor \"\n \"\\\"c:0\\\"\"):\n stepper.get_tensor_value(\"c:0\")\n\n # Using the node/tensor itself, instead of the name str, should work on\n # cont().\n result = stepper.cont(self.c)\n self.assertAllClose(6.0, result)\n self.assertEqual({}, stepper.last_feed_types())\n\n self.assertEqual([\"c:0\"], stepper.handle_names())\n self.assertEqual({\"c\"}, stepper.handle_node_names())\n\n # After the cont() call, the stepper should have access to the value of c:0\n # via a tensor handle.\n self.assertAllClose(6.0, stepper.get_tensor_value(\"c:0\"))\n\n result = stepper.cont(self.e)\n self.assertAllClose(24.0, result)\n self.assertEqual({\n \"c:0\": NodeStepper.FEED_TYPE_HANDLE\n }, stepper.last_feed_types())\n\n def testIsFeedableShouldGiveCorrectAnswers(self):\n stepper = NodeStepper(self.sess, self.e)\n\n self.assertTrue(stepper.is_feedable(\"a/read:0\"))\n self.assertTrue(stepper.is_feedable(\"b/read:0\"))\n self.assertTrue(stepper.is_feedable(\"c:0\"))\n self.assertTrue(stepper.is_feedable(\"d:0\"))\n\n def testOverrideValue(self):\n stepper = NodeStepper(self.sess, self.e)\n\n result = stepper.cont(self.c)\n self.assertAllClose(6.0, result)\n self.assertEqual({}, stepper.last_feed_types())\n\n # There should be no overrides before any cont() calls.\n self.assertEqual([], stepper.override_names())\n\n # Calling cont() on c again should lead to use of the handle.\n result = stepper.cont(self.c)\n self.assertAllClose(6.0, result)\n self.assertEqual({\n \"c:0\": NodeStepper.FEED_TYPE_HANDLE\n }, stepper.last_feed_types())\n\n # Override c:0.\n stepper.override_tensor(\"c:0\", 7.0)\n\n # After the overriding, calling get_tensor_value() on c:0 should yield the\n # overriding value.\n self.assertEqual(7.0, stepper.get_tensor_value(\"c:0\"))\n\n # Now c:0 should have only an override value, but no cached handle, because\n # the handle should have been invalidated.\n self.assertEqual([], stepper.handle_names())\n self.assertSetEqual(set(), stepper.handle_node_names())\n self.assertEqual([\"c:0\"], stepper.override_names())\n\n # Run a downstream tensor after the value override.\n result = stepper.cont(self.e)\n self.assertAllClose(28.0, result) # Should reflect the overriding value.\n\n # Should use override, instead of the handle.\n self.assertEqual({\n \"c:0\": NodeStepper.FEED_TYPE_OVERRIDE\n }, stepper.last_feed_types())\n\n def testOverrideValueTwice(self):\n stepper = NodeStepper(self.sess, self.e)\n\n # Override once.\n stepper.override_tensor(\"c:0\", 7.0)\n self.assertAllClose(28.0, stepper.cont(self.e))\n self.assertEqual({\n \"c:0\": NodeStepper.FEED_TYPE_OVERRIDE\n }, stepper.last_feed_types())\n\n self.assertEqual([\"e:0\"], stepper.handle_names())\n self.assertSetEqual({\"e\"}, stepper.handle_node_names())\n self.assertEqual([\"c:0\"], stepper.override_names())\n\n # Calling cont(self.e) again. This time the cached tensor handle of e\n # should be used.\n self.assertEqual(28.0, stepper.cont(self.e))\n self.assertEqual({\n \"e:0\": NodeStepper.FEED_TYPE_HANDLE\n }, stepper.last_feed_types())\n\n # Override c again. This should have invalidated the cache for e.\n stepper.override_tensor(\"c:0\", 8.0)\n\n self.assertEqual([], stepper.handle_names())\n self.assertEqual(set(), stepper.handle_node_names())\n self.assertEqual([\"c:0\"], stepper.override_names())\n\n self.assertAllClose(32.0, stepper.cont(self.e))\n self.assertEqual({\n \"c:0\": NodeStepper.FEED_TYPE_OVERRIDE\n }, stepper.last_feed_types())\n\n def testRemoveOverrideValue(self):\n stepper = NodeStepper(self.sess, self.e)\n\n result = stepper.cont(self.c)\n self.assertAllClose(6.0, result)\n self.assertEqual({}, stepper.last_feed_types())\n\n # The previous cont() step should have generated a cached tensor handle.\n self.assertEqual([\"c:0\"], stepper.handle_names())\n self.assertSetEqual({\"c\"}, stepper.handle_node_names())\n\n # Override c:0.\n stepper.override_tensor(\"c:0\", 7.0)\n\n # The overriding should have invalidated the tensor handle.\n self.assertEqual([], stepper.handle_names())\n self.assertSetEqual(set(), stepper.handle_node_names())\n self.assertEqual([\"c:0\"], stepper.override_names())\n\n result = stepper.cont(self.e)\n self.assertAllClose(28.0, result) # Should reflect the overriding value.\n self.assertEqual({\n \"c:0\": NodeStepper.FEED_TYPE_OVERRIDE\n }, stepper.last_feed_types())\n\n # The handle to tensor e:0 should have been cached, even though its\n # transitive closure contains an override.\n self.assertIn(\"e:0\", stepper.handle_names())\n self.assertSetEqual({\"e\"}, stepper.handle_node_names())\n\n # Remove the override.\n stepper.remove_override(\"c:0\")\n # c:0 should not be in the overrides anymore.\n self.assertEqual([], stepper.override_names())\n\n # Removing the override should have invalidated the tensor handle for c.\n self.assertNotIn(\"e:0\", stepper.handle_names())\n self.assertNotIn(\"e\", stepper.handle_node_names())\n\n # Should reflect the non-overriding value.\n self.assertAllClose(24.0, stepper.cont(self.e))\n\n # This time, the handle to tensor e:0 should have been cached again, even\n # thought its transitive closure contains an override.\n self.assertIn(\"e:0\", stepper.handle_names())\n self.assertIn(\"e\", stepper.handle_node_names())\n\n # Calling cont(self.e) again should have used the tensor handle to e:0.\n self.assertAllClose(24.0, stepper.cont(self.e))\n self.assertEqual({\n \"e:0\": NodeStepper.FEED_TYPE_HANDLE\n }, stepper.last_feed_types())\n\n def testOverrideAndContToSameTensor(self):\n stepper = NodeStepper(self.sess, self.e)\n\n result = stepper.cont(self.c)\n self.assertAllClose(6.0, result)\n self.assertEqual({}, stepper.last_feed_types())\n self.assertEqual([\"c:0\"], stepper.handle_names())\n self.assertSetEqual({\"c\"}, stepper.handle_node_names())\n\n self.assertAllClose(6.0, stepper.cont(self.c))\n\n # The last cont() call should use the tensor handle directly.\n self.assertEqual({\n \"c:0\": NodeStepper.FEED_TYPE_HANDLE\n }, stepper.last_feed_types())\n\n # Override c:0.\n stepper.override_tensor(\"c:0\", 7.0)\n\n # As a result of the override, the tensor handle should have been\n # invalidated.\n self.assertEqual([], stepper.handle_names())\n self.assertSetEqual(set(), stepper.handle_node_names())\n\n result = stepper.cont(self.c)\n self.assertAllClose(7.0, result)\n\n self.assertEqual({\n \"c:0\": NodeStepper.FEED_TYPE_OVERRIDE\n }, stepper.last_feed_types())\n\n def testFinalizeWithPreviousOverrides(self):\n stepper = NodeStepper(self.sess, self.e)\n\n stepper.override_tensor(\"a/read:0\", 20.0)\n self.assertEqual([\"a/read:0\"], stepper.override_names())\n\n # Should reflect the overriding value.\n self.assertAllClose(24000.0, stepper.cont(\"e:0\"))\n self.assertEqual({\n \"a/read:0\": NodeStepper.FEED_TYPE_OVERRIDE\n }, stepper.last_feed_types())\n\n # Finalize call should have ignored the overriding value.\n self.assertAllClose(24.0, stepper.finalize())\n\n def testRemoveNonexistentOverrideValue(self):\n stepper = NodeStepper(self.sess, self.e)\n self.assertEqual([], stepper.override_names())\n\n with self.assertRaisesRegexp(\n ValueError, \"No overriding value exists for tensor \\\"c:0\\\"\"):\n stepper.remove_override(\"c:0\")\n\n def testAttemptToOverrideInvalidTensor(self):\n stepper = NodeStepper(self.sess, self.e)\n\n with self.assertRaisesRegexp(ValueError, \"Cannot override tensor \\\"f:0\\\"\"):\n stepper.override_tensor(\"f:0\", 42.0)\n\n def testInvalidOverrideArgumentType(self):\n stepper = NodeStepper(self.sess, self.e)\n\n with self.assertRaisesRegexp(TypeError, \"Expected type str; got type\"):\n stepper.override_tensor(self.a, 42.0)\n\n def testTransitiveClosureWithCrossLinksShouldHaveCorrectOrder(self):\n stepper = NodeStepper(self.sess, \"z:0\")\n\n sorted_nodes = stepper.sorted_nodes()\n self.assertEqual(4, len(sorted_nodes))\n self.assertLess(sorted_nodes.index(\"x\"), sorted_nodes.index(\"x/read\"))\n self.assertLess(sorted_nodes.index(\"x\"), sorted_nodes.index(\"y\"))\n self.assertLess(sorted_nodes.index(\"x\"), sorted_nodes.index(\"z\"))\n self.assertLess(sorted_nodes.index(\"y\"), sorted_nodes.index(\"z\"))\n\n def testNodeStepperConstructorShouldAllowListOrTupleOrDictOfFetches(self):\n for i in range(6):\n if i == 0:\n fetches = [self.e, [self.f, self.z]]\n elif i == 1:\n fetches = (self.e, (self.f, self.z))\n elif i == 2:\n fetches = {\"e\": self.e, \"fz\": {\"f\": self.f, \"z\": self.z}}\n elif i == 3:\n fetches = [\"e:0\", [\"f:0\", \"z:0\"]]\n elif i == 4:\n fetches = (\"e:0\", (\"f:0\", \"z:0\"))\n elif i == 5:\n fetches = {\"e\": \"e:0\", \"fz\": {\"f\": \"f:0\", \"z\": \"z:0\"}}\n\n stepper = NodeStepper(self.sess, fetches)\n\n sorted_nodes = stepper.sorted_nodes()\n self.assertEqual(13, len(sorted_nodes))\n\n # Check the topological order of the sorted nodes.\n self.assertLess(sorted_nodes.index(\"x\"), sorted_nodes.index(\"x/read\"))\n self.assertLess(sorted_nodes.index(\"x\"), sorted_nodes.index(\"y\"))\n self.assertLess(sorted_nodes.index(\"x\"), sorted_nodes.index(\"z\"))\n self.assertLess(sorted_nodes.index(\"y\"), sorted_nodes.index(\"z\"))\n\n self.assertLess(sorted_nodes.index(\"a\"), sorted_nodes.index(\"a/read\"))\n self.assertLess(sorted_nodes.index(\"b\"), sorted_nodes.index(\"b/read\"))\n self.assertLess(sorted_nodes.index(\"a\"), sorted_nodes.index(\"c\"))\n self.assertLess(sorted_nodes.index(\"b\"), sorted_nodes.index(\"c\"))\n self.assertLess(sorted_nodes.index(\"a\"), sorted_nodes.index(\"d\"))\n self.assertLess(sorted_nodes.index(\"d\"), sorted_nodes.index(\"e\"))\n self.assertLess(sorted_nodes.index(\"c\"), sorted_nodes.index(\"e\"))\n self.assertLess(sorted_nodes.index(\"b\"), sorted_nodes.index(\"f\"))\n self.assertLess(sorted_nodes.index(\"f_y\"), sorted_nodes.index(\"f\"))\n\n closure_elements = stepper.closure_elements()\n self.assertIn(\"x/read:0\", closure_elements)\n self.assertIn(\"e:0\", closure_elements)\n self.assertIn(\"f:0\", closure_elements)\n\n self.assertEqual([0], stepper.output_slots_in_closure(\"x/read\"))\n self.assertEqual([0], stepper.output_slots_in_closure(\"e\"))\n self.assertEqual([0], stepper.output_slots_in_closure(\"f\"))\n\n result = stepper.finalize()\n if i == 0 or i == 1 or i == 3 or i == 4:\n self.assertAllClose(24.0, result[0])\n self.assertAllClose(10.0, result[1][0])\n self.assertAllClose(-4.0, result[1][1])\n elif i == 2 or i == 5:\n self.assertAllClose(24.0, result[\"e\"])\n self.assertAllClose(10.0, result[\"fz\"][\"f\"])\n self.assertAllClose(-4.0, result[\"fz\"][\"z\"])\n\n\nclass StepperTestWithPlaceHolders(test_util.TensorFlowTestCase):\n\n def setUp(self):\n self.ph0 = array_ops.placeholder(dtypes.float32, shape=(2, 2), name=\"ph0\")\n self.ph1 = array_ops.placeholder(dtypes.float32, shape=(2, 1), name=\"ph1\")\n\n self.x = math_ops.matmul(self.ph0, self.ph1, name=\"x\")\n self.y = math_ops.add(self.x, self.ph1, name=\"y\")\n\n self.sess = session.Session()\n\n def tearDown(self):\n ops.reset_default_graph()\n\n def testGetTensorValueWorksOnPlaceholder(self):\n stepper = NodeStepper(\n self.sess,\n self.y,\n feed_dict={\n self.ph0: [[1.0, 2.0], [-3.0, 5.0]],\n self.ph1: [[-1.0], [0.5]]\n })\n\n self.assertAllClose([[1.0, 2.0], [-3.0, 5.0]],\n stepper.get_tensor_value(\"ph0\"))\n self.assertAllClose([[1.0, 2.0], [-3.0, 5.0]],\n stepper.get_tensor_value(\"ph0:0\"))\n with self.assertRaisesRegexp(\n KeyError, r\"The name 'ph0:1' refers to a Tensor which does not exist\"):\n stepper.get_tensor_value(\"ph0:1\")\n\n def testIsPlaceholdersShouldGiveCorrectAnswers(self):\n stepper = NodeStepper(self.sess, self.y)\n\n self.assertTrue(stepper.is_placeholder(self.ph0.name))\n self.assertTrue(stepper.is_placeholder(self.ph1.name))\n\n self.assertFalse(stepper.is_placeholder(self.x.name))\n self.assertFalse(stepper.is_placeholder(self.y.name))\n\n with self.assertRaisesRegexp(ValueError,\n \"A is not in the transitive closure\"):\n self.assertFalse(stepper.is_placeholder(\"A\"))\n\n def testPlaceholdersShouldGiveCorrectAnswers(self):\n stepper = NodeStepper(self.sess, self.y)\n\n self.assertSetEqual({\"ph0\", \"ph1\"}, set(stepper.placeholders()))\n\n def testContWithPlaceholders(self):\n stepper = NodeStepper(\n self.sess,\n self.y,\n feed_dict={\n self.ph0: [[1.0, 2.0], [-3.0, 5.0]],\n self.ph1: [[-1.0], [0.5]]\n })\n\n self.assertEqual(4, len(stepper.sorted_nodes()))\n self.assertSetEqual({\"ph0:0\", \"ph1:0\", \"x:0\", \"y:0\"},\n set(stepper.closure_elements()))\n\n result = stepper.cont(self.x)\n self.assertAllClose([[0.0], [5.5]], result)\n self.assertEqual({\n \"ph0:0\": NodeStepper.FEED_TYPE_CLIENT,\n \"ph1:0\": NodeStepper.FEED_TYPE_CLIENT,\n }, stepper.last_feed_types())\n\n self.assertEqual([\"x:0\"], stepper.handle_names())\n self.assertSetEqual({\"x\"}, stepper.handle_node_names())\n\n result = stepper.cont(self.y)\n self.assertAllClose([[-1.0], [6.0]], result)\n self.assertEqual({\n \"x:0\": NodeStepper.FEED_TYPE_HANDLE,\n \"ph1:0\": NodeStepper.FEED_TYPE_CLIENT,\n }, stepper.last_feed_types())\n\n def testAttemptToContToPlaceholderWithTensorFeedKeysShouldWork(self):\n \"\"\"Continuing to a placeholder should be allowed, using client feed.\"\"\"\n\n ph0_feed = [[1.0, 2.0], [-3.0, 5.0]]\n ph1_feed = [[-1.0], [0.5]]\n stepper = NodeStepper(\n self.sess, self.y, feed_dict={\n self.ph0: ph0_feed,\n self.ph1: ph1_feed,\n })\n\n self.assertAllClose(ph0_feed, stepper.cont(self.ph0))\n self.assertEqual({\n self.ph0.name: NodeStepper.FEED_TYPE_CLIENT\n }, stepper.last_feed_types())\n\n self.assertAllClose(ph1_feed, stepper.cont(self.ph1))\n self.assertEqual({\n self.ph1.name: NodeStepper.FEED_TYPE_CLIENT\n }, stepper.last_feed_types())\n\n ph0_node = self.sess.graph.as_graph_element(\"ph0\")\n self.assertAllClose(ph0_feed, stepper.cont(ph0_node))\n self.assertEqual({\n self.ph0.name: NodeStepper.FEED_TYPE_CLIENT\n }, stepper.last_feed_types())\n\n self.assertAllClose([[-1.0], [6.0]], stepper.finalize())\n\n def testAttemptToContToPlaceholderWithTensorNameFeedKeysShouldWork(self):\n\n ph0_feed = [[1.0, 2.0], [-3.0, 5.0]]\n ph1_feed = [[-1.0], [0.5]]\n stepper = NodeStepper(\n self.sess,\n self.y,\n feed_dict={\n self.ph0.name: ph0_feed,\n self.ph1.name: ph1_feed,\n })\n\n self.assertAllClose(ph0_feed, stepper.cont(self.ph0))\n self.assertEqual({\n self.ph0.name: NodeStepper.FEED_TYPE_CLIENT\n }, stepper.last_feed_types())\n\n self.assertAllClose(ph1_feed, stepper.cont(self.ph1))\n self.assertEqual({\n self.ph1.name: NodeStepper.FEED_TYPE_CLIENT\n }, stepper.last_feed_types())\n\n ph0_node = self.sess.graph.as_graph_element(\"ph0\")\n self.assertAllClose(ph0_feed, stepper.cont(ph0_node))\n self.assertEqual({\n self.ph0.name: NodeStepper.FEED_TYPE_CLIENT\n }, stepper.last_feed_types())\n\n self.assertAllClose([[-1.0], [6.0]], stepper.finalize())\n\n\nclass StepperBackwardRunTest(test_util.TensorFlowTestCase):\n\n def setUp(self):\n \"\"\"Test setup.\n\n Structure of the forward graph:\n f\n | |\n ----- -----\n | |\n d e\n | | | |\n --- --------- ---\n | | |\n a b c\n\n Construct a backward graph using the GradientDescentOptimizer.\n \"\"\"\n\n self.a = variables.Variable(1.0, name=\"a\")\n self.b = variables.Variable(2.0, name=\"b\")\n self.c = variables.Variable(4.0, name=\"c\")\n self.d = math_ops.multiply(self.a, self.b, name=\"d\")\n self.e = math_ops.multiply(self.b, self.c, name=\"e\")\n self.f = math_ops.multiply(self.d, self.e, name=\"f\")\n\n # Gradient descent optimizer that minimizes g.\n gradient_descent.GradientDescentOptimizer(0.01).minimize(\n self.f, name=\"optim\")\n\n self.sess = session.Session()\n self.sess.run(variables.global_variables_initializer())\n\n def tearDown(self):\n ops.reset_default_graph()\n\n def testContToUpdateA(self):\n stepper = NodeStepper(self.sess, \"optim\")\n\n result = stepper.cont(\"a:0\")\n self.assertAllClose(1.0, result)\n self.assertEqual({}, stepper.last_feed_types())\n\n result = stepper.cont(\"optim/learning_rate:0\")\n self.assertAllClose(0.01, result)\n self.assertEqual({}, stepper.last_feed_types())\n\n # Before any cont calls on ApplyGradientDescent, there should be no \"dirty\"\n # variables.\n self.assertEqual(set(), stepper.dirty_variables())\n\n # First, all the two control inputs to optim.\n result = stepper.cont(\"optim/update_a/ApplyGradientDescent\")\n\n # Now variable a should have been marked as dirty due to the update\n # by optim/update_a/ApplyGradientDescent.\n self.assertEqual({\"a:0\"}, stepper.dirty_variables())\n self.assertIsNone(result)\n self.assertEqual({\n \"optim/learning_rate:0\": NodeStepper.FEED_TYPE_HANDLE\n }, stepper.last_feed_types())\n\n # Check that Variable \"a\" has been updated properly, but \"b\", \"c\" and \"d\"\n # remain the same.\n # For backprop on Variable a:\n # Because f = a * b * b * c, df / da = b * b * c.\n # 1.0 - learning_rate * b * b * c\n # = 1.0 - 0.01 * 2.0 * 2.0 * 4.0 = 0.84.\n self.assertAllClose(0.84, self.sess.run(self.a))\n self.assertAllClose(2.0, self.sess.run(self.b))\n self.assertAllClose(4.0, self.sess.run(self.c))\n\n def testContToUpdateB(self):\n stepper = NodeStepper(self.sess, \"optim\")\n\n result = stepper.cont(\"optim/update_b/ApplyGradientDescent\")\n self.assertIsNone(result)\n self.assertEqual(set([\"b:0\"]), stepper.dirty_variables())\n\n # For backprop on Variable b:\n # Because f = a * b * b * c, df / da = 2 * a * b * c.\n # 2.0 - learning_rate * 2 * a * b * c\n # = 2.0 - 0.01 * 2 * 1.0 * 2.0 * 4.0 = 1.84\n self.assertAllClose(1.0, self.sess.run(self.a))\n self.assertAllClose(1.84, self.sess.run(self.b))\n self.assertAllClose(4.0, self.sess.run(self.c))\n\n def testContAfterUpdateWithoutRestoringVariableValue(self):\n stepper = NodeStepper(self.sess, \"optim\")\n\n # First, update Variable a from 1.0 to 0.84.\n result = stepper.cont(\n \"optim/update_a/ApplyGradientDescent\", restore_variable_values=True)\n self.assertIsNone(result)\n self.assertEqual(set([\"a:0\"]), stepper.dirty_variables())\n self.assertAllClose(0.84, self.sess.run(self.a))\n self.assertAllClose(2.0, self.sess.run(self.b))\n self.assertAllClose(4.0, self.sess.run(self.c))\n\n # Second, update Variable b without the default restore_variable_values.\n result = stepper.cont(\n \"optim/update_b/ApplyGradientDescent\", restore_variable_values=False)\n self.assertIsNone(result)\n # For the backprop on Variable b under the updated value of a:\n # 2.0 - learning_rate * 2 * a' * b * c\n # = 2.0 - 0.01 * 2 * 0.84 * 2.0 * 4.0 = 1.8656\n self.assertAllClose(0.84, self.sess.run(self.a))\n self.assertAllClose(1.8656, self.sess.run(self.b))\n self.assertAllClose(4.0, self.sess.run(self.c))\n\n def testUpdateTwiceRestoreVariable(self):\n stepper = NodeStepper(self.sess, \"optim\")\n\n result = stepper.cont(\n \"optim/update_a/ApplyGradientDescent\", restore_variable_values=True)\n self.assertIsNone(result)\n self.assertEqual({\"a:0\"}, stepper.dirty_variables())\n\n result = stepper.cont(\n \"optim/update_b/ApplyGradientDescent\", restore_variable_values=True)\n self.assertIsNone(result)\n # Variables a and c should have been restored and hence no longer dirty.\n # Variable b should have been marked as dirty.\n self.assertEqual({\"b:0\"}, stepper.dirty_variables())\n\n # The result of the update should be identitcal to as if only update_b is\n # run.\n self.assertAllClose(1.0, self.sess.run(self.a))\n self.assertAllClose(1.84, self.sess.run(self.b))\n self.assertAllClose(4.0, self.sess.run(self.c))\n\n def testSelectiveHandleUsageDependingOnTransitiveCleanliness(self):\n \"\"\"Test tensor handlers are using only during clean transitive closure.\n\n \"clean\" means no Variables have been updated by preceding cont() calls.\n \"\"\"\n\n stepper = NodeStepper(self.sess, \"optim\")\n\n # First, call cont() on the two tensors on the intermediate level: e and f.\n result = stepper.cont(\"d:0\")\n self.assertAllClose(2.0, result)\n self.assertEqual({}, stepper.last_feed_types())\n self.assertEqual(set(), stepper.dirty_variables())\n\n # The cont call above should have restored Variable \"b\".\n result = stepper.cont(\"e:0\")\n self.assertAllClose(8.0, result)\n self.assertEqual({}, stepper.last_feed_types())\n self.assertEqual(set(), stepper.dirty_variables())\n\n # Now run update_a, so as to let Variable a be diry.\n result = stepper.cont(\n \"optim/update_a/ApplyGradientDescent\", restore_variable_values=True)\n self.assertIsNone(result)\n self.assertEqual({\"a:0\"}, stepper.dirty_variables())\n\n # Now, run update_b.\n result = stepper.cont(\n \"optim/update_b/ApplyGradientDescent\", restore_variable_values=True)\n self.assertIsNone(result)\n\n # The last cont() run should have use the handle of tensor e, but not the\n # handle of tensor d, because the transitive closure of e is clean, whereas\n # that of d is dirty due to the update to a in the previous cont() call.\n self.assertEqual({\n \"e:0\": NodeStepper.FEED_TYPE_HANDLE\n }, stepper.last_feed_types())\n\n # The result of the update_b should be identical to as if no other\n # update_* cont() calls have occurred before.\n self.assertAllClose(1.0, self.sess.run(self.a))\n self.assertAllClose(1.84, self.sess.run(self.b))\n self.assertAllClose(4.0, self.sess.run(self.c))\n\n def testRestoreVariableValues(self):\n \"\"\"Test restore_variable_values() restores the old values of variables.\"\"\"\n\n stepper = NodeStepper(self.sess, \"optim\")\n\n stepper.cont(\n \"optim/update_b/ApplyGradientDescent\", restore_variable_values=True)\n self.assertAllClose(1.84, self.sess.run(self.b))\n\n stepper.restore_variable_values()\n self.assertAllClose(2.0, self.sess.run(self.b))\n\n def testFinalize(self):\n \"\"\"Test finalize() to restore variables and run the original fetch.\"\"\"\n\n stepper = NodeStepper(self.sess, \"optim\")\n\n # Invoke update_b before calling finalize.\n stepper.cont(\n \"optim/update_b/ApplyGradientDescent\", restore_variable_values=True)\n\n result = stepper.finalize()\n self.assertIsNone(result)\n\n # The results of the Variable updates should be the same as if no cont()\n # call has occurred on update_b.\n self.assertAllClose(0.84, self.sess.run(self.a))\n self.assertAllClose(1.84, self.sess.run(self.b))\n self.assertAllClose(3.96, self.sess.run(self.c))\n\n def testOverrideThenContToUpdate(self):\n \"\"\"Test cont() to update nodes after overriding tensor values.\"\"\"\n\n stepper = NodeStepper(self.sess, \"optim\")\n\n result = stepper.cont(\"d:0\")\n self.assertAllClose(2.0, result)\n self.assertEqual({}, stepper.last_feed_types())\n self.assertEqual(set(), stepper.dirty_variables())\n self.assertEqual([\"d:0\"], stepper.handle_names())\n self.assertSetEqual({\"d\"}, stepper.handle_node_names())\n\n # Override the value from 1.0 to 10.0.\n stepper.override_tensor(\"a/read:0\", 10.0)\n\n self.assertEqual([\"a/read:0\"], stepper.override_names())\n\n result = stepper.cont(\n \"optim/update_c/ApplyGradientDescent\", restore_variable_values=True)\n self.assertIsNone(result)\n\n # The last cont() call should have not used the tensor handle to d:0,\n # because the transitive closure of d:0 contains an override tensor.\n self.assertEqual({\n \"a/read:0\": NodeStepper.FEED_TYPE_OVERRIDE\n }, stepper.last_feed_types())\n\n # The tensor handle to d:0 should have been removed due to the dirty\n # transitive closure.\n self.assertEqual([], stepper.handle_names())\n self.assertSetEqual(set(), stepper.handle_node_names())\n\n # For this backprop on c, the overriding value of a/read:0 should have been\n # used:\n # 4.0 - learning_rate * a * b * b\n # = 4.0 - 0.01 * 10.0 * 2.0 * 2.0 = 3.6.\n self.assertAllClose(3.6, self.sess.run(self.c))\n\n # Now remove the overriding value of a/read:0.\n stepper.remove_override(\"a/read:0\")\n self.assertEqual([], stepper.override_names())\n\n # Obtain the tensor handle to d:0 again.\n result = stepper.cont(\"d:0\")\n self.assertAllClose(2.0, result)\n self.assertEqual([\"d:0\"], stepper.handle_names())\n self.assertSetEqual({\"d\"}, stepper.handle_node_names())\n\n # Then call update_c again, without restoring c.\n result = stepper.cont(\n \"optim/update_c/ApplyGradientDescent\", restore_variable_values=False)\n self.assertIsNone(result)\n\n # This time, the d:0 tensor handle should have been used, because its\n # transitive closure is clean.\n self.assertEqual({\n \"d:0\": NodeStepper.FEED_TYPE_HANDLE\n }, stepper.last_feed_types())\n\n # For this backprop on c, the overriding value of a/read:0 should have been\n # used:\n # 3.6 - learning_rate * a * b * b\n # = 3.6 - 0.01 * 1.0 * 2.0 * 2.0 = 3.56.\n self.assertAllClose(3.56, self.sess.run(self.c))\n\n def testContToNodeWithOutputTensors(self):\n \"\"\"cont() to an op should cache its output tensors if appropriate.\"\"\"\n\n stepper = NodeStepper(self.sess, \"optim\")\n\n # In the transitive closure of the stepper, look for an op of which the\n # output tensor also is in the transitive closure.\n # Do not assume a specific op, e.g., \"\"gradients/e_grad/Reshape_1\",\n # because it may vary between builds.\n closure_elements = stepper.closure_elements()\n op_with_output_in_closure = None\n for element_name in closure_elements:\n if element_name + \":0\" in closure_elements:\n op_with_output_in_closure = str(element_name)\n break\n\n self.assertEqual([0],\n stepper.output_slots_in_closure(op_with_output_in_closure))\n\n self.assertIsNotNone(op_with_output_in_closure)\n output_tensor = op_with_output_in_closure + \":0\"\n\n # The op \"gradients/?_grad/Reshape_1\" is in the transitive closure of the\n # stepper, because it is the control input to another o. However, its\n # output tensor \"gradients/?_grad/Reshape_1:0\" is also in the transitive\n # closure, because it is the (non-control) input of certain ops. Calling\n # cont() on the op should lead to the caching of the tensor handle for\n # the output tensor.\n stepper.cont(op_with_output_in_closure)\n\n self.assertEqual([output_tensor], stepper.handle_names())\n self.assertSetEqual({op_with_output_in_closure},\n stepper.handle_node_names())\n\n # Do a cont() call that uses the cached tensor of\n # \"gradients/?_grad/Reshape_1:0\".\n stepper.cont(output_tensor)\n self.assertEqual({\n output_tensor: NodeStepper.FEED_TYPE_HANDLE\n }, stepper.last_feed_types())\n\n\nif __name__ == \"__main__\":\n googletest.main()\n", "# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\"\"\"Python front-end supports for functions.\n\nNOTE: functions are currently experimental and subject to change!\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport hashlib\nimport inspect\nimport re\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import function_pb2\nfrom tensorflow.core.framework import op_def_pb2\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import op_def_registry\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.util import compat\n\n\ndef _make_argname_from_tensor_name(name):\n return re.sub(\":0$\", \"\", name).replace(\":\", \"_o\")\n\n\ndef _tensor_to_argdef(t, name=None, used_names=None):\n \"\"\"Convert tensor t to an argdef, with a specified name or a unique name.\"\"\"\n arg = op_def_pb2.OpDef.ArgDef()\n if name is None:\n arg.name = _make_argname_from_tensor_name(t.name)\n if used_names is not None:\n if arg.name in used_names:\n i = 0\n while True:\n new_name = \"%s_U%d\" % (arg.name, i)\n if new_name not in used_names:\n arg.name = new_name\n break\n i += 1\n used_names.add(arg.name)\n else:\n arg.name = name\n arg.type = t.dtype.as_datatype_enum\n return arg\n\n\ndef _get_node_def(op):\n return op._node_def # pylint: disable=protected-access\n\n\ndef _get_op_def(op):\n # pylint: disable=protected-access\n if hasattr(op, \"_sig\"):\n return getattr(op, \"_sig\")\n else:\n return op_def_registry.get_registered_ops()[op.type]\n # pylint: enable=protected-access\n\n\ndef _is_in_placeholders(op, func_arg_placeholders):\n return op.values() and (op.values()[0].name in func_arg_placeholders)\n\n\ndef _create_input_dict(function_graph, func_arg_placeholders):\n \"\"\"Create a mapping from graph tensor names to function tensor names.\"\"\"\n input_dict = {}\n for op in function_graph.get_operations():\n if _is_in_placeholders(op, func_arg_placeholders):\n input_dict[op.values()[0].name] = op.values()[0].name\n input_dict[op.name] = op.name\n else:\n op_def = _get_op_def(op)\n attrs = _get_node_def(op).attr\n o = 0\n for arg_def in op_def.output_arg:\n if arg_def.number_attr:\n num = attrs[arg_def.number_attr].i\n elif arg_def.type_list_attr:\n num = len(attrs[arg_def.type_list_attr].list.type)\n else:\n num = 1\n for i in range(num):\n result = \"%s:%s:%d\" % (op.name, arg_def.name, i)\n input_dict[op.values()[o].name] = result\n if o == 0:\n input_dict[op.name] = result\n o += 1\n return input_dict\n\n\ndef _add_op_node(op, func, input_dict):\n \"\"\"Converts an op to a function def node and add it to `func`.\"\"\"\n # Add an entry in func.node_def\n\n # Note that extend() makes a copy in this case, see:\n # https://developers.google.com/protocol-buffers/docs/reference/python-generated#repeated-message-fields\n func.node_def.extend([_get_node_def(op)])\n node_def = func.node_def[-1]\n for i in range(len(node_def.input)):\n if not node_def.input[i].startswith(\"^\"):\n assert node_def.input[i] in input_dict, (\n \"%s missing from %s\" % (node_def.input[i], input_dict.items()))\n node_def.input[i] = input_dict[node_def.input[i]]\n\n\ndef _graph_to_function_def(graph, inputs, outputs, out_names=None):\n \"\"\"Returns `graph` as a `FunctionDef` protocol buffer.\n\n This method creates a [`FunctionDef`](\n https://www.tensorflow.org/code/tensorflow/core/framework/function.proto)\n protocol buffer that contains all the ops present in the graph. The\n graph effectively becomes the body of the function.\n\n The arguments `inputs` and `outputs` will be listed as the inputs\n and outputs tensors of the function. They must be lists of\n tensors present in the graph. The lists can optionally be empty.\n\n Args:\n graph: Graph.\n inputs: List of tensors. Inputs to the function.\n outputs: List of tensors. Outputs of the function.\n out_names: Optional list of string names for the outputs.\n\n Returns:\n A FunctionDef protocol buffer.\n\n Raises:\n ValueError: if out_names is specified and the wrong length.\n \"\"\"\n func = function_pb2.FunctionDef()\n func.signature.name = \"_\"\n used_names = set()\n func.signature.input_arg.extend([_tensor_to_argdef(i, used_names=used_names)\n for i in inputs])\n if out_names is None:\n used_names = set()\n func.signature.output_arg.extend([\n _tensor_to_argdef(o, used_names=used_names) for o in outputs])\n elif len(outputs) != len(out_names):\n raise ValueError(\n \"Length of out_names (%d) does not match number of outputs (%d): %s\" %\n (len(out_names), len(outputs), \", \".join(out_names)))\n elif len(out_names) != len(set(out_names)):\n raise ValueError(\n \"Must not have duplicates in out_names: %s\" % \", \".join(out_names))\n else:\n func.signature.output_arg.extend([\n _tensor_to_argdef(o, name=n) for o, n in zip(outputs, out_names)])\n func_arg_placeholders = set([i.name for i in inputs])\n input_dict = _create_input_dict(graph, func_arg_placeholders)\n\n for op in graph.get_operations():\n if _is_in_placeholders(op, func_arg_placeholders):\n continue\n _add_op_node(op, func, input_dict)\n\n if out_names is None:\n for index, o in enumerate(outputs):\n k = func.signature.output_arg[index].name\n func.ret[k] = input_dict[o.name]\n else:\n for o, n in zip(outputs, out_names):\n func.ret[n] = input_dict[o.name]\n\n return func\n\n\ndef _parse_kwargs_as_attrs(**kwargs):\n \"\"\"Parses **kwargs into a node's attributes.\"\"\"\n attrs = {}\n\n noinline = kwargs.pop(\"noinline\", None)\n if noinline is not None:\n attrs[\"_noinline\"] = attr_value_pb2.AttrValue(b=bool(noinline))\n\n compiled = kwargs.pop(\"compiled\", None)\n if compiled is not None:\n attrs[\"_XlaCompile\"] = attr_value_pb2.AttrValue(b=bool(compiled))\n\n if kwargs:\n raise ValueError(\"Unknown keyword arguments: %s\" % kwargs.keys())\n return attrs\n\n\ndef _call(sig, *inputs, **kwargs):\n \"\"\"Adds a node calling a function.\n\n This adds a `call` op to the default graph that calls the function\n of signature `sig`, passing the tensors in `inputs` as arguments.\n It returns the outputs of the call, which are one or more tensors.\n\n `sig` is OpDefArg.a `_DefinedFunction` object.\n\n You can pass an optional keyword parameter `name=string` to name the\n added operation.\n\n You can pass an optional keyword parameter `noinline=True|False` to\n instruct the runtime not to inline the function body into the call\n site.\n\n Args:\n sig: OpDefArg. The signature of the function.\n *inputs: arguments to the function.\n **kwargs: Optional keyword arguments. Can only contain 'name' or\n 'noinline'.\n\n Returns:\n A Tensor if the function returns a single value; a list of Tensors\n if the functio returns multiple value; the Operation if the function\n returns no values.\n\n Raises:\n ValueError: if the arguments are invalid.\n \"\"\"\n if len(inputs) != len(sig.input_arg):\n raise ValueError(\"Expected number of arguments: %d, received: %d\" %\n (len(sig.input_arg), len(inputs)))\n name = kwargs.pop(\"name\", None)\n attrs = _parse_kwargs_as_attrs(**kwargs)\n g = ops.get_default_graph()\n func_name = sig.name\n output_types = [dtypes.DType(x.type) for x in sig.output_arg]\n with ops.name_scope(name, func_name, inputs) as name:\n op = g.create_op(\n func_name,\n list(inputs),\n output_types,\n name=name,\n attrs=attrs,\n compute_shapes=False)\n setattr(op, \"_sig\", sig) # Remember the signature.\n if op.outputs:\n if len(op.outputs) == 1:\n return op.outputs[0]\n else:\n return tuple(op.outputs)\n else:\n return op\n\n\ndef _get_func_name(func):\n if callable(func):\n if inspect.isfunction(func):\n return func.__name__\n elif inspect.ismethod(func):\n return \"%s.%s\" % (func.__self__.__name__, func.__name__)\n else: # Probably a class instance with __call__\n return type(func)\n else:\n raise ValueError(\"Argument must be callable\")\n\n\nclass _FuncGraph(ops.Graph):\n \"\"\"A helper for construction a function.\n\n _FuncGraph overrides ops.Graph's create_op() so that we can keep\n track of every inputs into every op created inside the function. If\n any input is from other graphs, we keep track of it in self.capture\n and substitue the input with a place holder.\n\n Each captured input's corresponding place holder is converted into a\n function argument and the caller passes in the captured tensor.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(_FuncGraph, self).__init__(*args, **kwargs)\n self._building_function = True\n self._outer_graph = ops.get_default_graph()\n self._vscope = vs.get_variable_scope()\n self._old_custom_getter = self._vscope.custom_getter\n self._captured = {}\n self.extra_inputs = []\n self.extra_args = []\n self.extra_vars = []\n\n def getvar(self,\n getter,\n name,\n shape=None,\n dtype=None,\n initializer=None,\n trainable=True,\n collections=None,\n **kwargs):\n \"\"\"A custom variable getter.\"\"\"\n # Here, we switch the default graph to the outer graph and ask the\n # variable scope in which the function is defined to give us the\n # variable. The variable is stashed in extra_vars and returned to\n # the caller.\n #\n # We capture these variables so that the variable definition is\n # hoisted upward to the outer most graph.\n with self._outer_graph.as_default():\n # pylint: disable=protected-access\n var = self._vscope.get_variable(\n vs._get_default_variable_store(),\n name,\n shape=shape,\n dtype=dtype,\n initializer=initializer,\n trainable=trainable,\n collections=collections)\n self.extra_vars.append(var)\n return var\n\n def create_op(self, op_type, inputs, data_types, **kwargs):\n for i, x in enumerate(inputs):\n if x.graph is not self:\n # Referring to a tensor from other graph.\n if x in self._captured:\n # Captured already.\n inputs[i] = self._captured[x]\n else:\n # Substitute with a placeholder.\n self.extra_inputs.append(x)\n ph = array_ops.placeholder(x.dtype, shape=x.get_shape())\n inputs[i] = ph\n self._captured[x] = ph\n self.extra_args.append(ph)\n return super(_FuncGraph, self).create_op(op_type, inputs, data_types,\n **kwargs)\n\n\ndef get_extra_vars():\n \"\"\"Returns the captured variables by the function.\n\n Returns:\n If the default graph is being used to define a function, the\n returned list of variables are those created inside the function\n body so far. Otherwise, returns an empty list.\n \"\"\"\n g = ops.get_default_graph()\n if isinstance(g, _FuncGraph):\n return g.extra_vars\n else:\n return []\n\n\ndef get_extra_inputs():\n \"\"\"Returns the captured input tensors by the function.\n\n Returns:\n If the default graph is being used to define a function, the\n returned list of tensors are those accessed inside the function body\n but defined outside the function body so far. Otherwise, returns an\n empty list.\n \"\"\"\n g = ops.get_default_graph()\n if isinstance(g, _FuncGraph):\n return g.extra_inputs\n else:\n return []\n\n\ndef get_extra_args():\n \"\"\"Returns the corresponding function arguments for the captured inputs.\n\n Returns:\n If the default graph is being used to define a function, the\n returned list of place holders are those used inside the function\n body corresponding those returned by get_extra_inputs(). Otherwise,\n returns an empty list.\n \"\"\"\n g = ops.get_default_graph()\n if isinstance(g, _FuncGraph):\n return g.extra_args\n else:\n return []\n\n\nclass _DefinedFunction(object):\n \"\"\"_DefinedFunction encapsulates a function definition and its properties.\n\n Attributes:\n name: The function name.\n definition: The definition of this function. A FunctionDef proto.\n grad_func_name: If not None, the name of this function's gradient function.\n python_grad_func: A python callable implementing the gradient of\n the function python-side.\n \"\"\"\n\n def __init__(self,\n func,\n argnames,\n input_types,\n func_name=None,\n grad_func=None,\n python_grad_func=None,\n out_names=None,\n **kwargs):\n \"\"\"Creates _DefinedFunction.\n\n Args:\n func: A python callable which constructs a tf function body.\n argnames: A list of strings for function argument names.\n input_types: The function's argument types. Can be a tuple, list of\n tf data types.\n func_name: The function name. Defaults to None, in which derives from\n 'func'.\n grad_func: This function's gradient function, if not None. Defaults\n to None.\n python_grad_func: A python callable implementing the gradient of\n the function python-side.\n out_names: An optional list of strings for the function return value\n names.\n **kwargs: The keyword arguments. **kwargs is passed to every call\n site of this function.\n\n Raises:\n ValueError: The function definition is invalid.\n\n \"\"\"\n self._func = func\n self._input_types = input_types\n self._func_name = func_name\n self._grad_func = grad_func\n self._python_grad_func = python_grad_func\n self._out_names = out_names\n self._extra_kwargs = kwargs\n self._definition = None # Constructed lazily.\n\n self._args = []\n assert isinstance(input_types, (list, tuple))\n for i in range(len(input_types)):\n argname = argnames[i] if i < len(argnames) else (\"arg%d\" % i)\n argtype = input_types[i]\n self._args.append((argname, argtype))\n\n @property\n def name(self):\n \"\"\"Function name.\"\"\"\n self._create_definition_if_needed()\n return self._func_name\n\n @property\n def definition(self):\n \"\"\"Function definition proto.\"\"\"\n self._create_definition_if_needed()\n return self._definition\n\n def set_grad_func(self, grad_func):\n \"\"\"Specifies the gradient function of this function.\"\"\"\n assert not self._grad_func\n assert isinstance(grad_func, _DefinedFunction)\n self._grad_func = grad_func\n\n @property\n def grad_func_name(self):\n \"\"\"Its gradient function's name.\"\"\"\n return self._grad_func.name if self._grad_func else None\n\n @property\n def python_grad_func(self):\n \"\"\"Python gradient function callable.\"\"\"\n return self._python_grad_func\n\n @property\n def declared_input_types(self):\n \"\"\"Returns the list of data types of explicit declared inputs.\"\"\"\n return self._input_types\n\n @property\n def captured_inputs(self):\n \"\"\"Returns the list of implicitly captured inputs.\"\"\"\n return self._extra_inputs\n\n def _create_definition_if_needed(self):\n \"\"\"Creates the function definition if it's not created yet.\"\"\"\n\n if self._definition is not None:\n return\n\n # Create the func_def object.\n temp_graph = _FuncGraph()\n with temp_graph.as_default():\n # List of placeholders for the function_def.\n inputs = []\n for (argname, argtype) in self._args:\n argholder = array_ops.placeholder(argtype, name=argname)\n inputs.append(argholder)\n # Call func and gather the output tensors.\n with vs.variable_scope(\"\", custom_getter=temp_graph.getvar):\n outputs = self._func(*inputs)\n # If func only returned one value, make it a tuple.\n if not isinstance(outputs, (list, tuple)):\n outputs = (outputs,)\n if any([_ is None for _ in outputs]):\n raise ValueError(\"Function can not return None.\")\n # Ensures each output is a Tensor.\n outputs = [ops.convert_to_tensor(_) for _ in outputs]\n self._extra_inputs = temp_graph.extra_inputs\n inputs.extend(temp_graph.extra_args)\n\n # Build the FunctionDef\n self._definition = _graph_to_function_def(\n temp_graph, inputs, outputs, out_names=self._out_names)\n\n # Extra kwargs are treated as attrs on the function def.\n kwargs_attr = _parse_kwargs_as_attrs(**self._extra_kwargs)\n for k in kwargs_attr:\n self._definition.attr[k].CopyFrom(kwargs_attr[k])\n\n # Hash the definition and its dependencies.\n hasher = hashlib.sha1()\n\n def _hash_func_def():\n \"\"\"Hash the function definition agnostic to node/map ordering.\"\"\"\n\n def update_num(n):\n hasher.update(compat.as_bytes(\"%x\" % n))\n\n def update_str(s):\n update_num(len(s))\n hasher.update(compat.as_bytes(s))\n\n def update_strs(slist):\n update_num(len(slist))\n for s in slist:\n update_str(s)\n\n for adef in self._definition.signature.input_arg:\n update_str(adef.SerializeToString())\n\n for adef in self._definition.signature.output_arg:\n update_str(adef.SerializeToString())\n\n for n in sorted(self._definition.node_def, key=lambda n: n.name):\n update_str(n.name)\n update_str(n.op)\n update_strs(n.input)\n update_num(len(n.attr))\n # NOTE: protobuf map serialization does not guarantee ordering.\n for k in sorted(n.attr):\n update_str(k)\n update_str(n.attr[k].SerializeToString())\n\n _hash_func_def()\n # pylint: disable=protected-access\n self._sub_functions = temp_graph._functions\n for subname in sorted(self._sub_functions.keys()):\n hasher.update(compat.as_bytes(self._sub_functions[subname]._hash_str))\n # pylint: enable=protected-access\n\n # Uses the first 8 bytes sha1 hash digest as the __hash__.\n self._hash_str = hasher.hexdigest()[:8]\n self._hash = int(self._hash_str, 16)\n\n # Finally, we decide the function name to use. If not specified,\n # make up something which is almost certainly unique.\n if not self._func_name:\n self._func_name = \"_\".join([_get_func_name(self._func), self._hash_str])\n self._definition.signature.name = self._func_name\n if self._func.__doc__:\n self._definition.signature.description = self._func.__doc__\n\n def __hash__(self):\n self._create_definition_if_needed()\n return self._hash\n\n def add_to_graph(self, g):\n \"\"\"Adds this function into the graph g.\"\"\"\n self._create_definition_if_needed()\n\n # pylint: disable=protected-access\n # If 'g' has an identical function already, do nothing.\n prev = g._get_function(self.name)\n if prev and (prev._hash == self._hash):\n return\n\n # Adds this function into 'g'.\n g._add_function(self)\n # pylint: enable=protected-access\n\n # Ensures related sub-routines are defined in 'g', too.\n for f in self._sub_functions.values():\n f.add_to_graph(g)\n\n # Adds its gradient function, too.\n if self._grad_func:\n self._grad_func.add_to_graph(g)\n\n def __call__(self, *args, **kwargs):\n self.add_to_graph(ops.get_default_graph())\n args = [ops.convert_to_tensor(_) for _ in args] + self._extra_inputs\n return _call(self._definition.signature, *args, **kwargs)\n\n# NOTE: The list needs to be extended when more data types are added.\n_DTYPE_TO_STR = {\n dtypes.float16: \"f16\",\n dtypes.float32: \"f32\",\n dtypes.float64: \"f64\",\n dtypes.int32: \"i32\",\n dtypes.uint8: \"i8\",\n dtypes.uint16: \"u16\",\n dtypes.int16: \"i16\",\n dtypes.int8: \"i8\",\n dtypes.string: \"s\",\n dtypes.complex64: \"c64\",\n dtypes.complex128: \"c128\",\n dtypes.int64: \"i64\",\n dtypes.bool: \"b\",\n dtypes.qint8: \"qi8\",\n dtypes.quint8: \"qu8\",\n dtypes.qint16: \"qi16\",\n dtypes.quint16: \"qu16\",\n dtypes.qint32: \"qi32\",\n dtypes.bfloat16: \"b16\"\n}\n\n\ndef _type_list_to_str(types):\n if any([_ not in _DTYPE_TO_STR for _ in types]):\n raise ValueError(\"Unsupported dtypes: %s\" % types)\n return \"\".join([_DTYPE_TO_STR[_] for _ in types])\n\n\nclass _OverloadedFunction(object):\n \"\"\"_OverloadedFunction encapsulates an overloaded function.\n\n _OverloadedFunction maintains a mapping from input types to\n instantiated _DefinedFunction in self._overload.\n\n \"\"\"\n\n def __init__(self,\n func,\n argnames,\n func_name=None,\n grad_func=None,\n python_grad_func=None,\n out_names=None,\n **kwargs):\n \"\"\"Creates _DefinedFunction.\n\n Args:\n func: A python callable which constructs a tf function body.\n argnames: A list of strings for function argument names.\n func_name: The function name. Defaults to None, in which derives from\n 'func'.\n grad_func: This function's gradient function, if not None. Defaults\n to None.\n python_grad_func: A python callable implementing the gradient of\n the function python-side.\n out_names: A list of strings for the function return value names.\n **kwargs: The keyword arguments. **kwargs is passed to every call\n site of this function.\n\n Raises:\n ValueError: The function definition is invalid.\n\n \"\"\"\n self._func = func\n self._argnames = argnames\n self._func_name = func_name\n assert grad_func is None or isinstance(grad_func, _OverloadedFunction)\n self._grad_func = grad_func\n self._python_grad_func = python_grad_func\n self._out_names = out_names\n self._extra_kwargs = kwargs\n self._overload = {}\n\n def instantiate(self, input_types):\n \"\"\"Instantiate this function given input argument types.\n\n Args:\n input_types: A list of data types for the inputs.\n\n Returns:\n _DefinedFunction for the given input types.\n\n \"\"\"\n # Stringify the type list.\n key = _type_list_to_str(input_types)\n defined = self._overload.get(key)\n if not defined:\n # If not defined yet, define the function given the input types.\n name = self._func_name\n if name is not None:\n name = \"_\".join([name, key])\n defined = _DefinedFunction(self._func, self._argnames, input_types, name,\n None, self._python_grad_func,\n out_names=self._out_names,\n **self._extra_kwargs)\n _ = defined.name # Fully instantiate the function definition.\n if self._grad_func:\n # If _grad_func is given, it is another\n # _OverloadedFunction. We need to instantiate it with the\n # right input types.\n output_types = [\n dtypes.DType(_.type)\n for _ in defined.definition.signature.output_arg\n ]\n # pylint: disable=protected-access\n defined._grad_func = self._grad_func.instantiate(input_types +\n output_types)\n # pylint: enable=protected-access\n self._overload[key] = defined\n return defined\n\n def __call__(self, *args, **kwargs):\n input_types = []\n args = list(args)\n for (i, x) in enumerate(args):\n x = ops.convert_to_tensor(x)\n if not isinstance(x, ops.Tensor):\n raise ValueError(\"Expect a Tensor but get \", x)\n input_types.append(x.dtype)\n args[i] = x\n return self.instantiate(input_types)(*args, **kwargs)\n\n\nclass Defun(object):\n \"\"\"Decorator used to define TensorFlow functions.\n\n Use this decorator to make a Python function usable directly as a TensorFlow\n function.\n\n The decorated function must add ops to the default graph and return zero or\n more `Tensor` objects. Call the decorator with named arguments, one for each\n argument of the function to decorate, with the expected type of the argument\n as value.\n\n For example if the function to decorate accepts two `tf.float32` arguments\n named `x` and `y`, call the decorator with:\n\n @Defun(tf.float32, tf.float32)\n def foo(x, y):\n ...\n\n When you call the decorated function it will add `call` ops to the\n default graph and adds the definition of the function into the\n default graph. Because the addition of the function into the graph\n is deferred, the decorator can be used anywhere in the program.\n\n Example, but also see the [How To on functions](link_needed).\n\n ```python\n # Defining the function.\n @tf.Defun(tf.float32, tf.float32)\n def MyFunc(x, y):\n return x + y, x - y\n\n # Building the graph.\n a = tf.Constant([1.0])\n b = tf.Constant([2.0])\n c, d = MyFunc(a, b, name='mycall')\n ```\n \"\"\"\n\n def __init__(self, *input_types, **kwargs):\n \"\"\"Create a `Defun` decorator.\n\n Args:\n *input_types: A list of `tf.DType`\n **kwargs: Optional keyword arguments, including\n func_name - (optional). A python string, the name to use to\n declare this `Function` in the graph.\n\n grad_func - (optional). A function implementing the gradient\n of the function-to-register. This is either a\n `_DefinedFunction` or a `Declare` object. The gradient\n function must satisify the criterion defined in\n function.proto:GradientDef.\n\n python_grad_func - (optional). A function implementing the\n gradient of the function python-side. This function must\n take the current op and the gradients w.r.t. its outputs,\n and return the gradients w.r.t. the inputs. That is it must\n implement the interface expected by `tf.RegisterGradient`).\n This will be called by tf.gradients to add the gradient ops\n to the graph. At most one of grad_func and python_grad_func\n can be specified.\n\n out_names = (optional). A list of strings, one per output\n tensor.\n \"\"\"\n self._input_types = input_types\n self._func_name = kwargs.pop(\"func_name\", None)\n self._grad_func = kwargs.pop(\"grad_func\", None)\n self._python_grad_func = kwargs.pop(\"python_grad_func\", None)\n self._out_names = kwargs.pop(\"out_names\", None)\n self._extra_kwargs = kwargs\n\n def __call__(self, func):\n # Various sanity checks on the callable func.\n if not callable(func):\n raise ValueError(\"func %s must be callable\" % func)\n\n # Func should not use kwargs and defaults.\n argspec = inspect.getargspec(func)\n if argspec.keywords or argspec.defaults:\n raise ValueError(\"Functions with argument defaults or keyword \"\n \"arguments are not supported.\")\n\n # Computes how many arguments 'func' has.\n min_args = len(argspec.args)\n max_args = min_args\n if argspec.varargs:\n max_args = 1000000\n argnames = argspec.args\n if inspect.ismethod(func):\n # 1st argument is the \"class\" type.\n min_args -= 1\n argnames = argnames[1:]\n\n if self._input_types:\n # If Defun is given a list of types for the inputs, the number\n # of input types should be compatible with 'func'.\n num = len(self._input_types)\n if num < min_args or num > max_args:\n raise ValueError(\n \"The function has fewer arguments than the number of specified \"\n \"input types.\")\n return _DefinedFunction(func, argnames, self._input_types,\n self._func_name, self._grad_func,\n self._python_grad_func,\n out_names=self._out_names, **self._extra_kwargs)\n\n # 'func' expects no arguments and input types is an empty list.\n if min_args == 0 and max_args == 0:\n return _DefinedFunction(func, [], [], self._func_name, self._grad_func,\n self._python_grad_func,\n out_names=self._out_names, **self._extra_kwargs)\n\n # Input types are unknown. It's an overloaded function and hence\n # its definition needs to be deferred until it's called.\n return _OverloadedFunction(func, argnames, self._func_name, self._grad_func,\n self._python_grad_func,\n out_names=self._out_names, **self._extra_kwargs)\n\n\nclass Declare(object):\n \"\"\"Declares a TensorFlow function.\n\n The object represents a TensorFlow function which will be defined\n later during a graph construction.\n\n For example,\n # Declares a function Foo, which takes a tf.int32 named \"n\" and a\n # tf.float32 named \"n\" as inputs and returns a tf.float32 named \"z\"\n # as its output.\n foo = Declare(\"Foo\", [(\"n\", tf.int32), (\"x\", tf.float32)],\n [(\"z\", tf.float32)])\n\n # Defines a function Bar calls Foo.\n @tf.Defun(tf.float32)\n def Bar(x):\n return foo(6, x)\n\n # Defines Foo, with output named \"z\".\n @tf.Defun(tf.int32, tf.float32, out_names=[\"z\"])\n def Foo(n, x):\n ... # Calculation.\n return result\n \"\"\"\n\n def __init__(self, func_name, inputs, outputs):\n \"\"\"Creates a `Declare` object.\n\n Args:\n func_name: The name of the function.\n inputs: A list of (name, data type) pairs of function arguments.\n outputs: A list of (name, data type) pairs of function return values.\n \"\"\"\n self._sig = op_def_pb2.OpDef()\n self._sig.name = func_name\n\n def _to_argdef_list(args):\n names = [n for n, t in args]\n if len(names) != len(set(names)):\n raise ValueError(\"Expected names to all be unique: %s\" % str(names))\n return [op_def_pb2.OpDef.ArgDef(type=t.as_datatype_enum, name=n)\n for n, t in args]\n\n self._sig.input_arg.extend(_to_argdef_list(inputs))\n self._sig.output_arg.extend(_to_argdef_list(outputs))\n\n def __call__(self, *inputs, **kwargs):\n inputs = [ops.convert_to_tensor(_) for _ in inputs]\n return _call(self._sig, *inputs, **kwargs)\n" ]
[ [ "tensorflow.python.ops.array_ops.constant", "tensorflow.python.ops.array_ops.shape", "tensorflow.python.ops.math_ops.reduce_max", "tensorflow.python.ops.control_flow_ops.while_loop", "tensorflow.python.framework.ops.device", "tensorflow.python.ops.array_ops.identity", "tensorflow.python.ops.control_flow_ops.cond", "tensorflow.python.ops.math_ops.to_int32", "tensorflow.python.ops.array_ops.transpose", "tensorflow.python.ops.math_ops.reduce_all", "tensorflow.python.ops.math_ops.to_int64", "tensorflow.python.ops.array_ops.where", "tensorflow.python.ops.array_ops.unstack", "tensorflow.python.ops.math_ops.reduce_min", "tensorflow.python.ops.variable_scope.variable_scope", "tensorflow.python.ops.math_ops.logical_or", "tensorflow.python.ops.tensor_array_ops.TensorArray", "tensorflow.python.util.nest.is_sequence", "tensorflow.python.ops.array_ops.reverse_sequence", "tensorflow.python.ops.math_ops.equal", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.util.nest.pack_sequence_as", "tensorflow.python.ops.array_ops.stack", "tensorflow.python.util.nest.assert_same_structure", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.util.nest.flatten", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.python.ops.math_ops.negative", "tensorflow.python.ops.math_ops.div", "tensorflow.python.ops.variables.Variable", "tensorflow.python.debug.lib.stepper.NodeStepper", "tensorflow.python.client.session.Session", "tensorflow.python.ops.math_ops.multiply", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.platform.googletest.main", "tensorflow.python.ops.math_ops.add", "tensorflow.python.training.gradient_descent.GradientDescentOptimizer", "tensorflow.python.ops.math_ops.matmul", "tensorflow.python.ops.variables.global_variables_initializer", "tensorflow.python.framework.ops.reset_default_graph", "tensorflow.python.framework.constant_op.constant" ], [ "tensorflow.core.framework.function_pb2.FunctionDef", "tensorflow.core.framework.op_def_pb2.OpDef", "tensorflow.python.ops.variable_scope.get_variable_scope", "tensorflow.python.ops.variable_scope._get_default_variable_store", "tensorflow.core.framework.op_def_pb2.OpDef.ArgDef", "tensorflow.python.framework.op_def_registry.get_registered_ops", "tensorflow.python.framework.ops.get_default_graph", "tensorflow.python.framework.ops.name_scope", "tensorflow.python.ops.array_ops.placeholder", "tensorflow.python.util.compat.as_bytes", "tensorflow.python.framework.dtypes.DType", "tensorflow.python.framework.ops.convert_to_tensor", "tensorflow.python.ops.variable_scope.variable_scope" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.4", "2.9", "1.5", "1.7", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.5", "1.7", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
morethanbooks/XML-TEI-Bible
[ "eb42b0ff37ad0049e84f01eb55ec786c8b4a54ea" ]
[ "code/python/scripts/bible2books.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 2 14:33:27 2018\n\n@author: jose\n\"\"\"\n\nimport pandas as pd\nimport re\nimport os\nimport glob \n\nmetadata = pd.read_csv(\"/home/jose/Dropbox/biblia/tb/documentation/libros.csv\", sep=\"\\t\")\n\nfor doc in glob.glob(\"/home/jose/Dropbox/biblia/datos/origen/rv95.txt\"):\n #print(\"aquí va doc!!!: \",doc)\n input_name = os.path.splitext(os.path.split(doc)[1])[0]\n #print(input_name)\n with open(doc, \"r\", errors=\"replace\", encoding=\"utf-8\") as fin:\n biblia = fin.read()\n for index, row in metadata.iterrows():\n print(row[[\"id\",\"codebook\"]])\n if row[\"id\"] < 66:\n book = re.findall(r\"(\\n\\|\"+str(row[\"id\"])+\"\\|.*?)\\n\\|\"+str(int(row[\"id\"])+1)+\"\\|\", biblia, flags=re.DOTALL)[0]\n else:\n book = re.findall(r\"(\\n\\|\"+str(row[\"id\"])+\"\\|.*?)\\Z\", biblia, flags=re.DOTALL|re.MULTILINE)[0]\n \n #print(book[0:100])\n with open (\"/home/jose/Dropbox/biblia/datos/origen/\"+ row[\"codebook\"]+\".txt\", \"w\", encoding=\"utf-8\") as fout:\n fout.write(book)\n fin.close() \n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
HexDecimal/7drl-2022
[ "755949875cc11e288908eccaee102c7ca0e43777" ]
[ "game/rendering.py" ]
[ "from __future__ import annotations\n\nimport numpy as np\nimport tcod\n\nimport g\nimport game.constants\nimport game.engine\nimport game.game_map\nimport game.render_functions\nfrom game.tiles import tile_graphics\n\n\ndef render_map(console: tcod.Console, gamemap: game.game_map.GameMap) -> None:\n # The default graphics are of tiles that are visible.\n light = tile_graphics[gamemap.tiles]\n light[gamemap.fire > 0] = (ord(\"^\"), (255, 255, 255), (0xCC, 0x22, 0))\n\n # Apply effects to create a darkened map of tile graphics.\n dark = gamemap.memory.copy()\n dark[\"fg\"] //= 2\n dark[\"bg\"] //= 8\n\n visible = gamemap.visible\n if g.fullbright:\n visible = np.ones_like(visible)\n\n for entity in sorted(gamemap.entities, key=lambda x: x.render_order.value):\n if not visible[entity.x, entity.y]:\n continue # Skip entities that are not in the FOV.\n light[entity.x, entity.y][\"ch\"] = ord(entity.char)\n light[entity.x, entity.y][\"fg\"] = entity.color\n\n console.rgb[0 : gamemap.width, 0 : gamemap.height] = np.select(\n condlist=[visible, gamemap.explored],\n choicelist=[light, dark],\n default=dark,\n )\n\n for entity in sorted(gamemap.entities, key=lambda x: x.render_order.value):\n if not visible[entity.x, entity.y]:\n continue # Skip entities that are not in the FOV.\n console.print(entity.x, entity.y, entity.char, fg=entity.color)\n\n visible.choose((gamemap.memory, light), out=gamemap.memory)\n\n\ndef render_ui(console: tcod.Console, engine: game.engine.Engine) -> None:\n UI_WIDTH = game.constants.ui_width\n UI_LEFT = console.width - UI_WIDTH\n LOG_HEIGHT = console.height - 8\n\n engine.message_log.render(\n console=console, x=UI_LEFT, y=console.height - LOG_HEIGHT, width=UI_WIDTH, height=LOG_HEIGHT\n )\n console.draw_rect(UI_LEFT, 0, UI_WIDTH, 2, 0x20, (0xFF, 0xFF, 0xFF), (0, 0, 0))\n\n game.render_functions.render_bar(\n console=console,\n x=UI_LEFT,\n y=0,\n current_value=engine.player.fighter.hp,\n maximum_value=engine.player.fighter.max_hp,\n total_width=UI_WIDTH,\n )\n\n game.render_functions.render_names_at_mouse_location(console=console, x=UI_LEFT, y=1, engine=engine)\n\n if g.mouse_pos:\n console.rgb[g.mouse_pos][\"fg\"] = (0, 0, 0)\n console.rgb[g.mouse_pos][\"bg\"] = (255, 255, 255)\n if g.fullbright or engine.game_map.visible[g.mouse_pos]:\n console.print(\n UI_LEFT,\n 2,\n f\"Fire={engine.game_map.fire[g.mouse_pos]}, Heat={engine.game_map.heat[g.mouse_pos]}, \"\n f\"Smoke={engine.game_map.smoke[g.mouse_pos]},\\nFuel={engine.game_map.fuel[g.mouse_pos]}\",\n )\n" ]
[ [ "numpy.ones_like", "numpy.select" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
platiagro/tasks
[ "a6103cb101eeed26381cdb170a11d0e1dc53d3ad" ]
[ "tasks/retriever/mrr.py" ]
[ "# Import dependencies\n\n# Math/Torch\nimport numpy as np\nimport torch.nn as nn\n\n# Typing\nfrom typing import List\n\n# Instantiate class\nclass MRR(nn.Module):\n \"\"\"Compute MRR metric (Mean reciprocal rank)\"\"\"\n def __init__(self, max_rank = 10):\n\n super(MRR, self).__init__()\n\n # Set max mrr rank\n self.max_rank = max_rank\n\n def _calculate_reciprocal_rank(self, hypothesis_ids: np.ndarray, reference_id: int) -> float:\n \"\"\"Calculate the reciprocal rank for a given hypothesis and reference\n \n Params:\n hypothesis_ids: Iterator of hypothesis ids (as numpy array) ordered by its relevance\n reference_id: Reference id (as a integer) of the correct id of response\n Returns:\n reciprocal rank\n \"\"\"\n\n # Assure hypothesis_ids is a numpy array\n hypothesis_ids = np.asarray(hypothesis_ids)\n\n # Calculate rank\n try:\n rank = np.where(hypothesis_ids == reference_id)[0][0] + 1\n except IndexError:\n rank = self.max_rank + 1\n\n # Rank grater then max_rank is set to zero\n if rank > self.max_rank:\n reciprocal_rank = 0.0\n\n else:\n # Calculate reciprocal rank\n reciprocal_rank = 1. / rank\n \n return reciprocal_rank\n\n def forward(self, batch_hypothesis_ids: List[np.ndarray], batch_reference_id: List[int]) -> float:\n \"\"\"Score the mean reciprocal rank for the batch\n \n Example from http://en.wikipedia.org/wiki/Mean_reciprocal_rank\n \n >>> batch_hypothesis_ids = [[1, 0, 2], [0, 2, 1], [1, 0, 2]]\n >>> batch_reference_id = [2, 2, 1]\n >>> mrr = MRR()\n >>> mrr(batch_hypothesis_ids, batch_reference_id)\n 0.61111111111111105\n\n Args:\n batch_hypothesis_ids: Batch of hypothesis ids (as numpy array) ordered by its relevance\n reference_id: Batch of reference id (as a integer) of the correct id of response\n Returns:\n Mean reciprocal rank (MRR)\n \"\"\"\n\n # Assure batches have same length\n assert len(batch_hypothesis_ids) == len(batch_reference_id), \"Hypothesis batch and reference batch must have same length.\"\n\n # Size of batch\n batch_size = len(batch_hypothesis_ids)\n \n # MRR to be calculated\n mrr = 0\n\n for hypothesis_ids, reference_id in zip(batch_hypothesis_ids, batch_reference_id):\n\n # Calculate reciprocal rank\n reciprocal_rank = self._calculate_reciprocal_rank(hypothesis_ids, reference_id)\n\n # Add to MRR\n mrr += reciprocal_rank/batch_size\n\n return mrr\n" ]
[ [ "numpy.asarray", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]