INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Renders the training and test learning curves.
def draw(self, **kwargs): """ Renders the training and test learning curves. """ # Specify the curves to draw and their labels labels = ("Training Score", "Cross Validation Score") curves = ( (self.train_scores_mean_, self.train_scores_std_), (self...
Displays each feature as a vertical axis and each instance as a line.
def parallel_coordinates(X, y, ax=None, features=None, classes=None, normalize=None, sample=1.0, color=None, colormap=None, alpha=None, fast=False, vlines=True, vlines_kwds=None, **kwargs): """Displays each feature as a vertical axis and eac...
The fit method is the primary drawing input for the visualization since it has both the X and y data required for the viz and the transform method does not.
def fit(self, X, y=None, **kwargs): """ The fit method is the primary drawing input for the visualization since it has both the X and y data required for the viz and the transform method does not. Parameters ---------- X : ndarray or DataFrame of shape n x m ...
Called from the fit method this method creates the parallel coordinates canvas and draws each instance and vertical lines on it.
def draw(self, X, y, **kwargs): """ Called from the fit method, this method creates the parallel coordinates canvas and draws each instance and vertical lines on it. Parameters ---------- X : ndarray of shape n x m A matrix of n instances with m features ...
Draw the instances colored by the target y such that each line is a single instance. This is the slow mode of drawing since each instance has to be drawn individually. However in so doing the density of instances in braids is more apparent since lines have an independent alpha that is compounded in the figure.
def draw_instances(self, X, y, **kwargs): """ Draw the instances colored by the target y such that each line is a single instance. This is the "slow" mode of drawing, since each instance has to be drawn individually. However, in so doing, the density of instances in braids is mor...
Draw the instances colored by the target y such that each line is a single class. This is the fast mode of drawing since the number of lines drawn equals the number of classes rather than the number of instances. However this drawing method sacrifices inter - class density of points using the alpha parameter.
def draw_classes(self, X, y, **kwargs): """ Draw the instances colored by the target y such that each line is a single class. This is the "fast" mode of drawing, since the number of lines drawn equals the number of classes, rather than the number of instances. However, this drawi...
Finalize executes any subclass - specific axes finalization steps. The user calls poof and poof calls finalize.
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title self.set_title( ...
Displays a validation curve for the specified param and values plotting both the train and cross - validated test scores. The validation curve is a visual single - parameter grid search used to tune a model to find the best balance between error due to bias and error due to variance.
def validation_curve(model, X, y, param_name, param_range, ax=None, logx=False, groups=None, cv=None, scoring=None, n_jobs=1, pre_dispatch="all", **kwargs): """ Displays a validation curve for the specified param and values, plotting both the train and cross-validat...
Fits the validation curve with the wrapped estimator and parameter array to the specified data. Draws training and test score curves and saves the scores to the visualizer.
def fit(self, X, y=None): """ Fits the validation curve with the wrapped estimator and parameter array to the specified data. Draws training and test score curves and saves the scores to the visualizer. Parameters ---------- X : array-like, shape (n_samples, n_fe...
Proxy property to smartly access the classes from the estimator or stored locally on the score visualizer for visualization.
def classes_(self): """ Proxy property to smartly access the classes from the estimator or stored locally on the score visualizer for visualization. """ if self.__classes is None: try: return self.estimator.classes_ except AttributeError: ...
Parameters ----------
def fit(self, X, y=None, **kwargs): """ Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series of target or class values kwargs: keyword argument...
Load a dataset by name and return specified format.
def _load_dataset(name, data_home=None, return_dataset=False): """ Load a dataset by name and return specified format. """ info = DATASETS[name] data = Dataset(name, data_home=data_home, **info) if return_dataset: return data return data.to_data()
Load a corpus object by name.
def _load_corpus(name, data_home=None): """ Load a corpus object by name. """ info = DATASETS[name] return Corpus(name, data_home=data_home, **info)
Generates a list of colors based on common color arguments for example the name of a colormap or palette or another iterable of colors. The list is then truncated ( or multiplied ) to the specific number of requested colors.
def resolve_colors(n_colors=None, colormap=None, colors=None): """ Generates a list of colors based on common color arguments, for example the name of a colormap or palette or another iterable of colors. The list is then truncated (or multiplied) to the specific number of requested colors. Para...
Converts color strings into a color listing.
def colors(self, value): """ Converts color strings into a color listing. """ if isinstance(value, str): # Must import here to avoid recursive import from .palettes import PALETTES if value not in PALETTES: raise YellowbrickValueError(...
Return a property attribute for new - style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned preventing the need to call the getter any more.
def memoized(fget): """ Return a property attribute for new-style classes that only calls its getter on the first access. The result is stored and on subsequent accesses is returned, preventing the need to call the getter any more. Parameters ---------- fget: function The getter met...
Creates 2x2 grid plot of the 4 anscombe datasets for illustration.
def anscombe(): """ Creates 2x2 grid plot of the 4 anscombe datasets for illustration. """ _, ((axa, axb), (axc, axd)) = plt.subplots(2, 2, sharex='col', sharey='row') colors = get_color_cycle() for arr, ax, color in zip(ANSCOMBE, (axa, axb, axc, axd), colors): x = arr[0] y = a...
Displays each feature as an axis around a circle surrounding a scatter plot whose points are each individual instance.
def radviz(X, y=None, ax=None, features=None, classes=None, color=None, colormap=None, alpha=1.0, **kwargs): """ Displays each feature as an axis around a circle surrounding a scatter plot whose points are each individual instance. This helper function is a quick wrapper to utilize the Radia...
MinMax normalization to fit a matrix in the space [ 0 1 ] by column.
def normalize(X): """ MinMax normalization to fit a matrix in the space [0,1] by column. """ a = X.min(axis=0) b = X.max(axis=0) return (X - a[np.newaxis, :]) / ((b - a)[np.newaxis, :])
Called from the fit method this method creates the radviz canvas and draws each instance as a class or target colored point whose location is determined by the feature data set.
def draw(self, X, y, **kwargs): """ Called from the fit method, this method creates the radviz canvas and draws each instance as a class or target colored point, whose location is determined by the feature data set. """ # Convert from dataframe if is_dataframe(X):...
Finalize executes any subclass - specific axes finalization steps. The user calls poof and poof calls finalize.
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title self.set_title( ...
Returns the index of the value at the Qth percentile in array a.
def percentile_index(a, q): """ Returns the index of the value at the Qth percentile in array a. """ return np.where( a==np.percentile(a, q, interpolation='nearest') )[0][0]
Raises a well formatted exception if s is not in valid otherwise does not raise an exception. Uses param_name to identify the parameter.
def validate_string_param(s, valid, param_name="param"): """ Raises a well formatted exception if s is not in valid, otherwise does not raise an exception. Uses ``param_name`` to identify the parameter. """ if s.lower() not in valid: raise YellowbrickValueError( "unknown {} '{}',...
Quick Method:
def intercluster_distance(model, X, y=None, ax=None, min_size=400, max_size=25000, embedding='mds', scoring='membership', legend=True, legend_loc="lower left", legend_size=1.5, random_state=None, **kwargs): """Qu...
Returns the legend axes creating it only on demand by creating a 2 by 2 inset axes that has no grid ticks spines or face frame ( e. g is mostly invisible ). The legend can then be drawn on this axes.
def lax(self): """ Returns the legend axes, creating it only on demand by creating a 2" by 2" inset axes that has no grid, ticks, spines or face frame (e.g is mostly invisible). The legend can then be drawn on this axes. """ if inset_locator is None: raise Yel...
Creates the internal transformer that maps the cluster center s high dimensional space to its two dimensional space.
def transformer(self): """ Creates the internal transformer that maps the cluster center's high dimensional space to its two dimensional space. """ ttype = self.embedding.lower() # transformer method type if ttype == 'mds': return MDS(n_components=2, random_s...
Searches for or creates cluster centers for the specified clustering algorithm. This algorithm ensures that that the centers are appropriately drawn and scaled so that distance between clusters are maintained.
def cluster_centers_(self): """ Searches for or creates cluster centers for the specified clustering algorithm. This algorithm ensures that that the centers are appropriately drawn and scaled so that distance between clusters are maintained. """ # TODO: Handle agg...
Fit the clustering model computing the centers then embeds the centers into 2D space using the embedding method specified.
def fit(self, X, y=None): """ Fit the clustering model, computing the centers then embeds the centers into 2D space using the embedding method specified. """ with Timer() as self.fit_time_: # Fit the underlying estimator self.estimator.fit(X, y) ...
Draw the embedded centers with their sizes on the visualization.
def draw(self): """ Draw the embedded centers with their sizes on the visualization. """ # Compute the sizes of the markers from their score sizes = self._get_cluster_sizes() # Draw the scatter plots with associated sizes on the graph self.ax.scatter( ...
Finalize the visualization to create an origin grid feel instead of the default matplotlib feel. Set the title remove spines and label the grid with components. This function also adds a legend from the sizes if required.
def finalize(self): """ Finalize the visualization to create an "origin grid" feel instead of the default matplotlib feel. Set the title, remove spines, and label the grid with components. This function also adds a legend from the sizes if required. """ # Set the ...
Determines the scores of the cluster the metric that determines the size of the cluster visualized on the visualization.
def _score_clusters(self, X, y=None): """ Determines the "scores" of the cluster, the metric that determines the size of the cluster visualized on the visualization. """ stype = self.scoring.lower() # scoring method name if stype == "membership": return np.bi...
Returns the marker size ( in points e. g. area of the circle ) based on the scores using the prop_to_size scaling mechanism.
def _get_cluster_sizes(self): """ Returns the marker size (in points, e.g. area of the circle) based on the scores, using the prop_to_size scaling mechanism. """ # NOTE: log and power are hardcoded, should we allow the user to specify? return prop_to_size( sel...
Draw a legend that shows relative sizes of the clusters at the 25th 50th and 75th percentile based on the current scoring metric.
def _make_size_legend(self): """ Draw a legend that shows relative sizes of the clusters at the 25th, 50th, and 75th percentile based on the current scoring metric. """ # Compute the size of the markers and scale them to our figure size # NOTE: the marker size is the area...
Adds a manual legend for a scatter plot to the visualizer where the labels and associated colors are drawn with circle patches instead of determining them from the labels of the artist objects on the axes. This helper is used either when there are a lot of duplicate labels no labeled artists or when the color of the le...
def manual_legend(g, labels, colors, **legend_kwargs): """ Adds a manual legend for a scatter plot to the visualizer where the labels and associated colors are drawn with circle patches instead of determining them from the labels of the artist objects on the axes. This helper is used either when the...
Displays frequency distribution plot for text.
def freqdist(X, y=None, ax=None, color=None, N=50, **kwargs): """Displays frequency distribution plot for text. This helper function is a quick wrapper to utilize the FreqDist Visualizer (Transformer) for one-off analysis. Parameters ---------- X: ndarray or DataFrame of shape n x m A...
Called from the fit method this method gets all the words from the corpus and their corresponding frequency counts.
def count(self, X): """ Called from the fit method, this method gets all the words from the corpus and their corresponding frequency counts. Parameters ---------- X : ndarray or masked ndarray Pass in the matrix of vectorized documents, can be masked...
The fit method is the primary drawing input for the frequency distribution visualization. It requires vectorized lists of documents and a list of features which are the actual words from the original corpus ( needed to label the x - axis ticks ).
def fit(self, X, y=None): """ The fit method is the primary drawing input for the frequency distribution visualization. It requires vectorized lists of documents and a list of features, which are the actual words from the original corpus (needed to label the x-axis ticks). ...
Called from the fit method this method creates the canvas and draws the distribution plot on it.
def draw(self, **kwargs): """ Called from the fit method, this method creates the canvas and draws the distribution plot on it. Parameters ---------- kwargs: generic keyword arguments. """ # Prepare the data bins = np.arange(self.N) word...
The finalize method executes any subclass - specific axes finalization steps. The user calls poof & poof calls finalize.
def finalize(self, **kwargs): """ The finalize method executes any subclass-specific axes finalization steps. The user calls poof & poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title self.set_title( ...
Quick method:
def classification_report(model, X, y=None, ax=None, classes=None, random_state=None,**kwargs): """Quick method: Displays precision, recall, F1, and support scores for the model. Integrates numerical scores as well as color-coded heatmap. This helper function is a quick wrapp...
Generates the Scikit - Learn classification report.
def score(self, X, y=None, **kwargs): """ Generates the Scikit-Learn classification report. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features y : ndarray or Series of length n An array or series...
Renders the classification report across each axis.
def draw(self): """ Renders the classification report across each axis. """ # Create display grid cr_display = np.zeros((len(self.classes_), len(self._displayed_scores))) # For each class row, append columns for precision, recall, f1, and support for idx, cls in...
Finalize executes any subclass - specific axes finalization steps. The user calls poof and poof calls finalize.
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Set the title of the classifiation report ...
Create a deprecated __getitem__ method that tells users to use getattr instead.
def _deprecated_getitem_method(name, attrs): """Create a deprecated ``__getitem__`` method that tells users to use getattr instead. Parameters ---------- name : str The name of the object in the warning message. attrs : iterable[str] The set of allowed attributes. Returns ...
A decorator to wrap with try.. except to swallow specific HTTP errors.
def skip_http_error(statuses): ''' A decorator to wrap with try..except to swallow specific HTTP errors. @skip_http_error((404, 503)) def fetch(): ... ''' assert isinstance(statuses, tuple) def decorator(func): def wrapper(*args, **kwargs): try: ...
Utility for debug/ testing
def _symbols2assets(self, symbols): ''' Utility for debug/testing ''' assets = {a.symbol: a for a in self.get_equities()} return [assets[symbol] for symbol in symbols if symbol in assets]
Interface method.
def get_bars(self, assets, data_frequency, bar_count=500): ''' Interface method. Return: pd.Dataframe() with columns MultiIndex [asset -> OHLCV] ''' assets_is_scalar = not isinstance(assets, (list, set, tuple)) is_daily = 'd' in data_frequency # 'daily' or '1d' ...
Query historic_agg either minute or day in parallel for multiple symbols and return in dict.
def _symbol_bars( self, symbols, size, _from=None, to=None, limit=None): ''' Query historic_agg either minute or day in parallel for multiple symbols, and return in dict. symbols: list[str] size: str ('da...
Query last_trade in parallel for multiple symbols and return in dict.
def _symbol_trades(self, symbols): ''' Query last_trade in parallel for multiple symbols and return in dict. symbols: list[str] return: dict[str -> polygon.Trade] ''' @skip_http_error((404, 504)) def fetch(symbol): return self._api.polygon.l...
Track and record values each day.
def record(self, *args, **kwargs): """Track and record values each day. Parameters ---------- **kwargs The names and values to record. Notes ----- These values will appear in the performance packets and the performance dataframe passed to ``a...
Lookup equities by symbol.
def symbols(self, *args, **kwargs): '''Lookup equities by symbol. Parameters: args (iterable[str]): List of ticker symbols for the asset. Returns: equities (List[Equity]): The equity lookuped by the ``symbol``. Raises: AssetNotFound: When could not ...
If asset is unspecified or None returns a dictionary keyed by asset ID. The dictionary contains a list of orders for each ID oldest first. If an asset is specified returns a list of open orders for that asset oldest first. Orders submitted after before will not be returned. If provided only orders of type status ( clos...
def get_all_orders( self, asset=None, before=None, status='all', days_back=None): ''' If asset is unspecified or None, returns a dictionary keyed by asset ID. The dictionary contains a list of orders for each ID, oldest first. I...
DEPRECATED: use data. history instead.
def history(self, bar_count, frequency, field, ffill=True): """DEPRECATED: use ``data.history`` instead. """ return self.get_history_window( bar_count, frequency, self._calculate_universe(), field, ffill, )
Calculates how many shares/ contracts to order based on the type of asset being ordered.
def _calculate_order_value_amount(self, asset, value): """ Calculates how many shares/contracts to order based on the type of asset being ordered. """ if not self.executor.current_data.can_trade(asset): raise CannotOrderDelistedAsset( msg="Cannot order...
Set a restriction on which assets can be ordered.
def set_do_not_order_list(self, restricted_list, on_error='fail'): """Set a restriction on which assets can be ordered. Parameters ---------- restricted_list : container[Asset], SecurityList The assets that cannot be ordered. """ if isinstance(restricted_list...
translate zipline script into pylivetrader script.
def translate(script): '''translate zipline script into pylivetrader script. ''' tree = ast.parse(script) ZiplineImportVisitor().visit(tree) return astor.to_source(tree)
Constructs an event rule from the factory api.
def make_eventrule(date_rule, time_rule, cal, half_days=True): """ Constructs an event rule from the factory api. """ # Insert the calendar in to the individual rules date_rule.cal = cal time_rule.cal = cal if half_days: inner_rule = date_rule & time_rule else: nhd_rule...
In this method for the given sector we ll get the data we need for each stock in the sector from IEX. Once we have the data we ll check that the earnings reports meet our criteria with eps_good (). We ll put stocks that meet those requirements into a dataframe along with all the data about them we ll need.
def build_sector_fundamentals(sector): ''' In this method, for the given sector, we'll get the data we need for each stock in the sector from IEX. Once we have the data, we'll check that the earnings reports meet our criteria with `eps_good()`. We'll put stocks that meet those requirements into a da...
Create our pipeline.
def make_pipeline(context): """ Create our pipeline. """ # Filter for primary share equities. IsPrimaryShare is a built-in filter. primary_share = IsPrimaryShare() # Not when-issued equities. not_wi = ~IEXCompany.symbol.latest.endswith('.WI') # Equities without LP in their name, .matc...
Record variables at the end of each day.
def my_record_vars(context, data): """ Record variables at the end of each day. """ # Record our variables. record(leverage=context.account.leverage) record(positions=len(context.portfolio.positions)) if 0 < len(context.age): MaxAge = context.age[max( list(context.age.ke...
Retrieve all assets in sids.
def retrieve_all(self, sids, default_none=False): """ Retrieve all assets in `sids`. Parameters ---------- sids : iterable of string Assets to retrieve. default_none : bool If True, return None for failed lookups. If False, raise `Sids...
Retrieve the Asset for a given sid.
def retrieve_asset(self, sid, default_none=False): """ Retrieve the Asset for a given sid. """ try: asset = self._asset_cache[sid] if asset is None and not default_none: raise SidsNotFound(sids=[sid]) return asset except KeyErro...
Retrieve Equity objects for a list of sids.
def retrieve_equities(self, sids): """ Retrieve Equity objects for a list of sids. Users generally shouldn't need to this method (instead, they should prefer the more general/friendly `retrieve_assets`), but it has a documented interface and tests because it's used upstream. ...
Asymmetric rounding function for adjusting prices to two places in a way that improves the price. For limit prices this means preferring to round down on buys and preferring to round up on sells. For stop prices it means the reverse.
def asymmetric_round_price_to_penny(price, prefer_round_down, diff=(0.0095 - .005)): """ Asymmetric rounding function for adjusting prices to two places in a way that "improves" the price. For limit prices, this means preferring to round down on buys and preferring t...
For the given asset or iterable of assets returns true if all of the following are true: 1 ) the asset is alive for the session of the current simulation time ( if current simulation time is not a market minute we use the next session ) 2 ) ( if we are in minute mode ) the asset s exchange is open at the current simula...
def can_trade(self, assets): """ For the given asset or iterable of assets, returns true if all of the following are true: 1) the asset is alive for the session of the current simulation time (if current simulation time is not a market minute, we use the next session)...
For the given asset or iterable of assets returns true if the asset is alive and there is no trade data for the current simulation time.
def is_stale(self, assets): """ For the given asset or iterable of assets, returns true if the asset is alive and there is no trade data for the current simulation time. If the asset has never traded, returns False. If the current simulation time is not a valid market time, we ...
Internal utility method to get the current simulation time.
def _get_current_minute(self): """ Internal utility method to get the current simulation time. Possible answers are: - whatever the algorithm's get_datetime() method returns (this is what `self.simulation_dt_func()` points to) - sometimes we're knowingly not in a mar...
Redirect pylivetrader. api. * operations to the algorithm in the local context.
def api_method(f): ''' Redirect pylivetrader.api.* operations to the algorithm in the local context. ''' @wraps(f) def wrapped(*args, **kwargs): # Get the instance and call the method algorithm = get_context() if algorithm is None: raise RuntimeError( ...
Create our pipeline.
def make_pipeline(context): """ Create our pipeline. """ # Filter for primary share equities. IsPrimaryShare is a built-in filter. primary_share = IsPrimaryShare() # Equities listed as common stock (as opposed to, say, preferred stock). # 'ST00000001' indicates common stock. common_sto...
Parallelize the mapfunc with multithreading. mapfunc calls will be partitioned by the provided list of arguments. Each item in the list will represent one call s arguments. They can be tuples if the function takes multiple arguments but one - tupling is not necessary.
def parallelize(mapfunc, workers=None): ''' Parallelize the mapfunc with multithreading. mapfunc calls will be partitioned by the provided list of arguments. Each item in the list will represent one call's arguments. They can be tuples if the function takes multiple arguments, but one-tupling is not...
TODO: for external data ( fetch_csv ) support need to update logic here.
def get_adjusted_value( self, assets, field, dt, perspective_dt, data_frequency): ''' TODO: for external data (fetch_csv) support, need to update logic here. ''' return self.backend.get_spot_value( ...
Wrapper around pandas read_csv.
def load_df_from_file(file_path, sep=",", header=0): """Wrapper around pandas' read_csv.""" with tf.gfile.Open(file_path) as infile: df = pd.read_csv(infile, sep=sep, header=header) return df
Pickle obj to file_name.
def serialize_to_file(obj, file_name, append=False): """Pickle obj to file_name.""" logging.info("Serializing to file %s.", file_name) with tf.gfile.Open(file_name, "a+" if append else "wb") as output_file: pickle.dump(obj, output_file) logging.info("Done serializing to file %s.", file_name)
Savez_compressed obj to file_name.
def savez_two_column(matrix, row_offset, file_name, append=False): """Savez_compressed obj to file_name.""" logging.info("Saving obj to file in two column .npz format %s.", file_name) tc = [] for u, items in enumerate(matrix): user = row_offset + u for item in items: tc.append([user, item]) n...
Compute the product set of array_a and array_b and sort it.
def sorted_product_set(array_a, array_b): """Compute the product set of array_a and array_b and sort it.""" return np.sort( np.concatenate( [array_a[i] * array_b for i in xrange(len(array_a))], axis=0) )[::-1]
Produce additional matches for predictions that have only low - quality matches. Specifically for each ground - truth find the set of predictions that have maximum overlap with it ( including ties ) ; for each prediction in that set if it is unmatched then match it to the ground - truth with which it has the highest qu...
def set_low_quality_matches_(self, matches, all_matches, match_quality_matrix): """ Produce additional matches for predictions that have only low-quality matches. Specifically, for each ground-truth find the set of predictions that have maximum overlap with it (including ties); for each ...
Evaluate on voc dataset. Args: pred_boxlists ( list [ BoxList ] ): pred boxlist has labels and scores fields. gt_boxlists ( list [ BoxList ] ): ground truth boxlist has labels field. iou_thresh: iou thresh use_07_metric: boolean Returns: dict represents the results
def eval_detection_voc(pred_boxlists, gt_boxlists, iou_thresh=0.5, use_07_metric=False): """Evaluate on voc dataset. Args: pred_boxlists(list[BoxList]): pred boxlist, has labels and scores fields. gt_boxlists(list[BoxList]): ground truth boxlist, has labels field. iou_thresh: iou thresh ...
Calculate precision and recall based on evaluation code of PASCAL VOC. This function calculates precision and recall of predicted bounding boxes obtained from a dataset which has: math: N images. The code is based on the evaluation code used in PASCAL VOC Challenge.
def calc_detection_voc_prec_rec(gt_boxlists, pred_boxlists, iou_thresh=0.5): """Calculate precision and recall based on evaluation code of PASCAL VOC. This function calculates precision and recall of predicted bounding boxes obtained from a dataset which has :math:`N` images. The code is based on th...
Calculate average precisions based on evaluation code of PASCAL VOC. This function calculates average precisions from given precisions and recalls. The code is based on the evaluation code used in PASCAL VOC Challenge. Args: prec ( list of numpy. array ): A list of arrays.: obj: prec [ l ] indicates precision for class...
def calc_detection_voc_ap(prec, rec, use_07_metric=False): """Calculate average precisions based on evaluation code of PASCAL VOC. This function calculates average precisions from given precisions and recalls. The code is based on the evaluation code used in PASCAL VOC Challenge. Args: prec ...
Arguments: proposals: list [ BoxList ] targets: list [ BoxList ]
def add_gt_proposals(self, proposals, targets): """ Arguments: proposals: list[BoxList] targets: list[BoxList] """ # Get the device we're operating on device = proposals[0].bbox.device gt_boxes = [target.copy_with_fields([]) for target in targets]...
Arguments: anchors: list [ BoxList ] objectness: tensor of size N A H W box_regression: tensor of size N A * 4 H W
def forward_for_single_feature_map(self, anchors, objectness, box_regression): """ Arguments: anchors: list[BoxList] objectness: tensor of size N, A, H, W box_regression: tensor of size N, A * 4, H, W """ device = objectness.device N, A, H, W =...
Arguments: anchors: list [ list [ BoxList ]] objectness: list [ tensor ] box_regression: list [ tensor ]
def forward(self, anchors, objectness, box_regression, targets=None): """ Arguments: anchors: list[list[BoxList]] objectness: list[tensor] box_regression: list[tensor] Returns: boxlists (list[BoxList]): the post-processed anchors, after ...
Drop values from a sparse matrix encoded as a SciPy coo matrix.
def _dropout_sparse_coo_matrix(sparse_matrix, rate, min_dropout_rate, max_dropout_rate): """Drop values from a sparse matrix encoded as a SciPy coo matrix. Args: sparse_matrix: a SciPy coo sparse matrix. rate: if rate > 0 then non-zero elements of the input matrix will ...
Shuffle sparse matrix encoded as a SciPy coo matrix.
def shuffle_sparse_coo_matrix(sparse_matrix, dropout_rate=0.0, min_dropout_rate=None, max_dropout_rate=None): """Shuffle sparse matrix encoded as a SciPy coo matrix. Args: sparse_matrix: a SciPy coo sparse matrix. dropout_rate: if dropout_rate > 0 then non-zero elements of the...
Plays out a self - play match returning a MCTSPlayer object containing: - the final position - the n x 362 tensor of floats representing the mcts search probabilities - the n - ary tensor of floats representing the original value - net estimate where n is the number of moves in the game
def play(network): """Plays out a self-play match, returning a MCTSPlayer object containing: - the final position - the n x 362 tensor of floats representing the mcts search probabilities - the n-ary tensor of floats representing the original value-net estimate where n is the numbe...
Takes a played game and record results and game data.
def run_game(load_file, selfplay_dir=None, holdout_dir=None, sgf_dir=None, holdout_pct=0.05): """Takes a played game and record results and game data.""" if sgf_dir is not None: minimal_sgf_dir = os.path.join(sgf_dir, 'clean') full_sgf_dir = os.path.join(sgf_dir, 'full') uti...
Entry point for running one selfplay game.
def main(argv): """Entry point for running one selfplay game.""" del argv # Unused flags.mark_flag_as_required('load_file') run_game( load_file=FLAGS.load_file, selfplay_dir=FLAGS.selfplay_dir, holdout_dir=FLAGS.holdout_dir, holdout_pct=FLAGS.holdout_pct, sgf_di...
Apply algorith 2 in https:// arxiv. org/ pdf/ 1901. 08910. pdf.
def resize_matrix(usv, num_rows, num_cols): """Apply algorith 2 in https://arxiv.org/pdf/1901.08910.pdf. Args: usv: matrix to reduce given in SVD form with the spectrum s in increasing order. num_rows: number of rows in the output matrix. num_cols: number of columns in the output matrix. Return...
Fold all values of the matrix into [ 0 1 ].
def normalize_matrix(matrix): """Fold all values of the matrix into [0, 1].""" abs_matrix = np.abs(matrix.copy()) return abs_matrix / abs_matrix.max()
Read and sort lines from the file sorted by decreasing length.
def _get_sorted_inputs(filename): """Read and sort lines from the file sorted by decreasing length. Args: filename: String name of file to read inputs from. Returns: Sorted list of inputs, and dictionary mapping original index->sorted index of each element. """ with tf.gfile.Open(filename) as f: ...
Trim EOS and PAD tokens from ids and decode to return a string.
def _trim_and_decode(ids, subtokenizer): """Trim EOS and PAD tokens from ids, and decode to return a string.""" try: index = list(ids).index(tokenizer.EOS_ID) return subtokenizer.decode(ids[:index]) except ValueError: # No EOS found in sequence return subtokenizer.decode(ids)
Translate lines in file and save to output file if specified.
def translate_file( estimator, subtokenizer, input_file, output_file=None, print_all_translations=True): """Translate lines in file, and save to output file if specified. Args: estimator: tf.Estimator used to generate the translations. subtokenizer: Subtokenizer object for encoding and decoding sou...
Translate a single string.
def translate_text(estimator, subtokenizer, txt): """Translate a single string.""" encoded_txt = _encode_and_add_eos(txt, subtokenizer) def input_fn(): ds = tf.data.Dataset.from_tensors(encoded_txt) ds = ds.batch(_DECODE_BATCH_SIZE) return ds predictions = estimator.predict(input_fn) translation...
Pads vocabulary to a multiple of pad tokens.
def pad_vocabulary(self, vocab, pad): """ Pads vocabulary to a multiple of 'pad' tokens. :param vocab: list with vocabulary :param pad: integer """ vocab_size = len(vocab) padded_vocab_size = (vocab_size + pad - 1) // pad * pad for i in range(0, padded_vo...
Tokenizes single sentence and adds special BOS and EOS tokens.
def segment(self, line): """ Tokenizes single sentence and adds special BOS and EOS tokens. :param line: sentence returns: list representing tokenized sentence """ line = line.strip().split() entry = [self.tok2idx[i] for i in line] entry = [config.BOS] +...
Detokenizes single sentence and removes token separator characters.
def detokenize(self, inputs, delim=' '): """ Detokenizes single sentence and removes token separator characters. :param inputs: sequence of tokens :param delim: tokenization delimiter returns: string representing detokenized sentence """ detok = delim.join([self...
Arguments: x ( list [ Tensor ] ): feature maps for each feature level. Returns: results ( tuple [ Tensor ] ): feature maps after FPN layers. They are ordered from highest resolution first.
def forward(self, x): """ Arguments: x (list[Tensor]): feature maps for each feature level. Returns: results (tuple[Tensor]): feature maps after FPN layers. They are ordered from highest resolution first. """ last_inner = getattr(self, self...
Upload benchmark run information to Bigquery.
def upload_benchmark_run(self, dataset_name, table_name, run_id): """Upload benchmark run information to Bigquery. Args: dataset_name: string, the name of bigquery dataset where the data will be uploaded. table_name: string, the name of bigquery table under the dataset where the dat...
Upload metric information to Bigquery.
def upload_metric(self, dataset_name, table_name, run_id): """Upload metric information to Bigquery. Args: dataset_name: string, the name of bigquery dataset where the data will be uploaded. table_name: string, the name of bigquery table under the dataset where the metric data will ...
Compute BLEU for two files ( reference and hypothesis translation ).
def bleu_wrapper(ref_filename, hyp_filename, case_sensitive=False): """Compute BLEU for two files (reference and hypothesis translation).""" ref_lines = tf.gfile.Open(ref_filename).read().strip().splitlines() hyp_lines = tf.gfile.Open(hyp_filename).read().strip().splitlines() if len(ref_lines) != len(hyp_lines...