partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | LearningCurve.draw | Renders the training and test learning curves. | yellowbrick/model_selection/learning_curve.py | 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... | 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... | [
"Renders",
"the",
"training",
"and",
"test",
"learning",
"curves",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/model_selection/learning_curve.py#L239-L268 | [
"def",
"draw",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Specify the curves to draw and their labels",
"labels",
"=",
"(",
"\"Training Score\"",
",",
"\"Cross Validation Score\"",
")",
"curves",
"=",
"(",
"(",
"self",
".",
"train_scores_mean_",
",",
"self... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | parallel_coordinates | Displays each feature as a vertical axis and each instance as a line.
This helper function is a quick wrapper to utilize the ParallelCoordinates
Visualizer (Transformer) for one-off analysis.
Parameters
----------
X : ndarray or DataFrame of shape n x m
A matrix of n instances with m feat... | yellowbrick/features/pcoords.py | 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... | 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... | [
"Displays",
"each",
"feature",
"as",
"a",
"vertical",
"axis",
"and",
"each",
"instance",
"as",
"a",
"line",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/pcoords.py#L38-L127 | [
"def",
"parallel_coordinates",
"(",
"X",
",",
"y",
",",
"ax",
"=",
"None",
",",
"features",
"=",
"None",
",",
"classes",
"=",
"None",
",",
"normalize",
"=",
"None",
",",
"sample",
"=",
"1.0",
",",
"color",
"=",
"None",
",",
"colormap",
"=",
"None",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ParallelCoordinates.fit | 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
A matrix of n instances with m features
... | yellowbrick/features/pcoords.py | 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
... | 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
... | [
"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",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/pcoords.py#L313-L374 | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Convert from pandas data types",
"if",
"is_dataframe",
"(",
"X",
")",
":",
"# Get column names before reverting to an np.ndarray",
"if",
"self",
".",
"features_",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ParallelCoordinates.draw | 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
y : ndarray of length n
An array or... | yellowbrick/features/pcoords.py | 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
... | 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
... | [
"Called",
"from",
"the",
"fit",
"method",
"this",
"method",
"creates",
"the",
"parallel",
"coordinates",
"canvas",
"and",
"draws",
"each",
"instance",
"and",
"vertical",
"lines",
"on",
"it",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/pcoords.py#L376-L395 | [
"def",
"draw",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"fast",
":",
"return",
"self",
".",
"draw_classes",
"(",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"draw_instances",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ParallelCoordinates.draw_instances | 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 ... | yellowbrick/features/pcoords.py | 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... | 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",
"instance",
".",
"This",
"is",
"the",
"slow",
"mode",
"of",
"drawing",
"since",
"each",
"instance",
"has",
"to",
"be",
"drawn",
"indiv... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/pcoords.py#L397-L439 | [
"def",
"draw_instances",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get alpha from param or default",
"alpha",
"=",
"self",
".",
"alpha",
"or",
"0.25",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"X",
")",
")",
":",
"Xi"... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ParallelCoordinates.draw_classes | 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 u... | yellowbrick/features/pcoords.py | 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... | 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... | [
"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",... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/pcoords.py#L441-L486 | [
"def",
"draw_classes",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get alpha from param or default",
"alpha",
"=",
"self",
".",
"alpha",
"or",
"0.5",
"# Prepare to flatten data within each class:",
"# introduce separation between individual ... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ParallelCoordinates.finalize | Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments. | yellowbrick/features/pcoords.py | 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(
... | 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(
... | [
"Finalize",
"executes",
"any",
"subclass",
"-",
"specific",
"axes",
"finalization",
"steps",
".",
"The",
"user",
"calls",
"poof",
"and",
"poof",
"calls",
"finalize",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/pcoords.py#L488-L520 | [
"def",
"finalize",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set the title",
"self",
".",
"set_title",
"(",
"'Parallel Coordinates for {} Features'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"features_",
")",
")",
")",
"# Add the vertical lines",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | validation_curve | 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.
This helper function... | yellowbrick/model_selection/validation_curve.py | 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... | 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... | [
"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",
"-",
"param... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/model_selection/validation_curve.py#L272-L364 | [
"def",
"validation_curve",
"(",
"model",
",",
"X",
",",
"y",
",",
"param_name",
",",
"param_range",
",",
"ax",
"=",
"None",
",",
"logx",
"=",
"False",
",",
"groups",
"=",
"None",
",",
"cv",
"=",
"None",
",",
"scoring",
"=",
"None",
",",
"n_jobs",
"... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ValidationCurve.fit | 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_features)
Training vector, where n_s... | yellowbrick/model_selection/validation_curve.py | 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... | 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... | [
"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",
... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/model_selection/validation_curve.py#L172-L217 | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"# arguments to pass to sk_validation_curve",
"skvc_kwargs",
"=",
"{",
"key",
":",
"self",
".",
"get_params",
"(",
")",
"[",
"key",
"]",
"for",
"key",
"in",
"(",
"'param_name'",
",",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ClassificationScoreVisualizer.classes_ | Proxy property to smartly access the classes from the estimator or
stored locally on the score visualizer for visualization. | yellowbrick/classifier/base.py | 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:
... | 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:
... | [
"Proxy",
"property",
"to",
"smartly",
"access",
"the",
"classes",
"from",
"the",
"estimator",
"or",
"stored",
"locally",
"on",
"the",
"score",
"visualizer",
"for",
"visualization",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/base.py#L68-L78 | [
"def",
"classes_",
"(",
"self",
")",
":",
"if",
"self",
".",
"__classes",
"is",
"None",
":",
"try",
":",
"return",
"self",
".",
"estimator",
".",
"classes_",
"except",
"AttributeError",
":",
"return",
"None",
"return",
"self",
".",
"__classes"
] | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ClassificationScoreVisualizer.fit | 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 arguments passed to Scikit-Learn API.
Returns
-... | yellowbrick/classifier/base.py | 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... | 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... | [
"Parameters",
"----------"
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/base.py#L84-L111 | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Fit the inner estimator",
"self",
".",
"estimator",
".",
"fit",
"(",
"X",
",",
"y",
")",
"# Extract the classes from the estimator",
"if",
"self",
".",
"cla... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | _load_dataset | Load a dataset by name and return specified format. | yellowbrick/datasets/loaders.py | 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() | 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",
"dataset",
"by",
"name",
"and",
"return",
"specified",
"format",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/datasets/loaders.py#L42-L50 | [
"def",
"_load_dataset",
"(",
"name",
",",
"data_home",
"=",
"None",
",",
"return_dataset",
"=",
"False",
")",
":",
"info",
"=",
"DATASETS",
"[",
"name",
"]",
"data",
"=",
"Dataset",
"(",
"name",
",",
"data_home",
"=",
"data_home",
",",
"*",
"*",
"info"... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | _load_corpus | Load a corpus object by name. | yellowbrick/datasets/loaders.py | def _load_corpus(name, data_home=None):
"""
Load a corpus object by name.
"""
info = DATASETS[name]
return Corpus(name, data_home=data_home, **info) | def _load_corpus(name, data_home=None):
"""
Load a corpus object by name.
"""
info = DATASETS[name]
return Corpus(name, data_home=data_home, **info) | [
"Load",
"a",
"corpus",
"object",
"by",
"name",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/datasets/loaders.py#L53-L58 | [
"def",
"_load_corpus",
"(",
"name",
",",
"data_home",
"=",
"None",
")",
":",
"info",
"=",
"DATASETS",
"[",
"name",
"]",
"return",
"Corpus",
"(",
"name",
",",
"data_home",
"=",
"data_home",
",",
"*",
"*",
"info",
")"
] | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | resolve_colors | 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.
Parameters
----------
n_colors : int, default: None
Specify the... | yellowbrick/style/colors.py | 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... | 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... | [
"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",
"(... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/style/colors.py#L57-L121 | [
"def",
"resolve_colors",
"(",
"n_colors",
"=",
"None",
",",
"colormap",
"=",
"None",
",",
"colors",
"=",
"None",
")",
":",
"# Work with the colormap if specified and colors is not",
"if",
"colormap",
"is",
"not",
"None",
"and",
"colors",
"is",
"None",
":",
"if",... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ColorMap.colors | Converts color strings into a color listing. | yellowbrick/style/colors.py | 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(... | 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(... | [
"Converts",
"color",
"strings",
"into",
"a",
"color",
"listing",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/style/colors.py#L145-L161 | [
"def",
"colors",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"# Must import here to avoid recursive import",
"from",
".",
"palettes",
"import",
"PALETTES",
"if",
"value",
"not",
"in",
"PALETTES",
":",
"raise",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | memoized | 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 method to memoize for subsequent ac... | yellowbrick/utils/decorators.py | 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... | 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... | [
"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",
"preventin... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/utils/decorators.py#L27-L51 | [
"def",
"memoized",
"(",
"fget",
")",
":",
"attr_name",
"=",
"'_{0}'",
".",
"format",
"(",
"fget",
".",
"__name__",
")",
"@",
"wraps",
"(",
"fget",
")",
"def",
"fget_memoized",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"attr_nam... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | anscombe | Creates 2x2 grid plot of the 4 anscombe datasets for illustration. | yellowbrick/anscombe.py | 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... | 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... | [
"Creates",
"2x2",
"grid",
"plot",
"of",
"the",
"4",
"anscombe",
"datasets",
"for",
"illustration",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/anscombe.py#L51-L72 | [
"def",
"anscombe",
"(",
")",
":",
"_",
",",
"(",
"(",
"axa",
",",
"axb",
")",
",",
"(",
"axc",
",",
"axd",
")",
")",
"=",
"plt",
".",
"subplots",
"(",
"2",
",",
"2",
",",
"sharex",
"=",
"'col'",
",",
"sharey",
"=",
"'row'",
")",
"colors",
"... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | radviz | 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 RadialVisualizer
(Transformer) for one-off analysis.
Parameters
----------
X : ndarray or DataFrame of shape n x m
... | yellowbrick/features/radviz.py | 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... | 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... | [
"Displays",
"each",
"feature",
"as",
"an",
"axis",
"around",
"a",
"circle",
"surrounding",
"a",
"scatter",
"plot",
"whose",
"points",
"are",
"each",
"individual",
"instance",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/radviz.py#L34-L86 | [
"def",
"radviz",
"(",
"X",
",",
"y",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"features",
"=",
"None",
",",
"classes",
"=",
"None",
",",
"color",
"=",
"None",
",",
"colormap",
"=",
"None",
",",
"alpha",
"=",
"1.0",
",",
"*",
"*",
"kwargs",
")"... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | RadialVisualizer.normalize | MinMax normalization to fit a matrix in the space [0,1] by column. | yellowbrick/features/radviz.py | 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, :]) | 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, :]) | [
"MinMax",
"normalization",
"to",
"fit",
"a",
"matrix",
"in",
"the",
"space",
"[",
"0",
"1",
"]",
"by",
"column",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/radviz.py#L157-L163 | [
"def",
"normalize",
"(",
"X",
")",
":",
"a",
"=",
"X",
".",
"min",
"(",
"axis",
"=",
"0",
")",
"b",
"=",
"X",
".",
"max",
"(",
"axis",
"=",
"0",
")",
"return",
"(",
"X",
"-",
"a",
"[",
"np",
".",
"newaxis",
",",
":",
"]",
")",
"/",
"(",... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | RadialVisualizer.draw | 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. | yellowbrick/features/radviz.py | 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):... | 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):... | [
"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",
"da... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/radviz.py#L165-L249 | [
"def",
"draw",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"# Convert from dataframe",
"if",
"is_dataframe",
"(",
"X",
")",
":",
"X",
"=",
"X",
".",
"values",
"# Clean out nans and warn that the user they aren't plotted",
"nan_warnings",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | RadialVisualizer.finalize | Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments. | yellowbrick/features/radviz.py | 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(
... | 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(
... | [
"Finalize",
"executes",
"any",
"subclass",
"-",
"specific",
"axes",
"finalization",
"steps",
".",
"The",
"user",
"calls",
"poof",
"and",
"poof",
"calls",
"finalize",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/features/radviz.py#L251-L272 | [
"def",
"finalize",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set the title",
"self",
".",
"set_title",
"(",
"'RadViz for {} Features'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"features_",
")",
")",
")",
"# Remove the ticks from the graph",
"self... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | percentile_index | Returns the index of the value at the Qth percentile in array a. | yellowbrick/cluster/icdm.py | 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] | 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] | [
"Returns",
"the",
"index",
"of",
"the",
"value",
"at",
"the",
"Qth",
"percentile",
"in",
"array",
"a",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L387-L393 | [
"def",
"percentile_index",
"(",
"a",
",",
"q",
")",
":",
"return",
"np",
".",
"where",
"(",
"a",
"==",
"np",
".",
"percentile",
"(",
"a",
",",
"q",
",",
"interpolation",
"=",
"'nearest'",
")",
")",
"[",
"0",
"]",
"[",
"0",
"]"
] | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | validate_string_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. | yellowbrick/cluster/icdm.py | 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 {} '{}',... | 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 {} '{}',... | [
"Raises",
"a",
"well",
"formatted",
"exception",
"if",
"s",
"is",
"not",
"in",
"valid",
"otherwise",
"does",
"not",
"raise",
"an",
"exception",
".",
"Uses",
"param_name",
"to",
"identify",
"the",
"parameter",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L396-L406 | [
"def",
"validate_string_param",
"(",
"s",
",",
"valid",
",",
"param_name",
"=",
"\"param\"",
")",
":",
"if",
"s",
".",
"lower",
"(",
")",
"not",
"in",
"valid",
":",
"raise",
"YellowbrickValueError",
"(",
"\"unknown {} '{}', chose from '{}'\"",
".",
"format",
"... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | intercluster_distance | Quick Method:
Intercluster distance maps display an embedding of the cluster centers in
2 dimensions with the distance to other centers preserved. E.g. the closer
to centers are in the visualization, the closer they are in the original
feature space. The clusters are sized according to a scoring metric... | yellowbrick/cluster/icdm.py | 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... | 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... | [
"Quick",
"Method",
":"
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L427-L519 | [
"def",
"intercluster_distance",
"(",
"model",
",",
"X",
",",
"y",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"min_size",
"=",
"400",
",",
"max_size",
"=",
"25000",
",",
"embedding",
"=",
"'mds'",
",",
"scoring",
"=",
"'membership'",
",",
"legend",
"=",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | InterclusterDistance.lax | 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. | yellowbrick/cluster/icdm.py | 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... | 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... | [
"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"... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L184-L211 | [
"def",
"lax",
"(",
"self",
")",
":",
"if",
"inset_locator",
"is",
"None",
":",
"raise",
"YellowbrickValueError",
"(",
"(",
"\"intercluster distance map legend requires matplotlib 2.0.2 or greater \"",
"\"please upgrade matplotlib or set legend=False on the visualizer\"",
")",
")"... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | InterclusterDistance.transformer | Creates the internal transformer that maps the cluster center's high
dimensional space to its two dimensional space. | yellowbrick/cluster/icdm.py | 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... | 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... | [
"Creates",
"the",
"internal",
"transformer",
"that",
"maps",
"the",
"cluster",
"center",
"s",
"high",
"dimensional",
"space",
"to",
"its",
"two",
"dimensional",
"space",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L214-L227 | [
"def",
"transformer",
"(",
"self",
")",
":",
"ttype",
"=",
"self",
".",
"embedding",
".",
"lower",
"(",
")",
"# transformer method type",
"if",
"ttype",
"==",
"'mds'",
":",
"return",
"MDS",
"(",
"n_components",
"=",
"2",
",",
"random_state",
"=",
"self",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | InterclusterDistance.cluster_centers_ | 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. | yellowbrick/cluster/icdm.py | 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... | 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... | [
"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",
"be... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L230-L247 | [
"def",
"cluster_centers_",
"(",
"self",
")",
":",
"# TODO: Handle agglomerative clustering and LDA",
"for",
"attr",
"in",
"(",
"'cluster_centers_'",
",",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"self",
".",
"estimator",
",",
"attr",
")",
"except",
"Attri... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | InterclusterDistance.fit | Fit the clustering model, computing the centers then embeds the centers
into 2D space using the embedding method specified. | yellowbrick/cluster/icdm.py | 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)
... | 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)
... | [
"Fit",
"the",
"clustering",
"model",
"computing",
"the",
"centers",
"then",
"embeds",
"the",
"centers",
"into",
"2D",
"space",
"using",
"the",
"embedding",
"method",
"specified",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L249-L268 | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"with",
"Timer",
"(",
")",
"as",
"self",
".",
"fit_time_",
":",
"# Fit the underlying estimator",
"self",
".",
"estimator",
".",
"fit",
"(",
"X",
",",
"y",
")",
"# Get the centers",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | InterclusterDistance.draw | Draw the embedded centers with their sizes on the visualization. | yellowbrick/cluster/icdm.py | 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(
... | 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(
... | [
"Draw",
"the",
"embedded",
"centers",
"with",
"their",
"sizes",
"on",
"the",
"visualization",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L270-L291 | [
"def",
"draw",
"(",
"self",
")",
":",
"# 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",
"(",
"self",
".",
"e... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | InterclusterDistance.finalize | 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. | yellowbrick/cluster/icdm.py | 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 ... | 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 ... | [
"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",
"fu... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L293-L318 | [
"def",
"finalize",
"(",
"self",
")",
":",
"# Set the default title if a user hasn't supplied one",
"self",
".",
"set_title",
"(",
"\"{} Intercluster Distance Map (via {})\"",
".",
"format",
"(",
"self",
".",
"estimator",
".",
"__class__",
".",
"__name__",
",",
"self",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | InterclusterDistance._score_clusters | Determines the "scores" of the cluster, the metric that determines the
size of the cluster visualized on the visualization. | yellowbrick/cluster/icdm.py | 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... | 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... | [
"Determines",
"the",
"scores",
"of",
"the",
"cluster",
"the",
"metric",
"that",
"determines",
"the",
"size",
"of",
"the",
"cluster",
"visualized",
"on",
"the",
"visualization",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L320-L330 | [
"def",
"_score_clusters",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"stype",
"=",
"self",
".",
"scoring",
".",
"lower",
"(",
")",
"# scoring method name",
"if",
"stype",
"==",
"\"membership\"",
":",
"return",
"np",
".",
"bincount",
"(",
"... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | InterclusterDistance._get_cluster_sizes | Returns the marker size (in points, e.g. area of the circle) based on
the scores, using the prop_to_size scaling mechanism. | yellowbrick/cluster/icdm.py | 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... | 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... | [
"Returns",
"the",
"marker",
"size",
"(",
"in",
"points",
"e",
".",
"g",
".",
"area",
"of",
"the",
"circle",
")",
"based",
"on",
"the",
"scores",
"using",
"the",
"prop_to_size",
"scaling",
"mechanism",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L332-L340 | [
"def",
"_get_cluster_sizes",
"(",
"self",
")",
":",
"# NOTE: log and power are hardcoded, should we allow the user to specify?",
"return",
"prop_to_size",
"(",
"self",
".",
"scores_",
",",
"mi",
"=",
"self",
".",
"min_size",
",",
"ma",
"=",
"self",
".",
"max_size",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | InterclusterDistance._make_size_legend | Draw a legend that shows relative sizes of the clusters at the 25th,
50th, and 75th percentile based on the current scoring metric. | yellowbrick/cluster/icdm.py | 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... | 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... | [
"Draw",
"a",
"legend",
"that",
"shows",
"relative",
"sizes",
"of",
"the",
"clusters",
"at",
"the",
"25th",
"50th",
"and",
"75th",
"percentile",
"based",
"on",
"the",
"current",
"scoring",
"metric",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/icdm.py#L342-L380 | [
"def",
"_make_size_legend",
"(",
"self",
")",
":",
"# Compute the size of the markers and scale them to our figure size",
"# NOTE: the marker size is the area of the plot, we need to compute the",
"# radius of the markers.",
"areas",
"=",
"self",
".",
"_get_cluster_sizes",
"(",
")",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | manual_legend | 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 t... | yellowbrick/draw.py | 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... | 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... | [
"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",
... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/draw.py#L29-L90 | [
"def",
"manual_legend",
"(",
"g",
",",
"labels",
",",
"colors",
",",
"*",
"*",
"legend_kwargs",
")",
":",
"# Get access to the matplotlib Axes",
"if",
"isinstance",
"(",
"g",
",",
"Visualizer",
")",
":",
"g",
"=",
"g",
".",
"ax",
"elif",
"g",
"is",
"None... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | freqdist | 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 matrix of n instances with m features. In the case of text,
... | yellowbrick/text/freqdist.py | 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... | 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... | [
"Displays",
"frequency",
"distribution",
"plot",
"for",
"text",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/text/freqdist.py#L32-L75 | [
"def",
"freqdist",
"(",
"X",
",",
"y",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"color",
"=",
"None",
",",
"N",
"=",
"50",
",",
"*",
"*",
"kwargs",
")",
":",
"# Instantiate the visualizer",
"visualizer",
"=",
"FreqDistVisualizer",
"(",
"ax",
",",
"X... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | FrequencyVisualizer.count | 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 in
order to sum the word fr... | yellowbrick/text/freqdist.py | 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... | 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... | [
"Called",
"from",
"the",
"fit",
"method",
"this",
"method",
"gets",
"all",
"the",
"words",
"from",
"the",
"corpus",
"and",
"their",
"corresponding",
"frequency",
"counts",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/text/freqdist.py#L132-L155 | [
"def",
"count",
"(",
"self",
",",
"X",
")",
":",
"# Sum on axis 0 (by columns), each column is a word",
"# Convert the matrix to an array",
"# Squeeze to remove the 1 dimension objects (like ravel)",
"return",
"np",
".",
"squeeze",
"(",
"np",
".",
"asarray",
"(",
"X",
".",
... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | FrequencyVisualizer.fit | 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).
Parameters
----------
X : n... | yellowbrick/text/freqdist.py | 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).
... | 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).
... | [
"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",
"actua... | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/text/freqdist.py#L157-L200 | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"# Compute the conditional word frequency",
"if",
"y",
"is",
"not",
"None",
":",
"# Fit the frequencies",
"self",
".",
"conditional_freqdist_",
"=",
"{",
"}",
"# Conditional frequency distributi... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | FrequencyVisualizer.draw | Called from the fit method, this method creates the canvas and
draws the distribution plot on it.
Parameters
----------
kwargs: generic keyword arguments. | yellowbrick/text/freqdist.py | 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... | 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... | [
"Called",
"from",
"the",
"fit",
"method",
"this",
"method",
"creates",
"the",
"canvas",
"and",
"draws",
"the",
"distribution",
"plot",
"on",
"it",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/text/freqdist.py#L202-L263 | [
"def",
"draw",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Prepare the data",
"bins",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"N",
")",
"words",
"=",
"[",
"self",
".",
"features",
"[",
"i",
"]",
"for",
"i",
"in",
"self",
".",
"sorted_"... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | FrequencyVisualizer.finalize | The finalize method executes any subclass-specific axes
finalization steps. The user calls poof & poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments. | yellowbrick/text/freqdist.py | 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(
... | 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(
... | [
"The",
"finalize",
"method",
"executes",
"any",
"subclass",
"-",
"specific",
"axes",
"finalization",
"steps",
".",
"The",
"user",
"calls",
"poof",
"&",
"poof",
"calls",
"finalize",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/text/freqdist.py#L265-L290 | [
"def",
"finalize",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set the title",
"self",
".",
"set_title",
"(",
"'Frequency Distribution of Top {} tokens'",
".",
"format",
"(",
"self",
".",
"N",
")",
")",
"# Create the vocab, count, and hapaxes labels",
"infola... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | classification_report | 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 wrapper to utilize the ClassificationReport
ScoreVisualizer for one-off analysis.
Parameters
----------
X : ndarray ... | yellowbrick/classifier/classification_report.py | 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... | 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... | [
"Quick",
"method",
":"
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/classification_report.py#L238-L285 | [
"def",
"classification_report",
"(",
"model",
",",
"X",
",",
"y",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"classes",
"=",
"None",
",",
"random_state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Instantiate the visualizer",
"visualizer",
"=",
"C... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ClassificationReport.score | 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 of target or class values
Returns
------... | yellowbrick/classifier/classification_report.py | 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... | 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... | [
"Generates",
"the",
"Scikit",
"-",
"Learn",
"classification",
"report",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/classification_report.py#L111-L154 | [
"def",
"score",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"y_pred",
"=",
"self",
".",
"predict",
"(",
"X",
")",
"scores",
"=",
"precision_recall_fscore_support",
"(",
"y",
",",
"y_pred",
")",
"# Calculate the perc... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ClassificationReport.draw | Renders the classification report across each axis. | yellowbrick/classifier/classification_report.py | 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... | 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... | [
"Renders",
"the",
"classification",
"report",
"across",
"each",
"axis",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/classification_report.py#L156-L213 | [
"def",
"draw",
"(",
"self",
")",
":",
"# Create display grid",
"cr_display",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"self",
".",
"classes_",
")",
",",
"len",
"(",
"self",
".",
"_displayed_scores",
")",
")",
")",
"# For each class row, append columns ... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | ClassificationReport.finalize | Finalize executes any subclass-specific axes finalization steps.
The user calls poof and poof calls finalize.
Parameters
----------
kwargs: generic keyword arguments. | yellowbrick/classifier/classification_report.py | 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
... | 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
... | [
"Finalize",
"executes",
"any",
"subclass",
"-",
"specific",
"axes",
"finalization",
"steps",
".",
"The",
"user",
"calls",
"poof",
"and",
"poof",
"calls",
"finalize",
"."
] | DistrictDataLabs/yellowbrick | python | https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/classifier/classification_report.py#L215-L235 | [
"def",
"finalize",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set the title of the classifiation report",
"self",
".",
"set_title",
"(",
"'{} Classification Report'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"# Set the tick marks appropriately",
"s... | 59b67236a3862c73363e8edad7cd86da5b69e3b2 |
train | _deprecated_getitem_method | 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
-------
__getitem__ : callable[any, str]
... | pylivetrader/protocol.py | 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
... | 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
... | [
"Create",
"a",
"deprecated",
"__getitem__",
"method",
"that",
"tells",
"users",
"to",
"use",
"getattr",
"instead",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/protocol.py#L85-L115 | [
"def",
"_deprecated_getitem_method",
"(",
"name",
",",
"attrs",
")",
":",
"attrs",
"=",
"frozenset",
"(",
"attrs",
")",
"msg",
"=",
"(",
"\"'{name}[{attr!r}]' is deprecated, please use\"",
"\" '{name}.{attr}' instead\"",
")",
"def",
"__getitem__",
"(",
"self",
",",
... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | skip_http_error | A decorator to wrap with try..except to swallow
specific HTTP errors.
@skip_http_error((404, 503))
def fetch():
... | pylivetrader/backend/alpaca.py | 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:
... | 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:
... | [
"A",
"decorator",
"to",
"wrap",
"with",
"try",
"..",
"except",
"to",
"swallow",
"specific",
"HTTP",
"errors",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/backend/alpaca.py#L66-L89 | [
"def",
"skip_http_error",
"(",
"statuses",
")",
":",
"assert",
"isinstance",
"(",
"statuses",
",",
"tuple",
")",
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | Backend._symbols2assets | Utility for debug/testing | pylivetrader/backend/alpaca.py | 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] | 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] | [
"Utility",
"for",
"debug",
"/",
"testing"
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/backend/alpaca.py#L161-L167 | [
"def",
"_symbols2assets",
"(",
"self",
",",
"symbols",
")",
":",
"assets",
"=",
"{",
"a",
".",
"symbol",
":",
"a",
"for",
"a",
"in",
"self",
".",
"get_equities",
"(",
")",
"}",
"return",
"[",
"assets",
"[",
"symbol",
"]",
"for",
"symbol",
"in",
"sy... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | Backend.get_bars | Interface method.
Return: pd.Dataframe() with columns MultiIndex [asset -> OHLCV] | pylivetrader/backend/alpaca.py | 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'
... | 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'
... | [
"Interface",
"method",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/backend/alpaca.py#L474-L527 | [
"def",
"get_bars",
"(",
"self",
",",
"assets",
",",
"data_frequency",
",",
"bar_count",
"=",
"500",
")",
":",
"assets_is_scalar",
"=",
"not",
"isinstance",
"(",
"assets",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
"is_daily",
"=",
"'d'",
"in... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | Backend._symbol_bars | Query historic_agg either minute or day in parallel
for multiple symbols, and return in dict.
symbols: list[str]
size: str ('day', 'minute')
_from: str or pd.Timestamp
to: str or pd.Timestamp
limit: str or int
return: dict[str -> pd.DataFrame] | pylivetrader/backend/alpaca.py | 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... | 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",
"historic_agg",
"either",
"minute",
"or",
"day",
"in",
"parallel",
"for",
"multiple",
"symbols",
"and",
"return",
"in",
"dict",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/backend/alpaca.py#L529-L576 | [
"def",
"_symbol_bars",
"(",
"self",
",",
"symbols",
",",
"size",
",",
"_from",
"=",
"None",
",",
"to",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"assert",
"size",
"in",
"(",
"'day'",
",",
"'minute'",
")",
"# temp workaround for less bars after mask... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | Backend._symbol_trades | Query last_trade in parallel for multiple symbols and
return in dict.
symbols: list[str]
return: dict[str -> polygon.Trade] | pylivetrader/backend/alpaca.py | 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... | 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... | [
"Query",
"last_trade",
"in",
"parallel",
"for",
"multiple",
"symbols",
"and",
"return",
"in",
"dict",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/backend/alpaca.py#L578-L592 | [
"def",
"_symbol_trades",
"(",
"self",
",",
"symbols",
")",
":",
"@",
"skip_http_error",
"(",
"(",
"404",
",",
"504",
")",
")",
"def",
"fetch",
"(",
"symbol",
")",
":",
"return",
"self",
".",
"_api",
".",
"polygon",
".",
"last_trade",
"(",
"symbol",
"... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | Algorithm.record | 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 ``analyze`` and returned from
:func:`~zip... | pylivetrader/algorithm.py | 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... | 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... | [
"Track",
"and",
"record",
"values",
"each",
"day",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/algorithm.py#L395-L418 | [
"def",
"record",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Make 2 objects both referencing the same iterator",
"args",
"=",
"[",
"iter",
"(",
"args",
")",
"]",
"*",
"2",
"# Zip generates list entries by calling `next` on each iterator it",
... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | Algorithm.symbols | 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 resolve the ``Asset`` by ``symbol``. | pylivetrader/algorithm.py | 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 ... | 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 ... | [
"Lookup",
"equities",
"by",
"symbol",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/algorithm.py#L446-L458 | [
"def",
"symbols",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"self",
".",
"symbol",
"(",
"idendifier",
",",
"*",
"*",
"kwargs",
")",
"for",
"idendifier",
"in",
"args",
"]"
] | fd328b6595428c0789d9f218df34623f83a02b8b |
train | Algorithm.get_all_orders | 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 provid... | pylivetrader/algorithm.py | 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... | 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... | [
"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",
"spec... | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/algorithm.py#L653-L682 | [
"def",
"get_all_orders",
"(",
"self",
",",
"asset",
"=",
"None",
",",
"before",
"=",
"None",
",",
"status",
"=",
"'all'",
",",
"days_back",
"=",
"None",
")",
":",
"orders",
"=",
"self",
".",
"_backend",
".",
"all_orders",
"(",
"before",
",",
"status",
... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | Algorithm.history | DEPRECATED: use ``data.history`` instead. | pylivetrader/algorithm.py | 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,
) | 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,
) | [
"DEPRECATED",
":",
"use",
"data",
".",
"history",
"instead",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/algorithm.py#L697-L707 | [
"def",
"history",
"(",
"self",
",",
"bar_count",
",",
"frequency",
",",
"field",
",",
"ffill",
"=",
"True",
")",
":",
"return",
"self",
".",
"get_history_window",
"(",
"bar_count",
",",
"frequency",
",",
"self",
".",
"_calculate_universe",
"(",
")",
",",
... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | Algorithm._calculate_order_value_amount | Calculates how many shares/contracts to order based on the type of
asset being ordered. | pylivetrader/algorithm.py | 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... | 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... | [
"Calculates",
"how",
"many",
"shares",
"/",
"contracts",
"to",
"order",
"based",
"on",
"the",
"type",
"of",
"asset",
"being",
"ordered",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/algorithm.py#L814-L842 | [
"def",
"_calculate_order_value_amount",
"(",
"self",
",",
"asset",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"executor",
".",
"current_data",
".",
"can_trade",
"(",
"asset",
")",
":",
"raise",
"CannotOrderDelistedAsset",
"(",
"msg",
"=",
"\"Cannot orde... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | Algorithm.set_do_not_order_list | Set a restriction on which assets can be ordered.
Parameters
----------
restricted_list : container[Asset], SecurityList
The assets that cannot be ordered. | pylivetrader/algorithm.py | 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... | 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... | [
"Set",
"a",
"restriction",
"on",
"which",
"assets",
"can",
"be",
"ordered",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/algorithm.py#L1000-L1029 | [
"def",
"set_do_not_order_list",
"(",
"self",
",",
"restricted_list",
",",
"on_error",
"=",
"'fail'",
")",
":",
"if",
"isinstance",
"(",
"restricted_list",
",",
"SecurityList",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`set_do_not_order_list(security_lists.leveraged_e... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | translate | translate zipline script into pylivetrader script. | pylivetrader/loader.py | def translate(script):
'''translate zipline script into pylivetrader script.
'''
tree = ast.parse(script)
ZiplineImportVisitor().visit(tree)
return astor.to_source(tree) | def translate(script):
'''translate zipline script into pylivetrader script.
'''
tree = ast.parse(script)
ZiplineImportVisitor().visit(tree)
return astor.to_source(tree) | [
"translate",
"zipline",
"script",
"into",
"pylivetrader",
"script",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/loader.py#L72-L79 | [
"def",
"translate",
"(",
"script",
")",
":",
"tree",
"=",
"ast",
".",
"parse",
"(",
"script",
")",
"ZiplineImportVisitor",
"(",
")",
".",
"visit",
"(",
"tree",
")",
"return",
"astor",
".",
"to_source",
"(",
"tree",
")"
] | fd328b6595428c0789d9f218df34623f83a02b8b |
train | make_eventrule | Constructs an event rule from the factory api. | pylivetrader/misc/events.py | 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... | 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... | [
"Constructs",
"an",
"event",
"rule",
"from",
"the",
"factory",
"api",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/misc/events.py#L625-L641 | [
"def",
"make_eventrule",
"(",
"date_rule",
",",
"time_rule",
",",
"cal",
",",
"half_days",
"=",
"True",
")",
":",
"# Insert the calendar in to the individual rules",
"date_rule",
".",
"cal",
"=",
"cal",
"time_rule",
".",
"cal",
"=",
"cal",
"if",
"half_days",
":"... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | build_sector_fundamentals | 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 ne... | examples/graham-fundamentals/GrahamFundamentals.py | 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... | 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... | [
"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",
"earn... | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/examples/graham-fundamentals/GrahamFundamentals.py#L146-L202 | [
"def",
"build_sector_fundamentals",
"(",
"sector",
")",
":",
"stocks",
"=",
"get_sector",
"(",
"sector",
")",
"if",
"len",
"(",
"stocks",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Invalid sector name: {}\"",
".",
"format",
"(",
"sector",
")",
")",
... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | make_pipeline | Create our pipeline. | examples/q01/algo.py | 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... | 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... | [
"Create",
"our",
"pipeline",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/examples/q01/algo.py#L82-L158 | [
"def",
"make_pipeline",
"(",
"context",
")",
":",
"# Filter for primary share equities. IsPrimaryShare is a built-in filter.",
"primary_share",
"=",
"IsPrimaryShare",
"(",
")",
"# Not when-issued equities.",
"not_wi",
"=",
"~",
"IEXCompany",
".",
"symbol",
".",
"latest",
".... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | my_record_vars | Record variables at the end of each day. | examples/q01/algo.py | 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... | 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... | [
"Record",
"variables",
"at",
"the",
"end",
"of",
"each",
"day",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/examples/q01/algo.py#L291-L304 | [
"def",
"my_record_vars",
"(",
"context",
",",
"data",
")",
":",
"# Record our variables.",
"record",
"(",
"leverage",
"=",
"context",
".",
"account",
".",
"leverage",
")",
"record",
"(",
"positions",
"=",
"len",
"(",
"context",
".",
"portfolio",
".",
"positi... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | AssetFinder.retrieve_all | 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 `SidsNotFound`.
Returns
-------
assets : list[Asse... | pylivetrader/assets/finder.py | 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... | 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",
"all",
"assets",
"in",
"sids",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/assets/finder.py#L57-L95 | [
"def",
"retrieve_all",
"(",
"self",
",",
"sids",
",",
"default_none",
"=",
"False",
")",
":",
"failures",
"=",
"set",
"(",
")",
"hits",
"=",
"{",
"}",
"for",
"sid",
"in",
"sids",
":",
"try",
":",
"hits",
"[",
"sid",
"]",
"=",
"self",
".",
"_asset... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | AssetFinder.retrieve_asset | Retrieve the Asset for a given sid. | pylivetrader/assets/finder.py | 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... | 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",
"the",
"Asset",
"for",
"a",
"given",
"sid",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/assets/finder.py#L97-L107 | [
"def",
"retrieve_asset",
"(",
"self",
",",
"sid",
",",
"default_none",
"=",
"False",
")",
":",
"try",
":",
"asset",
"=",
"self",
".",
"_asset_cache",
"[",
"sid",
"]",
"if",
"asset",
"is",
"None",
"and",
"not",
"default_none",
":",
"raise",
"SidsNotFound"... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | AssetFinder.retrieve_equities | 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.
Parameters
----------
sids : iter... | pylivetrader/assets/finder.py | 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.
... | 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.
... | [
"Retrieve",
"Equity",
"objects",
"for",
"a",
"list",
"of",
"sids",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/assets/finder.py#L109-L138 | [
"def",
"retrieve_equities",
"(",
"self",
",",
"sids",
")",
":",
"cache",
"=",
"self",
".",
"_asset_cache",
"try",
":",
"return",
"{",
"k",
":",
"cache",
"[",
"k",
"]",
"for",
"k",
"in",
"sids",
"}",
"except",
"KeyError",
":",
"raise",
"EquitiesNotFound... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | asymmetric_round_price_to_penny | 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.
If prefer_round_down == True:
When .05 below to .95 abo... | pylivetrader/finance/execution.py | 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... | 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... | [
"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",
"prefer... | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/finance/execution.py#L147-L174 | [
"def",
"asymmetric_round_price_to_penny",
"(",
"price",
",",
"prefer_round_down",
",",
"diff",
"=",
"(",
"0.0095",
"-",
".005",
")",
")",
":",
"# Subtracting an epsilon from diff to enforce the open-ness of the upper",
"# bound on buys and the lower bound on sells. Using the actua... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | BarData.can_trade | 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'... | pylivetrader/data/bardata.py | 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)... | 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",
"all",
"of",
"the",
"following",
"are",
"true",
":",
"1",
")",
"the",
"asset",
"is",
"alive",
"for",
"the",
"session",
"of",
"the",
"current",
"simulation",
"time"... | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/data/bardata.py#L180-L231 | [
"def",
"can_trade",
"(",
"self",
",",
"assets",
")",
":",
"dt",
"=",
"self",
".",
"datetime",
"if",
"self",
".",
"_adjust_minutes",
":",
"adjusted_dt",
"=",
"self",
".",
"_get_current_minute",
"(",
")",
"else",
":",
"adjusted_dt",
"=",
"dt",
"data_portal",... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | BarData.is_stale | 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 use the
current time to check if the ass... | pylivetrader/data/bardata.py | 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 ... | 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 ... | [
"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",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/data/bardata.py#L269-L306 | [
"def",
"is_stale",
"(",
"self",
",",
"assets",
")",
":",
"dt",
"=",
"self",
".",
"datetime",
"if",
"self",
".",
"_adjust_minutes",
":",
"adjusted_dt",
"=",
"self",
".",
"_get_current_minute",
"(",
")",
"else",
":",
"adjusted_dt",
"=",
"dt",
"data_portal",
... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | BarData._get_current_minute | 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 market minute, like if we're in
before_tra... | pylivetrader/data/bardata.py | 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... | 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... | [
"Internal",
"utility",
"method",
"to",
"get",
"the",
"current",
"simulation",
"time",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/data/bardata.py#L333-L357 | [
"def",
"_get_current_minute",
"(",
"self",
")",
":",
"dt",
"=",
"self",
".",
"datetime",
"if",
"self",
".",
"_adjust_minutes",
":",
"dt",
"=",
"self",
".",
"data_portal",
".",
"trading_calendar",
".",
"previous_minute",
"(",
"dt",
")",
"if",
"self",
".",
... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | api_method | Redirect pylivetrader.api.* operations to the algorithm
in the local context. | pylivetrader/misc/api_context.py | 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(
... | 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(
... | [
"Redirect",
"pylivetrader",
".",
"api",
".",
"*",
"operations",
"to",
"the",
"algorithm",
"in",
"the",
"local",
"context",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/misc/api_context.py#L48-L69 | [
"def",
"api_method",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get the instance and call the method",
"algorithm",
"=",
"get_context",
"(",
")",
"if",
"algorithm",
"is",
"No... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | make_pipeline | Create our pipeline. | examples/q01/original.py | 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... | 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... | [
"Create",
"our",
"pipeline",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/examples/q01/original.py#L70-L168 | [
"def",
"make_pipeline",
"(",
"context",
")",
":",
"# 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 stoc... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | parallelize | 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.
If workers argument is not provided... | pylivetrader/misc/parallel_utils.py | 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... | 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... | [
"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",... | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/misc/parallel_utils.py#L10-L43 | [
"def",
"parallelize",
"(",
"mapfunc",
",",
"workers",
"=",
"None",
")",
":",
"workers",
"=",
"workers",
"if",
"workers",
"else",
"_get_default_workers",
"(",
")",
"def",
"wrapper",
"(",
"args_list",
")",
":",
"result",
"=",
"{",
"}",
"with",
"concurrent",
... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | DataPortal.get_adjusted_value | TODO:
for external data (fetch_csv) support, need to update logic here. | pylivetrader/data/data_portal.py | 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(
... | 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(
... | [
"TODO",
":",
"for",
"external",
"data",
"(",
"fetch_csv",
")",
"support",
"need",
"to",
"update",
"logic",
"here",
"."
] | alpacahq/pylivetrader | python | https://github.com/alpacahq/pylivetrader/blob/fd328b6595428c0789d9f218df34623f83a02b8b/pylivetrader/data/data_portal.py#L39-L52 | [
"def",
"get_adjusted_value",
"(",
"self",
",",
"assets",
",",
"field",
",",
"dt",
",",
"perspective_dt",
",",
"data_frequency",
")",
":",
"return",
"self",
".",
"backend",
".",
"get_spot_value",
"(",
"assets",
",",
"field",
",",
"dt",
",",
"data_frequency",
... | fd328b6595428c0789d9f218df34623f83a02b8b |
train | load_df_from_file | Wrapper around pandas' read_csv. | data_generation/fractal_graph_expansions/util.py | 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 | 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 | [
"Wrapper",
"around",
"pandas",
"read_csv",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/util.py#L34-L38 | [
"def",
"load_df_from_file",
"(",
"file_path",
",",
"sep",
"=",
"\",\"",
",",
"header",
"=",
"0",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"file_path",
")",
"as",
"infile",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"infile",
",",
"s... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | serialize_to_file | Pickle obj to file_name. | data_generation/fractal_graph_expansions/util.py | 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) | 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) | [
"Pickle",
"obj",
"to",
"file_name",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/util.py#L62-L67 | [
"def",
"serialize_to_file",
"(",
"obj",
",",
"file_name",
",",
"append",
"=",
"False",
")",
":",
"logging",
".",
"info",
"(",
"\"Serializing to file %s.\"",
",",
"file_name",
")",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"file_name",
",",
"\"a+\"",
"i... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | savez_two_column | Savez_compressed obj to file_name. | data_generation/fractal_graph_expansions/util.py | 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... | 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... | [
"Savez_compressed",
"obj",
"to",
"file_name",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/util.py#L69-L79 | [
"def",
"savez_two_column",
"(",
"matrix",
",",
"row_offset",
",",
"file_name",
",",
"append",
"=",
"False",
")",
":",
"logging",
".",
"info",
"(",
"\"Saving obj to file in two column .npz format %s.\"",
",",
"file_name",
")",
"tc",
"=",
"[",
"]",
"for",
"u",
"... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | sorted_product_set | Compute the product set of array_a and array_b and sort it. | data_generation/fractal_graph_expansions/util.py | 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] | 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] | [
"Compute",
"the",
"product",
"set",
"of",
"array_a",
"and",
"array_b",
"and",
"sort",
"it",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/util.py#L81-L86 | [
"def",
"sorted_product_set",
"(",
"array_a",
",",
"array_b",
")",
":",
"return",
"np",
".",
"sort",
"(",
"np",
".",
"concatenate",
"(",
"[",
"array_a",
"[",
"i",
"]",
"*",
"array_b",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"array_a",
")",
")",
... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | Matcher.set_low_quality_matches_ | 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 ... | object_detection/pytorch/maskrcnn_benchmark/modeling/matcher.py | 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 ... | 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 ... | [
"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",
"wi... | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/matcher.py#L83-L112 | [
"def",
"set_low_quality_matches_",
"(",
"self",
",",
"matches",
",",
"all_matches",
",",
"match_quality_matrix",
")",
":",
"# For each gt, find the prediction with which it has highest quality",
"highest_quality_foreach_gt",
",",
"_",
"=",
"match_quality_matrix",
".",
"max",
... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | eval_detection_voc | 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 | object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/voc/voc_eval.py | 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
... | 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
... | [
"Evaluate",
"on",
"voc",
"dataset",
".",
"Args",
":",
"pred_boxlists",
"(",
"list",
"[",
"BoxList",
"]",
")",
":",
"pred",
"boxlist",
"has",
"labels",
"and",
"scores",
"fields",
".",
"gt_boxlists",
"(",
"list",
"[",
"BoxList",
"]",
")",
":",
"ground",
... | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/voc/voc_eval.py#L48-L65 | [
"def",
"eval_detection_voc",
"(",
"pred_boxlists",
",",
"gt_boxlists",
",",
"iou_thresh",
"=",
"0.5",
",",
"use_07_metric",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"gt_boxlists",
")",
"==",
"len",
"(",
"pred_boxlists",
")",
",",
"\"Length of gt and pred li... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | calc_detection_voc_prec_rec | 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. | object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/voc/voc_eval.py | 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... | 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",
"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"... | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/voc/voc_eval.py#L68-L157 | [
"def",
"calc_detection_voc_prec_rec",
"(",
"gt_boxlists",
",",
"pred_boxlists",
",",
"iou_thresh",
"=",
"0.5",
")",
":",
"n_pos",
"=",
"defaultdict",
"(",
"int",
")",
"score",
"=",
"defaultdict",
"(",
"list",
")",
"match",
"=",
"defaultdict",
"(",
"list",
")... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | calc_detection_voc_ap | 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]... | object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/voc/voc_eval.py | 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 ... | 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 ... | [
"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",
"... | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/data/datasets/evaluation/voc/voc_eval.py#L160-L216 | [
"def",
"calc_detection_voc_ap",
"(",
"prec",
",",
"rec",
",",
"use_07_metric",
"=",
"False",
")",
":",
"n_fg_class",
"=",
"len",
"(",
"prec",
")",
"ap",
"=",
"np",
".",
"empty",
"(",
"n_fg_class",
")",
"for",
"l",
"in",
"range",
"(",
"n_fg_class",
")",... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | RPNPostProcessor.add_gt_proposals | Arguments:
proposals: list[BoxList]
targets: list[BoxList] | object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py | 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]... | 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",
":",
"proposals",
":",
"list",
"[",
"BoxList",
"]",
"targets",
":",
"list",
"[",
"BoxList",
"]"
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py#L51-L72 | [
"def",
"add_gt_proposals",
"(",
"self",
",",
"proposals",
",",
"targets",
")",
":",
"# Get the device we're operating on",
"device",
"=",
"proposals",
"[",
"0",
"]",
".",
"bbox",
".",
"device",
"gt_boxes",
"=",
"[",
"target",
".",
"copy_with_fields",
"(",
"[",... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | RPNPostProcessor.forward_for_single_feature_map | Arguments:
anchors: list[BoxList]
objectness: tensor of size N, A, H, W
box_regression: tensor of size N, A * 4, H, W | object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py | 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 =... | 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",
"[",
"BoxList",
"]",
"objectness",
":",
"tensor",
"of",
"size",
"N",
"A",
"H",
"W",
"box_regression",
":",
"tensor",
"of",
"size",
"N",
"A",
"*",
"4",
"H",
"W"
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py#L74-L121 | [
"def",
"forward_for_single_feature_map",
"(",
"self",
",",
"anchors",
",",
"objectness",
",",
"box_regression",
")",
":",
"device",
"=",
"objectness",
".",
"device",
"N",
",",
"A",
",",
"H",
",",
"W",
"=",
"objectness",
".",
"shape",
"# put in the same format ... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | RPNPostProcessor.forward | Arguments:
anchors: list[list[BoxList]]
objectness: list[tensor]
box_regression: list[tensor]
Returns:
boxlists (list[BoxList]): the post-processed anchors, after
applying box decoding and NMS | object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py | 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
... | 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
... | [
"Arguments",
":",
"anchors",
":",
"list",
"[",
"list",
"[",
"BoxList",
"]]",
"objectness",
":",
"list",
"[",
"tensor",
"]",
"box_regression",
":",
"list",
"[",
"tensor",
"]"
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/rpn/inference.py#L123-L150 | [
"def",
"forward",
"(",
"self",
",",
"anchors",
",",
"objectness",
",",
"box_regression",
",",
"targets",
"=",
"None",
")",
":",
"sampled_boxes",
"=",
"[",
"]",
"num_levels",
"=",
"len",
"(",
"objectness",
")",
"anchors",
"=",
"list",
"(",
"zip",
"(",
"... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | _dropout_sparse_coo_matrix | 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 be droped uniformly at random.
min_dropout_rate: minimum value for the dropout rate. If None
FLAGS.min_dropout_rate... | data_generation/fractal_graph_expansions/random_matrix_ops.py | 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 ... | 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 ... | [
"Drop",
"values",
"from",
"a",
"sparse",
"matrix",
"encoded",
"as",
"a",
"SciPy",
"coo",
"matrix",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/random_matrix_ops.py#L53-L103 | [
"def",
"_dropout_sparse_coo_matrix",
"(",
"sparse_matrix",
",",
"rate",
",",
"min_dropout_rate",
",",
"max_dropout_rate",
")",
":",
"if",
"min_dropout_rate",
"is",
"None",
":",
"min_dropout_rate",
"=",
"FLAGS",
".",
"min_dropout_rate",
"if",
"max_dropout_rate",
"is",
... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | shuffle_sparse_coo_matrix | 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 input matrix
will be droped uniformly at random.
min_dropout_rate: minimum value for the dropout rate. If None
FLAGS.min_dropout... | data_generation/fractal_graph_expansions/random_matrix_ops.py | 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... | 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... | [
"Shuffle",
"sparse",
"matrix",
"encoded",
"as",
"a",
"SciPy",
"coo",
"matrix",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/random_matrix_ops.py#L106-L139 | [
"def",
"shuffle_sparse_coo_matrix",
"(",
"sparse_matrix",
",",
"dropout_rate",
"=",
"0.0",
",",
"min_dropout_rate",
"=",
"None",
",",
"max_dropout_rate",
"=",
"None",
")",
":",
"if",
"(",
"dropout_rate",
"<",
"0.0",
")",
"or",
"(",
"dropout_rate",
">=",
"1.0",... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | play | 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 | reinforcement/tensorflow/minigo/selfplay.py | 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... | 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... | [
"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",
... | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/selfplay.py#L49-L107 | [
"def",
"play",
"(",
"network",
")",
":",
"readouts",
"=",
"FLAGS",
".",
"num_readouts",
"# defined in strategies.py",
"# Disable resign in 5% of games",
"if",
"random",
".",
"random",
"(",
")",
"<",
"FLAGS",
".",
"resign_disable_pct",
":",
"resign_threshold",
"=",
... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | run_game | Takes a played game and record results and game data. | reinforcement/tensorflow/minigo/selfplay.py | 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... | 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... | [
"Takes",
"a",
"played",
"game",
"and",
"record",
"results",
"and",
"game",
"data",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/selfplay.py#L110-L147 | [
"def",
"run_game",
"(",
"load_file",
",",
"selfplay_dir",
"=",
"None",
",",
"holdout_dir",
"=",
"None",
",",
"sgf_dir",
"=",
"None",
",",
"holdout_pct",
"=",
"0.05",
")",
":",
"if",
"sgf_dir",
"is",
"not",
"None",
":",
"minimal_sgf_dir",
"=",
"os",
".",
... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | main | Entry point for running one selfplay game. | reinforcement/tensorflow/minigo/selfplay.py | 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... | 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... | [
"Entry",
"point",
"for",
"running",
"one",
"selfplay",
"game",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/reinforcement/tensorflow/minigo/selfplay.py#L150-L160 | [
"def",
"main",
"(",
"argv",
")",
":",
"del",
"argv",
"# Unused",
"flags",
".",
"mark_flag_as_required",
"(",
"'load_file'",
")",
"run_game",
"(",
"load_file",
"=",
"FLAGS",
".",
"load_file",
",",
"selfplay_dir",
"=",
"FLAGS",
".",
"selfplay_dir",
",",
"holdo... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | resize_matrix | 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.
Returns:
A resized version of (u, s, v) whose non z... | data_generation/fractal_graph_expansions/graph_reduction.py | 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... | 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... | [
"Apply",
"algorith",
"2",
"in",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1901",
".",
"08910",
".",
"pdf",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/graph_reduction.py#L36-L58 | [
"def",
"resize_matrix",
"(",
"usv",
",",
"num_rows",
",",
"num_cols",
")",
":",
"u",
",",
"s",
",",
"v",
"=",
"usv",
"k",
"=",
"min",
"(",
"num_rows",
",",
"num_cols",
")",
"u_random_proj",
"=",
"transform",
".",
"resize",
"(",
"u",
"[",
":",
",",
... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | normalize_matrix | Fold all values of the matrix into [0, 1]. | data_generation/fractal_graph_expansions/graph_reduction.py | 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() | 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() | [
"Fold",
"all",
"values",
"of",
"the",
"matrix",
"into",
"[",
"0",
"1",
"]",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/data_generation/fractal_graph_expansions/graph_reduction.py#L61-L64 | [
"def",
"normalize_matrix",
"(",
"matrix",
")",
":",
"abs_matrix",
"=",
"np",
".",
"abs",
"(",
"matrix",
".",
"copy",
"(",
")",
")",
"return",
"abs_matrix",
"/",
"abs_matrix",
".",
"max",
"(",
")"
] | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | _get_sorted_inputs | 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. | translation/tensorflow/transformer/translate.py | 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:
... | 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:
... | [
"Read",
"and",
"sort",
"lines",
"from",
"the",
"file",
"sorted",
"by",
"decreasing",
"length",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/translate.py#L39-L62 | [
"def",
"_get_sorted_inputs",
"(",
"filename",
")",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"f",
":",
"records",
"=",
"f",
".",
"read",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"inputs",
"=",
"[",
"record",
".",... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | _trim_and_decode | Trim EOS and PAD tokens from ids, and decode to return a string. | translation/tensorflow/transformer/translate.py | 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) | 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) | [
"Trim",
"EOS",
"and",
"PAD",
"tokens",
"from",
"ids",
"and",
"decode",
"to",
"return",
"a",
"string",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/translate.py#L70-L76 | [
"def",
"_trim_and_decode",
"(",
"ids",
",",
"subtokenizer",
")",
":",
"try",
":",
"index",
"=",
"list",
"(",
"ids",
")",
".",
"index",
"(",
"tokenizer",
".",
"EOS_ID",
")",
"return",
"subtokenizer",
".",
"decode",
"(",
"ids",
"[",
":",
"index",
"]",
... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | translate_file | 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 source and
translated lines.
input_file: file containing lines to translate
output_file: file that stores ... | translation/tensorflow/transformer/translate.py | 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... | 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",
"lines",
"in",
"file",
"and",
"save",
"to",
"output",
"file",
"if",
"specified",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/translate.py#L79-L137 | [
"def",
"translate_file",
"(",
"estimator",
",",
"subtokenizer",
",",
"input_file",
",",
"output_file",
"=",
"None",
",",
"print_all_translations",
"=",
"True",
")",
":",
"batch_size",
"=",
"_DECODE_BATCH_SIZE",
"# Read and sort inputs by length. Keep dictionary (original in... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | translate_text | Translate a single string. | translation/tensorflow/transformer/translate.py | 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... | 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... | [
"Translate",
"a",
"single",
"string",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/translate.py#L140-L152 | [
"def",
"translate_text",
"(",
"estimator",
",",
"subtokenizer",
",",
"txt",
")",
":",
"encoded_txt",
"=",
"_encode_and_add_eos",
"(",
"txt",
",",
"subtokenizer",
")",
"def",
"input_fn",
"(",
")",
":",
"ds",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"f... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | Tokenizer.pad_vocabulary | Pads vocabulary to a multiple of 'pad' tokens.
:param vocab: list with vocabulary
:param pad: integer | rnn_translator/pytorch/seq2seq/data/tokenizer.py | 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... | 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... | [
"Pads",
"vocabulary",
"to",
"a",
"multiple",
"of",
"pad",
"tokens",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/tokenizer.py#L44-L56 | [
"def",
"pad_vocabulary",
"(",
"self",
",",
"vocab",
",",
"pad",
")",
":",
"vocab_size",
"=",
"len",
"(",
"vocab",
")",
"padded_vocab_size",
"=",
"(",
"vocab_size",
"+",
"pad",
"-",
"1",
")",
"//",
"pad",
"*",
"pad",
"for",
"i",
"in",
"range",
"(",
... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | Tokenizer.segment | Tokenizes single sentence and adds special BOS and EOS tokens.
:param line: sentence
returns: list representing tokenized sentence | rnn_translator/pytorch/seq2seq/data/tokenizer.py | 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] +... | 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] +... | [
"Tokenizes",
"single",
"sentence",
"and",
"adds",
"special",
"BOS",
"and",
"EOS",
"tokens",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/tokenizer.py#L75-L86 | [
"def",
"segment",
"(",
"self",
",",
"line",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"entry",
"=",
"[",
"self",
".",
"tok2idx",
"[",
"i",
"]",
"for",
"i",
"in",
"line",
"]",
"entry",
"=",
"[",
"config",
"... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | Tokenizer.detokenize | Detokenizes single sentence and removes token separator characters.
:param inputs: sequence of tokens
:param delim: tokenization delimiter
returns: string representing detokenized sentence | rnn_translator/pytorch/seq2seq/data/tokenizer.py | 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... | 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... | [
"Detokenizes",
"single",
"sentence",
"and",
"removes",
"token",
"separator",
"characters",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/rnn_translator/pytorch/seq2seq/data/tokenizer.py#L88-L105 | [
"def",
"detokenize",
"(",
"self",
",",
"inputs",
",",
"delim",
"=",
"' '",
")",
":",
"detok",
"=",
"delim",
".",
"join",
"(",
"[",
"self",
".",
"idx2tok",
"[",
"idx",
"]",
"for",
"idx",
"in",
"inputs",
"]",
")",
"detok",
"=",
"detok",
".",
"repla... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | FPN.forward | 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. | object_detection/pytorch/maskrcnn_benchmark/modeling/backbone/fpn.py | 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... | 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... | [
"Arguments",
":",
"x",
"(",
"list",
"[",
"Tensor",
"]",
")",
":",
"feature",
"maps",
"for",
"each",
"feature",
"level",
".",
"Returns",
":",
"results",
"(",
"tuple",
"[",
"Tensor",
"]",
")",
":",
"feature",
"maps",
"after",
"FPN",
"layers",
".",
"The... | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/backbone/fpn.py#L43-L74 | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"last_inner",
"=",
"getattr",
"(",
"self",
",",
"self",
".",
"inner_blocks",
"[",
"-",
"1",
"]",
")",
"(",
"x",
"[",
"-",
"1",
"]",
")",
"results",
"=",
"[",
"]",
"results",
".",
"append",
"(",... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | BigQueryUploader.upload_benchmark_run | 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 data will be uploaded.
run_id: string, a unique ID that will be attach... | image_classification/tensorflow/official/utils/logs/benchmark_uploader.py | 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... | 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",
"benchmark",
"run",
"information",
"to",
"Bigquery",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/benchmark_uploader.py#L61-L81 | [
"def",
"upload_benchmark_run",
"(",
"self",
",",
"dataset_name",
",",
"table_name",
",",
"run_id",
")",
":",
"expected_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_logging_dir",
",",
"logger",
".",
"BENCHMARK_RUN_LOG_FILE_NAME",
")",
"with",... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | BigQueryUploader.upload_metric | 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 be uploaded. This is different from the
benchmark_run tabl... | image_classification/tensorflow/official/utils/logs/benchmark_uploader.py | 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 ... | 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 ... | [
"Upload",
"metric",
"information",
"to",
"Bigquery",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/utils/logs/benchmark_uploader.py#L83-L108 | [
"def",
"upload_metric",
"(",
"self",
",",
"dataset_name",
",",
"table_name",
",",
"run_id",
")",
":",
"expected_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_logging_dir",
",",
"logger",
".",
"METRIC_LOG_FILE_NAME",
")",
"with",
"tf",
"."... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
train | bleu_wrapper | Compute BLEU for two files (reference and hypothesis translation). | translation/tensorflow/transformer/compute_bleu.py | 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... | 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... | [
"Compute",
"BLEU",
"for",
"two",
"files",
"(",
"reference",
"and",
"hypothesis",
"translation",
")",
"."
] | mlperf/training | python | https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/compute_bleu.py#L83-L96 | [
"def",
"bleu_wrapper",
"(",
"ref_filename",
",",
"hyp_filename",
",",
"case_sensitive",
"=",
"False",
")",
":",
"ref_lines",
"=",
"tf",
".",
"gfile",
".",
"Open",
"(",
"ref_filename",
")",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
".",
"splitlines",... | 1c6ae725a81d15437a2b2df05cac0673fde5c3a4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.