repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
HDI-Project/ballet | ballet/util/fs.py | spliceext | def spliceext(filepath, s):
"""Add s into filepath before the extension
Args:
filepath (str, path): file path
s (str): string to splice
Returns:
str
"""
root, ext = os.path.splitext(safepath(filepath))
return root + s + ext | python | def spliceext(filepath, s):
"""Add s into filepath before the extension
Args:
filepath (str, path): file path
s (str): string to splice
Returns:
str
"""
root, ext = os.path.splitext(safepath(filepath))
return root + s + ext | [
"def",
"spliceext",
"(",
"filepath",
",",
"s",
")",
":",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"safepath",
"(",
"filepath",
")",
")",
"return",
"root",
"+",
"s",
"+",
"ext"
] | Add s into filepath before the extension
Args:
filepath (str, path): file path
s (str): string to splice
Returns:
str | [
"Add",
"s",
"into",
"filepath",
"before",
"the",
"extension"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L12-L23 |
HDI-Project/ballet | ballet/util/fs.py | replaceext | def replaceext(filepath, new_ext):
"""Replace any existing file extension with a new one
Example::
>>> replaceext('/foo/bar.txt', 'py')
'/foo/bar.py'
>>> replaceext('/foo/bar.txt', '.doc')
'/foo/bar.doc'
Args:
filepath (str, path): file path
new_ext (str): ... | python | def replaceext(filepath, new_ext):
"""Replace any existing file extension with a new one
Example::
>>> replaceext('/foo/bar.txt', 'py')
'/foo/bar.py'
>>> replaceext('/foo/bar.txt', '.doc')
'/foo/bar.doc'
Args:
filepath (str, path): file path
new_ext (str): ... | [
"def",
"replaceext",
"(",
"filepath",
",",
"new_ext",
")",
":",
"if",
"new_ext",
"and",
"new_ext",
"[",
"0",
"]",
"!=",
"'.'",
":",
"new_ext",
"=",
"'.'",
"+",
"new_ext",
"root",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"safepath",
... | Replace any existing file extension with a new one
Example::
>>> replaceext('/foo/bar.txt', 'py')
'/foo/bar.py'
>>> replaceext('/foo/bar.txt', '.doc')
'/foo/bar.doc'
Args:
filepath (str, path): file path
new_ext (str): new file extension; if a leading dot is no... | [
"Replace",
"any",
"existing",
"file",
"extension",
"with",
"a",
"new",
"one"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L26-L48 |
HDI-Project/ballet | ballet/util/fs.py | splitext2 | def splitext2(filepath):
"""Split filepath into root, filename, ext
Args:
filepath (str, path): file path
Returns:
str
"""
root, filename = os.path.split(safepath(filepath))
filename, ext = os.path.splitext(safepath(filename))
return root, filename, ext | python | def splitext2(filepath):
"""Split filepath into root, filename, ext
Args:
filepath (str, path): file path
Returns:
str
"""
root, filename = os.path.split(safepath(filepath))
filename, ext = os.path.splitext(safepath(filename))
return root, filename, ext | [
"def",
"splitext2",
"(",
"filepath",
")",
":",
"root",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"safepath",
"(",
"filepath",
")",
")",
"filename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"safepath",
"(",
"filename... | Split filepath into root, filename, ext
Args:
filepath (str, path): file path
Returns:
str | [
"Split",
"filepath",
"into",
"root",
"filename",
"ext"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L51-L62 |
HDI-Project/ballet | ballet/util/fs.py | isemptyfile | def isemptyfile(filepath):
"""Determine if the file both exists and isempty
Args:
filepath (str, path): file path
Returns:
bool
"""
exists = os.path.exists(safepath(filepath))
if exists:
filesize = os.path.getsize(safepath(filepath))
return filesize == 0
els... | python | def isemptyfile(filepath):
"""Determine if the file both exists and isempty
Args:
filepath (str, path): file path
Returns:
bool
"""
exists = os.path.exists(safepath(filepath))
if exists:
filesize = os.path.getsize(safepath(filepath))
return filesize == 0
els... | [
"def",
"isemptyfile",
"(",
"filepath",
")",
":",
"exists",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"safepath",
"(",
"filepath",
")",
")",
"if",
"exists",
":",
"filesize",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"safepath",
"(",
"filepath",
"... | Determine if the file both exists and isempty
Args:
filepath (str, path): file path
Returns:
bool | [
"Determine",
"if",
"the",
"file",
"both",
"exists",
"and",
"isempty"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L65-L79 |
HDI-Project/ballet | ballet/util/fs.py | synctree | def synctree(src, dst, onexist=None):
"""Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
... | python | def synctree(src, dst, onexist=None):
"""Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
... | [
"def",
"synctree",
"(",
"src",
",",
"dst",
",",
"onexist",
"=",
"None",
")",
":",
"src",
"=",
"pathlib",
".",
"Path",
"(",
"src",
")",
".",
"resolve",
"(",
")",
"dst",
"=",
"pathlib",
".",
"Path",
"(",
"dst",
")",
".",
"resolve",
"(",
")",
"if"... | Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
Args:
src (path-like): source di... | [
"Recursively",
"sync",
"files",
"at",
"directory",
"src",
"to",
"dst"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/fs.py#L82-L110 |
HDI-Project/ballet | ballet/validation/entropy.py | calculate_disc_entropy | def calculate_disc_entropy(X):
r"""Calculates the exact Shannon entropy of a discrete dataset,
using empirical probabilities according to the equation:
$ H(X) = -\sum(c \in X) p(c) \times \log(p(c)) $
Where $ p(c) $ is calculated as the frequency of c in X.
If X's columns logically represent contin... | python | def calculate_disc_entropy(X):
r"""Calculates the exact Shannon entropy of a discrete dataset,
using empirical probabilities according to the equation:
$ H(X) = -\sum(c \in X) p(c) \times \log(p(c)) $
Where $ p(c) $ is calculated as the frequency of c in X.
If X's columns logically represent contin... | [
"def",
"calculate_disc_entropy",
"(",
"X",
")",
":",
"X",
"=",
"asarray2d",
"(",
"X",
")",
"n_samples",
",",
"_",
"=",
"X",
".",
"shape",
"_",
",",
"counts",
"=",
"np",
".",
"unique",
"(",
"X",
",",
"axis",
"=",
"0",
",",
"return_counts",
"=",
"T... | r"""Calculates the exact Shannon entropy of a discrete dataset,
using empirical probabilities according to the equation:
$ H(X) = -\sum(c \in X) p(c) \times \log(p(c)) $
Where $ p(c) $ is calculated as the frequency of c in X.
If X's columns logically represent continuous features,
it is better to ... | [
"r",
"Calculates",
"the",
"exact",
"Shannon",
"entropy",
"of",
"a",
"discrete",
"dataset",
"using",
"empirical",
"probabilities",
"according",
"to",
"the",
"equation",
":",
"$",
"H",
"(",
"X",
")",
"=",
"-",
"\\",
"sum",
"(",
"c",
"\\",
"in",
"X",
")",... | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L10-L35 |
HDI-Project/ballet | ballet/validation/entropy.py | estimate_cont_entropy | def estimate_cont_entropy(X, epsilon=None):
"""Estimate the Shannon entropy of a discrete dataset.
Based off the Kraskov Estimator [1] and Kozachenko [2]
estimators for a dataset's Shannon entropy.
The function relies on nonparametric methods based on entropy
estimation from k-nearest neighbors di... | python | def estimate_cont_entropy(X, epsilon=None):
"""Estimate the Shannon entropy of a discrete dataset.
Based off the Kraskov Estimator [1] and Kozachenko [2]
estimators for a dataset's Shannon entropy.
The function relies on nonparametric methods based on entropy
estimation from k-nearest neighbors di... | [
"def",
"estimate_cont_entropy",
"(",
"X",
",",
"epsilon",
"=",
"None",
")",
":",
"X",
"=",
"asarray2d",
"(",
"X",
")",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"if",
"n_samples",
"<=",
"1",
":",
"return",
"0",
"nn",
"=",
"NearestNeighbor... | Estimate the Shannon entropy of a discrete dataset.
Based off the Kraskov Estimator [1] and Kozachenko [2]
estimators for a dataset's Shannon entropy.
The function relies on nonparametric methods based on entropy
estimation from k-nearest neighbors distances as proposed
in [1] and augmented in [2]... | [
"Estimate",
"the",
"Shannon",
"entropy",
"of",
"a",
"discrete",
"dataset",
"."
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L38-L107 |
HDI-Project/ballet | ballet/validation/entropy.py | estimate_entropy | def estimate_entropy(X, epsilon=None):
r"""Estimate a dataset's Shannon entropy.
This function can take datasets of mixed discrete and continuous
features, and uses a set of heuristics to determine which functions
to apply to each.
Because this function is a subroutine in a mutual information esti... | python | def estimate_entropy(X, epsilon=None):
r"""Estimate a dataset's Shannon entropy.
This function can take datasets of mixed discrete and continuous
features, and uses a set of heuristics to determine which functions
to apply to each.
Because this function is a subroutine in a mutual information esti... | [
"def",
"estimate_entropy",
"(",
"X",
",",
"epsilon",
"=",
"None",
")",
":",
"X",
"=",
"asarray2d",
"(",
"X",
")",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"if",
"n_features",
"<",
"1",
":",
"return",
"0",
"disc_mask",
"=",
"_get_discrete... | r"""Estimate a dataset's Shannon entropy.
This function can take datasets of mixed discrete and continuous
features, and uses a set of heuristics to determine which functions
to apply to each.
Because this function is a subroutine in a mutual information estimator,
we employ the Kozachenko Estimat... | [
"r",
"Estimate",
"a",
"dataset",
"s",
"Shannon",
"entropy",
"."
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L126-L207 |
HDI-Project/ballet | ballet/validation/entropy.py | _calculate_epsilon | def _calculate_epsilon(X):
"""Calculates epsilon, a subroutine for the Kraskov Estimator [1]
Represents the chebyshev distance of each dataset element to its
K-th nearest neighbor.
Args:
X (array-like): An array with shape (n_samples, n_features)
Returns:
array-like: An array with ... | python | def _calculate_epsilon(X):
"""Calculates epsilon, a subroutine for the Kraskov Estimator [1]
Represents the chebyshev distance of each dataset element to its
K-th nearest neighbor.
Args:
X (array-like): An array with shape (n_samples, n_features)
Returns:
array-like: An array with ... | [
"def",
"_calculate_epsilon",
"(",
"X",
")",
":",
"disc_mask",
"=",
"_get_discrete_columns",
"(",
"X",
")",
"if",
"np",
".",
"all",
"(",
"disc_mask",
")",
":",
"# if all discrete columns, there's no point getting epsilon",
"return",
"0",
"cont_features",
"=",
"X",
... | Calculates epsilon, a subroutine for the Kraskov Estimator [1]
Represents the chebyshev distance of each dataset element to its
K-th nearest neighbor.
Args:
X (array-like): An array with shape (n_samples, n_features)
Returns:
array-like: An array with shape (n_samples, 1) representing
... | [
"Calculates",
"epsilon",
"a",
"subroutine",
"for",
"the",
"Kraskov",
"Estimator",
"[",
"1",
"]",
"Represents",
"the",
"chebyshev",
"distance",
"of",
"each",
"dataset",
"element",
"to",
"its",
"K",
"-",
"th",
"nearest",
"neighbor",
"."
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L210-L237 |
HDI-Project/ballet | ballet/validation/entropy.py | estimate_conditional_information | def estimate_conditional_information(x, y, z):
""" Estimate the conditional mutual information of three datasets.
Conditional mutual information is the
mutual information of two datasets, given a third:
$ I(x;y|z) = H(x,z) + H(y,z) - H(x,y,z) - H(z) $
Where H(x) is the Shannon entropy of x. F... | python | def estimate_conditional_information(x, y, z):
""" Estimate the conditional mutual information of three datasets.
Conditional mutual information is the
mutual information of two datasets, given a third:
$ I(x;y|z) = H(x,z) + H(y,z) - H(x,y,z) - H(z) $
Where H(x) is the Shannon entropy of x. F... | [
"def",
"estimate_conditional_information",
"(",
"x",
",",
"y",
",",
"z",
")",
":",
"xz",
"=",
"np",
".",
"concatenate",
"(",
"(",
"x",
",",
"z",
")",
",",
"axis",
"=",
"1",
")",
"yz",
"=",
"np",
".",
"concatenate",
"(",
"(",
"y",
",",
"z",
")",... | Estimate the conditional mutual information of three datasets.
Conditional mutual information is the
mutual information of two datasets, given a third:
$ I(x;y|z) = H(x,z) + H(y,z) - H(x,y,z) - H(z) $
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimato... | [
"Estimate",
"the",
"conditional",
"mutual",
"information",
"of",
"three",
"datasets",
"."
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L240-L282 |
HDI-Project/ballet | ballet/validation/entropy.py | estimate_mutual_information | def estimate_mutual_information(x, y):
"""Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the K... | python | def estimate_mutual_information(x, y):
"""Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the K... | [
"def",
"estimate_mutual_information",
"(",
"x",
",",
"y",
")",
":",
"xy",
"=",
"np",
".",
"concatenate",
"(",
"(",
"x",
",",
"y",
")",
",",
"axis",
"=",
"1",
")",
"epsilon",
"=",
"_calculate_epsilon",
"(",
"xy",
")",
"h_x",
"=",
"estimate_entropy",
"... | Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimator [1] for mutual information.
... | [
"Estimate",
"the",
"mutual",
"information",
"of",
"two",
"datasets",
"."
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/entropy.py#L285-L316 |
HDI-Project/ballet | ballet/util/git.py | get_diff_endpoints_from_commit_range | def get_diff_endpoints_from_commit_range(repo, commit_range):
"""Get endpoints of a diff given a commit range
The resulting endpoints can be diffed directly::
a, b = get_diff_endpoints_from_commit_range(repo, commit_range)
a.diff(b)
For details on specifying git diffs, see ``git diff --he... | python | def get_diff_endpoints_from_commit_range(repo, commit_range):
"""Get endpoints of a diff given a commit range
The resulting endpoints can be diffed directly::
a, b = get_diff_endpoints_from_commit_range(repo, commit_range)
a.diff(b)
For details on specifying git diffs, see ``git diff --he... | [
"def",
"get_diff_endpoints_from_commit_range",
"(",
"repo",
",",
"commit_range",
")",
":",
"if",
"not",
"commit_range",
":",
"raise",
"ValueError",
"(",
"'commit_range cannot be empty'",
")",
"result",
"=",
"re_find",
"(",
"COMMIT_RANGE_REGEX",
",",
"commit_range",
")... | Get endpoints of a diff given a commit range
The resulting endpoints can be diffed directly::
a, b = get_diff_endpoints_from_commit_range(repo, commit_range)
a.diff(b)
For details on specifying git diffs, see ``git diff --help``.
For details on specifying revisions, see ``git help revisio... | [
"Get",
"endpoints",
"of",
"a",
"diff",
"given",
"a",
"commit",
"range"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/git.py#L110-L152 |
HDI-Project/ballet | ballet/util/git.py | set_config_variables | def set_config_variables(repo, variables):
"""Set config variables
Args:
repo (git.Repo): repo
variables (dict): entries of the form 'user.email': 'you@example.com'
"""
with repo.config_writer() as writer:
for k, value in variables.items():
section, option = k.split(... | python | def set_config_variables(repo, variables):
"""Set config variables
Args:
repo (git.Repo): repo
variables (dict): entries of the form 'user.email': 'you@example.com'
"""
with repo.config_writer() as writer:
for k, value in variables.items():
section, option = k.split(... | [
"def",
"set_config_variables",
"(",
"repo",
",",
"variables",
")",
":",
"with",
"repo",
".",
"config_writer",
"(",
")",
"as",
"writer",
":",
"for",
"k",
",",
"value",
"in",
"variables",
".",
"items",
"(",
")",
":",
"section",
",",
"option",
"=",
"k",
... | Set config variables
Args:
repo (git.Repo): repo
variables (dict): entries of the form 'user.email': 'you@example.com' | [
"Set",
"config",
"variables"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/git.py#L185-L196 |
HDI-Project/ballet | ballet/validation/feature_api/validator.py | FeatureApiValidator.validate | def validate(self):
"""Collect and validate all new features"""
changes = self.change_collector.collect_changes()
features = []
imported_okay = True
for importer, modname, modpath in changes.new_feature_info:
try:
mod = importer()
fea... | python | def validate(self):
"""Collect and validate all new features"""
changes = self.change_collector.collect_changes()
features = []
imported_okay = True
for importer, modname, modpath in changes.new_feature_info:
try:
mod = importer()
fea... | [
"def",
"validate",
"(",
"self",
")",
":",
"changes",
"=",
"self",
".",
"change_collector",
".",
"collect_changes",
"(",
")",
"features",
"=",
"[",
"]",
"imported_okay",
"=",
"True",
"for",
"importer",
",",
"modname",
",",
"modpath",
"in",
"changes",
".",
... | Collect and validate all new features | [
"Collect",
"and",
"validate",
"all",
"new",
"features"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/validator.py#L31-L60 |
HDI-Project/ballet | ballet/project.py | load_config_at_path | def load_config_at_path(path):
"""Load config at exact path
Args:
path (path-like): path to config file
Returns:
dict: config dict
"""
if path.exists() and path.is_file():
with path.open('r') as f:
return yaml.load(f, Loader=yaml.SafeLoader)
else:
ra... | python | def load_config_at_path(path):
"""Load config at exact path
Args:
path (path-like): path to config file
Returns:
dict: config dict
"""
if path.exists() and path.is_file():
with path.open('r') as f:
return yaml.load(f, Loader=yaml.SafeLoader)
else:
ra... | [
"def",
"load_config_at_path",
"(",
"path",
")",
":",
"if",
"path",
".",
"exists",
"(",
")",
"and",
"path",
".",
"is_file",
"(",
")",
":",
"with",
"path",
".",
"open",
"(",
"'r'",
")",
"as",
"f",
":",
"return",
"yaml",
".",
"load",
"(",
"f",
",",
... | Load config at exact path
Args:
path (path-like): path to config file
Returns:
dict: config dict | [
"Load",
"config",
"at",
"exact",
"path"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L29-L42 |
HDI-Project/ballet | ballet/project.py | config_get | def config_get(config, *path, default=None):
"""Get a configuration option following a path through the config
Example usage:
>>> config_get(config,
'problem', 'problem_type_details', 'scorer',
default='accuracy')
Args:
config (dict): config d... | python | def config_get(config, *path, default=None):
"""Get a configuration option following a path through the config
Example usage:
>>> config_get(config,
'problem', 'problem_type_details', 'scorer',
default='accuracy')
Args:
config (dict): config d... | [
"def",
"config_get",
"(",
"config",
",",
"*",
"path",
",",
"default",
"=",
"None",
")",
":",
"o",
"=",
"object",
"(",
")",
"result",
"=",
"get_in",
"(",
"config",
",",
"path",
",",
"default",
"=",
"o",
")",
"if",
"result",
"is",
"not",
"o",
":",
... | Get a configuration option following a path through the config
Example usage:
>>> config_get(config,
'problem', 'problem_type_details', 'scorer',
default='accuracy')
Args:
config (dict): config dict
*path (list[str]): List of config sectio... | [
"Get",
"a",
"configuration",
"option",
"following",
"a",
"path",
"through",
"the",
"config"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L59-L79 |
HDI-Project/ballet | ballet/project.py | make_config_get | def make_config_get(conf_path):
"""Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module)
"""
project_root = _get_project_root_from_conf_path(conf_path)
config = load_config_in_dir(pro... | python | def make_config_get(conf_path):
"""Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module)
"""
project_root = _get_project_root_from_conf_path(conf_path)
config = load_config_in_dir(pro... | [
"def",
"make_config_get",
"(",
"conf_path",
")",
":",
"project_root",
"=",
"_get_project_root_from_conf_path",
"(",
"conf_path",
")",
"config",
"=",
"load_config_in_dir",
"(",
"project_root",
")",
"return",
"partial",
"(",
"config_get",
",",
"config",
")"
] | Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module) | [
"Return",
"a",
"function",
"to",
"get",
"configuration",
"options",
"for",
"a",
"specific",
"project"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L91-L100 |
HDI-Project/ballet | ballet/project.py | relative_to_contrib | def relative_to_contrib(diff, project):
"""Compute relative path of changed file to contrib dir
Args:
diff (git.diff.Diff): file diff
project (Project): project
Returns:
Path
"""
path = pathlib.Path(diff.b_path)
contrib_path = project.contrib_module_path
return path... | python | def relative_to_contrib(diff, project):
"""Compute relative path of changed file to contrib dir
Args:
diff (git.diff.Diff): file diff
project (Project): project
Returns:
Path
"""
path = pathlib.Path(diff.b_path)
contrib_path = project.contrib_module_path
return path... | [
"def",
"relative_to_contrib",
"(",
"diff",
",",
"project",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"diff",
".",
"b_path",
")",
"contrib_path",
"=",
"project",
".",
"contrib_module_path",
"return",
"path",
".",
"relative_to",
"(",
"contrib_path",
... | Compute relative path of changed file to contrib dir
Args:
diff (git.diff.Diff): file diff
project (Project): project
Returns:
Path | [
"Compute",
"relative",
"path",
"of",
"changed",
"file",
"to",
"contrib",
"dir"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L103-L115 |
HDI-Project/ballet | ballet/project.py | Project.pr_num | def pr_num(self):
"""Return the PR number or None if not on a PR"""
result = get_pr_num(repo=self.repo)
if result is None:
result = get_travis_pr_num()
return result | python | def pr_num(self):
"""Return the PR number or None if not on a PR"""
result = get_pr_num(repo=self.repo)
if result is None:
result = get_travis_pr_num()
return result | [
"def",
"pr_num",
"(",
"self",
")",
":",
"result",
"=",
"get_pr_num",
"(",
"repo",
"=",
"self",
".",
"repo",
")",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"get_travis_pr_num",
"(",
")",
"return",
"result"
] | Return the PR number or None if not on a PR | [
"Return",
"the",
"PR",
"number",
"or",
"None",
"if",
"not",
"on",
"a",
"PR"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L165-L170 |
HDI-Project/ballet | ballet/project.py | Project.branch | def branch(self):
"""Return whether the project is on master branch"""
result = get_branch(repo=self.repo)
if result is None:
result = get_travis_branch()
return result | python | def branch(self):
"""Return whether the project is on master branch"""
result = get_branch(repo=self.repo)
if result is None:
result = get_travis_branch()
return result | [
"def",
"branch",
"(",
"self",
")",
":",
"result",
"=",
"get_branch",
"(",
"repo",
"=",
"self",
".",
"repo",
")",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"get_travis_branch",
"(",
")",
"return",
"result"
] | Return whether the project is on master branch | [
"Return",
"whether",
"the",
"project",
"is",
"on",
"master",
"branch"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L177-L182 |
HDI-Project/ballet | ballet/project.py | Project.path | def path(self):
"""Return the project path (aka project root)
If ``package.__file__`` is ``/foo/foo/__init__.py``, then project.path
should be ``/foo``.
"""
return pathlib.Path(self.package.__file__).resolve().parent.parent | python | def path(self):
"""Return the project path (aka project root)
If ``package.__file__`` is ``/foo/foo/__init__.py``, then project.path
should be ``/foo``.
"""
return pathlib.Path(self.package.__file__).resolve().parent.parent | [
"def",
"path",
"(",
"self",
")",
":",
"return",
"pathlib",
".",
"Path",
"(",
"self",
".",
"package",
".",
"__file__",
")",
".",
"resolve",
"(",
")",
".",
"parent",
".",
"parent"
] | Return the project path (aka project root)
If ``package.__file__`` is ``/foo/foo/__init__.py``, then project.path
should be ``/foo``. | [
"Return",
"the",
"project",
"path",
"(",
"aka",
"project",
"root",
")"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L196-L202 |
HDI-Project/ballet | ballet/util/__init__.py | asarray2d | def asarray2d(a):
"""Cast to 2d array"""
arr = np.asarray(a)
if arr.ndim == 1:
arr = arr.reshape(-1, 1)
return arr | python | def asarray2d(a):
"""Cast to 2d array"""
arr = np.asarray(a)
if arr.ndim == 1:
arr = arr.reshape(-1, 1)
return arr | [
"def",
"asarray2d",
"(",
"a",
")",
":",
"arr",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"if",
"arr",
".",
"ndim",
"==",
"1",
":",
"arr",
"=",
"arr",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"return",
"arr"
] | Cast to 2d array | [
"Cast",
"to",
"2d",
"array"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/__init__.py#L16-L21 |
HDI-Project/ballet | ballet/util/__init__.py | get_arr_desc | def get_arr_desc(arr):
"""Get array description, in the form '<array type> <array shape>'"""
type_ = type(arr).__name__ # see also __qualname__
shape = getattr(arr, 'shape', None)
if shape is not None:
desc = '{type_} {shape}'
else:
desc = '{type_} <no shape>'
return desc.format... | python | def get_arr_desc(arr):
"""Get array description, in the form '<array type> <array shape>'"""
type_ = type(arr).__name__ # see also __qualname__
shape = getattr(arr, 'shape', None)
if shape is not None:
desc = '{type_} {shape}'
else:
desc = '{type_} <no shape>'
return desc.format... | [
"def",
"get_arr_desc",
"(",
"arr",
")",
":",
"type_",
"=",
"type",
"(",
"arr",
")",
".",
"__name__",
"# see also __qualname__",
"shape",
"=",
"getattr",
"(",
"arr",
",",
"'shape'",
",",
"None",
")",
"if",
"shape",
"is",
"not",
"None",
":",
"desc",
"=",... | Get array description, in the form '<array type> <array shape> | [
"Get",
"array",
"description",
"in",
"the",
"form",
"<array",
"type",
">",
"<array",
"shape",
">"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/__init__.py#L24-L32 |
HDI-Project/ballet | ballet/util/__init__.py | indent | def indent(text, n=4):
"""Indent each line of text by n spaces"""
_indent = ' ' * n
return '\n'.join(_indent + line for line in text.split('\n')) | python | def indent(text, n=4):
"""Indent each line of text by n spaces"""
_indent = ' ' * n
return '\n'.join(_indent + line for line in text.split('\n')) | [
"def",
"indent",
"(",
"text",
",",
"n",
"=",
"4",
")",
":",
"_indent",
"=",
"' '",
"*",
"n",
"return",
"'\\n'",
".",
"join",
"(",
"_indent",
"+",
"line",
"for",
"line",
"in",
"text",
".",
"split",
"(",
"'\\n'",
")",
")"
] | Indent each line of text by n spaces | [
"Indent",
"each",
"line",
"of",
"text",
"by",
"n",
"spaces"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/__init__.py#L46-L49 |
HDI-Project/ballet | ballet/util/__init__.py | has_nans | def has_nans(obj):
"""Check if obj has any NaNs
Compatible with different behavior of np.isnan, which sometimes applies
over all axes (py35, py35) and sometimes does not (py34).
"""
nans = np.isnan(obj)
while np.ndim(nans):
nans = np.any(nans)
return bool(nans) | python | def has_nans(obj):
"""Check if obj has any NaNs
Compatible with different behavior of np.isnan, which sometimes applies
over all axes (py35, py35) and sometimes does not (py34).
"""
nans = np.isnan(obj)
while np.ndim(nans):
nans = np.any(nans)
return bool(nans) | [
"def",
"has_nans",
"(",
"obj",
")",
":",
"nans",
"=",
"np",
".",
"isnan",
"(",
"obj",
")",
"while",
"np",
".",
"ndim",
"(",
"nans",
")",
":",
"nans",
"=",
"np",
".",
"any",
"(",
"nans",
")",
"return",
"bool",
"(",
"nans",
")"
] | Check if obj has any NaNs
Compatible with different behavior of np.isnan, which sometimes applies
over all axes (py35, py35) and sometimes does not (py34). | [
"Check",
"if",
"obj",
"has",
"any",
"NaNs"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/__init__.py#L66-L75 |
HDI-Project/ballet | ballet/util/__init__.py | needs_path | def needs_path(f):
"""Wraps a function that accepts path-like to give it a pathlib.Path"""
@wraps(f)
def wrapped(pathlike, *args, **kwargs):
path = pathlib.Path(pathlike)
return f(path, *args, **kwargs)
return wrapped | python | def needs_path(f):
"""Wraps a function that accepts path-like to give it a pathlib.Path"""
@wraps(f)
def wrapped(pathlike, *args, **kwargs):
path = pathlib.Path(pathlike)
return f(path, *args, **kwargs)
return wrapped | [
"def",
"needs_path",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"pathlike",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"pathlike",
")",
"return",
"f",
"(",
"path",
... | Wraps a function that accepts path-like to give it a pathlib.Path | [
"Wraps",
"a",
"function",
"that",
"accepts",
"path",
"-",
"like",
"to",
"give",
"it",
"a",
"pathlib",
".",
"Path"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/__init__.py#L128-L134 |
HDI-Project/ballet | ballet/util/mod.py | import_module_at_path | def import_module_at_path(modname, modpath):
"""Import module from path that may not be on system path
Args:
modname (str): module name from package root, e.g. foo.bar
modpath (str): absolute path to module itself,
e.g. /home/user/foo/bar.py. In the case of a module that is a
... | python | def import_module_at_path(modname, modpath):
"""Import module from path that may not be on system path
Args:
modname (str): module name from package root, e.g. foo.bar
modpath (str): absolute path to module itself,
e.g. /home/user/foo/bar.py. In the case of a module that is a
... | [
"def",
"import_module_at_path",
"(",
"modname",
",",
"modpath",
")",
":",
"# TODO just keep navigating up in the source tree until an __init__.py is",
"# not found?",
"modpath",
"=",
"pathlib",
".",
"Path",
"(",
"modpath",
")",
".",
"resolve",
"(",
")",
"if",
"modpath",... | Import module from path that may not be on system path
Args:
modname (str): module name from package root, e.g. foo.bar
modpath (str): absolute path to module itself,
e.g. /home/user/foo/bar.py. In the case of a module that is a
package, then the path should be specified as ... | [
"Import",
"module",
"from",
"path",
"that",
"may",
"not",
"be",
"on",
"system",
"path"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/mod.py#L19-L86 |
HDI-Project/ballet | ballet/util/mod.py | relpath_to_modname | def relpath_to_modname(relpath):
"""Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify directories, not regular
file... | python | def relpath_to_modname(relpath):
"""Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify directories, not regular
file... | [
"def",
"relpath_to_modname",
"(",
"relpath",
")",
":",
"# don't try to resolve!",
"p",
"=",
"pathlib",
".",
"Path",
"(",
"relpath",
")",
"if",
"p",
".",
"name",
"==",
"'__init__.py'",
":",
"p",
"=",
"p",
".",
"parent",
"elif",
"p",
".",
"suffix",
"==",
... | Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify directories, not regular
files, and (2) already 'foo/bar/__init__.py'... | [
"Convert",
"relative",
"path",
"to",
"module",
"name"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/mod.py#L89-L117 |
HDI-Project/ballet | ballet/util/mod.py | modname_to_relpath | def modname_to_relpath(modname, project_root=None, add_init=True):
"""Convert module name to relative path.
The project root is usually needed to detect if the module is a package, in
which case the relevant file is the `__init__.py` within the subdirectory.
Example:
>>> modname_to_relpath('fo... | python | def modname_to_relpath(modname, project_root=None, add_init=True):
"""Convert module name to relative path.
The project root is usually needed to detect if the module is a package, in
which case the relevant file is the `__init__.py` within the subdirectory.
Example:
>>> modname_to_relpath('fo... | [
"def",
"modname_to_relpath",
"(",
"modname",
",",
"project_root",
"=",
"None",
",",
"add_init",
"=",
"True",
")",
":",
"parts",
"=",
"modname",
".",
"split",
"(",
"'.'",
")",
"relpath",
"=",
"pathlib",
".",
"Path",
"(",
"*",
"parts",
")",
"# is the modul... | Convert module name to relative path.
The project root is usually needed to detect if the module is a package, in
which case the relevant file is the `__init__.py` within the subdirectory.
Example:
>>> modname_to_relpath('foo.features')
'foo/features.py'
>>> modname_to_relpath('foo... | [
"Convert",
"module",
"name",
"to",
"relative",
"path",
"."
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/mod.py#L120-L159 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | HasCorrectInputTypeCheck.check | def check(self, feature):
"""Check that the feature's `input` is a str or Iterable[str]"""
input = feature.input
is_str = isa(str)
is_nested_str = all_fn(
iterable, lambda x: all(is_str, x))
assert is_str(input) or is_nested_str(input) | python | def check(self, feature):
"""Check that the feature's `input` is a str or Iterable[str]"""
input = feature.input
is_str = isa(str)
is_nested_str = all_fn(
iterable, lambda x: all(is_str, x))
assert is_str(input) or is_nested_str(input) | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"input",
"=",
"feature",
".",
"input",
"is_str",
"=",
"isa",
"(",
"str",
")",
"is_nested_str",
"=",
"all_fn",
"(",
"iterable",
",",
"lambda",
"x",
":",
"all",
"(",
"is_str",
",",
"x",
")",
")",... | Check that the feature's `input` is a str or Iterable[str] | [
"Check",
"that",
"the",
"feature",
"s",
"input",
"is",
"a",
"str",
"or",
"Iterable",
"[",
"str",
"]"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L34-L40 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | HasTransformerInterfaceCheck.check | def check(self, feature):
"""Check that the feature has a fit/transform/fit_tranform interface"""
assert hasattr(feature.transformer, 'fit')
assert hasattr(feature.transformer, 'transform')
assert hasattr(feature.transformer, 'fit_transform') | python | def check(self, feature):
"""Check that the feature has a fit/transform/fit_tranform interface"""
assert hasattr(feature.transformer, 'fit')
assert hasattr(feature.transformer, 'transform')
assert hasattr(feature.transformer, 'fit_transform') | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"assert",
"hasattr",
"(",
"feature",
".",
"transformer",
",",
"'fit'",
")",
"assert",
"hasattr",
"(",
"feature",
".",
"transformer",
",",
"'transform'",
")",
"assert",
"hasattr",
"(",
"feature",
".",
... | Check that the feature has a fit/transform/fit_tranform interface | [
"Check",
"that",
"the",
"feature",
"has",
"a",
"fit",
"/",
"transform",
"/",
"fit_tranform",
"interface"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L45-L49 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | CanFitCheck.check | def check(self, feature):
"""Check that fit can be called on reference data"""
mapper = feature.as_dataframe_mapper()
mapper.fit(self.X, y=self.y) | python | def check(self, feature):
"""Check that fit can be called on reference data"""
mapper = feature.as_dataframe_mapper()
mapper.fit(self.X, y=self.y) | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"mapper",
"=",
"feature",
".",
"as_dataframe_mapper",
"(",
")",
"mapper",
".",
"fit",
"(",
"self",
".",
"X",
",",
"y",
"=",
"self",
".",
"y",
")"
] | Check that fit can be called on reference data | [
"Check",
"that",
"fit",
"can",
"be",
"called",
"on",
"reference",
"data"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L61-L64 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | CanFitTransformCheck.check | def check(self, feature):
"""Check that fit_transform can be called on reference data"""
mapper = feature.as_dataframe_mapper()
mapper.fit_transform(self.X, y=self.y) | python | def check(self, feature):
"""Check that fit_transform can be called on reference data"""
mapper = feature.as_dataframe_mapper()
mapper.fit_transform(self.X, y=self.y) | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"mapper",
"=",
"feature",
".",
"as_dataframe_mapper",
"(",
")",
"mapper",
".",
"fit_transform",
"(",
"self",
".",
"X",
",",
"y",
"=",
"self",
".",
"y",
")"
] | Check that fit_transform can be called on reference data | [
"Check",
"that",
"fit_transform",
"can",
"be",
"called",
"on",
"reference",
"data"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L78-L81 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | HasCorrectOutputDimensionsCheck.check | def check(self, feature):
"""Check that the dimensions of the transformed data are correct
For input X, an n x p array, a n x q array should be produced,
where q is the number of features produced by the logical feature.
"""
mapper = feature.as_dataframe_mapper()
X = map... | python | def check(self, feature):
"""Check that the dimensions of the transformed data are correct
For input X, an n x p array, a n x q array should be produced,
where q is the number of features produced by the logical feature.
"""
mapper = feature.as_dataframe_mapper()
X = map... | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"mapper",
"=",
"feature",
".",
"as_dataframe_mapper",
"(",
")",
"X",
"=",
"mapper",
".",
"fit_transform",
"(",
"self",
".",
"X",
",",
"y",
"=",
"self",
".",
"y",
")",
"assert",
"self",
".",
"X"... | Check that the dimensions of the transformed data are correct
For input X, an n x p array, a n x q array should be produced,
where q is the number of features produced by the logical feature. | [
"Check",
"that",
"the",
"dimensions",
"of",
"the",
"transformed",
"data",
"are",
"correct"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L86-L94 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | CanPickleCheck.check | def check(self, feature):
"""Check that the feature can be pickled
This is needed for saving the pipeline to disk
"""
try:
buf = io.BytesIO()
pickle.dump(feature, buf, protocol=pickle.HIGHEST_PROTOCOL)
buf.seek(0)
new_feature = pickle.load... | python | def check(self, feature):
"""Check that the feature can be pickled
This is needed for saving the pipeline to disk
"""
try:
buf = io.BytesIO()
pickle.dump(feature, buf, protocol=pickle.HIGHEST_PROTOCOL)
buf.seek(0)
new_feature = pickle.load... | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"try",
":",
"buf",
"=",
"io",
".",
"BytesIO",
"(",
")",
"pickle",
".",
"dump",
"(",
"feature",
",",
"buf",
",",
"protocol",
"=",
"pickle",
".",
"HIGHEST_PROTOCOL",
")",
"buf",
".",
"seek",
"(",... | Check that the feature can be pickled
This is needed for saving the pipeline to disk | [
"Check",
"that",
"the",
"feature",
"can",
"be",
"pickled"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L109-L122 |
HDI-Project/ballet | ballet/validation/feature_api/checks.py | NoMissingValuesCheck.check | def check(self, feature):
"""Check that the output of the transformer has no missing values"""
mapper = feature.as_dataframe_mapper()
X = mapper.fit_transform(self.X, y=self.y)
assert not np.any(np.isnan(X)) | python | def check(self, feature):
"""Check that the output of the transformer has no missing values"""
mapper = feature.as_dataframe_mapper()
X = mapper.fit_transform(self.X, y=self.y)
assert not np.any(np.isnan(X)) | [
"def",
"check",
"(",
"self",
",",
"feature",
")",
":",
"mapper",
"=",
"feature",
".",
"as_dataframe_mapper",
"(",
")",
"X",
"=",
"mapper",
".",
"fit_transform",
"(",
"self",
".",
"X",
",",
"y",
"=",
"self",
".",
"y",
")",
"assert",
"not",
"np",
"."... | Check that the output of the transformer has no missing values | [
"Check",
"that",
"the",
"output",
"of",
"the",
"transformer",
"has",
"no",
"missing",
"values"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/feature_api/checks.py#L127-L131 |
HDI-Project/ballet | ballet/eng/ts.py | make_multi_lagger | def make_multi_lagger(lags, groupby_kwargs=None):
"""Return a union of transformers that apply different lags
Args:
lags (Collection[int]): collection of lags to apply
groupby_kwargs (dict): keyword arguments to pd.DataFrame.groupby
"""
laggers = [SingleLagger(l, groupby_kwargs=groupby_... | python | def make_multi_lagger(lags, groupby_kwargs=None):
"""Return a union of transformers that apply different lags
Args:
lags (Collection[int]): collection of lags to apply
groupby_kwargs (dict): keyword arguments to pd.DataFrame.groupby
"""
laggers = [SingleLagger(l, groupby_kwargs=groupby_... | [
"def",
"make_multi_lagger",
"(",
"lags",
",",
"groupby_kwargs",
"=",
"None",
")",
":",
"laggers",
"=",
"[",
"SingleLagger",
"(",
"l",
",",
"groupby_kwargs",
"=",
"groupby_kwargs",
")",
"for",
"l",
"in",
"lags",
"]",
"feature_union",
"=",
"FeatureUnion",
"(",... | Return a union of transformers that apply different lags
Args:
lags (Collection[int]): collection of lags to apply
groupby_kwargs (dict): keyword arguments to pd.DataFrame.groupby | [
"Return",
"a",
"union",
"of",
"transformers",
"that",
"apply",
"different",
"lags"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/eng/ts.py#L20-L31 |
HDI-Project/ballet | ballet/templating.py | start_new_feature | def start_new_feature(**cc_kwargs):
"""Start a new feature within a ballet project
Renders the feature template into a temporary directory, then copies the
feature files into the proper path within the contrib directory.
Args:
**cc_kwargs: options for the cookiecutter template
Raises:
... | python | def start_new_feature(**cc_kwargs):
"""Start a new feature within a ballet project
Renders the feature template into a temporary directory, then copies the
feature files into the proper path within the contrib directory.
Args:
**cc_kwargs: options for the cookiecutter template
Raises:
... | [
"def",
"start_new_feature",
"(",
"*",
"*",
"cc_kwargs",
")",
":",
"project",
"=",
"Project",
".",
"from_path",
"(",
"pathlib",
".",
"Path",
".",
"cwd",
"(",
")",
".",
"resolve",
"(",
")",
")",
"contrib_dir",
"=",
"project",
".",
"get",
"(",
"'contrib'"... | Start a new feature within a ballet project
Renders the feature template into a temporary directory, then copies the
feature files into the proper path within the contrib directory.
Args:
**cc_kwargs: options for the cookiecutter template
Raises:
ballet.exc.BalletError: the new featur... | [
"Start",
"a",
"new",
"feature",
"within",
"a",
"ballet",
"project"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/templating.py#L61-L88 |
HDI-Project/ballet | ballet/validation/common.py | get_proposed_feature | def get_proposed_feature(project):
"""Get the proposed feature
The path of the proposed feature is determined by diffing the project
against a comparison branch, such as master. The feature is then imported
from that path and returned.
Args:
project (ballet.project.Project): project info
... | python | def get_proposed_feature(project):
"""Get the proposed feature
The path of the proposed feature is determined by diffing the project
against a comparison branch, such as master. The feature is then imported
from that path and returned.
Args:
project (ballet.project.Project): project info
... | [
"def",
"get_proposed_feature",
"(",
"project",
")",
":",
"change_collector",
"=",
"ChangeCollector",
"(",
"project",
")",
"collected_changes",
"=",
"change_collector",
".",
"collect_changes",
"(",
")",
"try",
":",
"new_feature_info",
"=",
"one_or_raise",
"(",
"colle... | Get the proposed feature
The path of the proposed feature is determined by diffing the project
against a comparison branch, such as master. The feature is then imported
from that path and returned.
Args:
project (ballet.project.Project): project info
Raises:
ballet.exc.BalletError... | [
"Get",
"the",
"proposed",
"feature"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/common.py#L16-L38 |
HDI-Project/ballet | ballet/validation/common.py | get_accepted_features | def get_accepted_features(features, proposed_feature):
"""Deselect candidate features from list of all features
Args:
features (List[Feature]): collection of all features in the ballet
project: both accepted features and candidate ones that have not
been accepted
propose... | python | def get_accepted_features(features, proposed_feature):
"""Deselect candidate features from list of all features
Args:
features (List[Feature]): collection of all features in the ballet
project: both accepted features and candidate ones that have not
been accepted
propose... | [
"def",
"get_accepted_features",
"(",
"features",
",",
"proposed_feature",
")",
":",
"def",
"eq",
"(",
"feature",
")",
":",
"\"\"\"Features are equal if they have the same source\n\n At least in this implementation...\n \"\"\"",
"return",
"feature",
".",
"source",
... | Deselect candidate features from list of all features
Args:
features (List[Feature]): collection of all features in the ballet
project: both accepted features and candidate ones that have not
been accepted
proposed_feature (Feature): candidate feature that has not been
... | [
"Deselect",
"candidate",
"features",
"from",
"list",
"of",
"all",
"features"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/common.py#L41-L76 |
HDI-Project/ballet | ballet/validation/common.py | ChangeCollector.collect_changes | def collect_changes(self):
"""Collect file and feature changes
Steps
1. Collects the files that have changed in this pull request as
compared to a comparison branch.
2. Categorize these file changes into admissible or inadmissible file
changes. Admissible file chan... | python | def collect_changes(self):
"""Collect file and feature changes
Steps
1. Collects the files that have changed in this pull request as
compared to a comparison branch.
2. Categorize these file changes into admissible or inadmissible file
changes. Admissible file chan... | [
"def",
"collect_changes",
"(",
"self",
")",
":",
"file_diffs",
"=",
"self",
".",
"_collect_file_diffs",
"(",
")",
"candidate_feature_diffs",
",",
"valid_init_diffs",
",",
"inadmissible_diffs",
"=",
"self",
".",
"_categorize_file_diffs",
"(",
"file_diffs",
")",
"new_... | Collect file and feature changes
Steps
1. Collects the files that have changed in this pull request as
compared to a comparison branch.
2. Categorize these file changes into admissible or inadmissible file
changes. Admissible file changes solely contribute python files to
... | [
"Collect",
"file",
"and",
"feature",
"changes"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/common.py#L116-L138 |
HDI-Project/ballet | ballet/validation/common.py | ChangeCollector._categorize_file_diffs | def _categorize_file_diffs(self, file_diffs):
"""Partition file changes into admissible and inadmissible changes"""
# TODO move this into a new validator
candidate_feature_diffs = []
valid_init_diffs = []
inadmissible_files = []
for diff in file_diffs:
valid,... | python | def _categorize_file_diffs(self, file_diffs):
"""Partition file changes into admissible and inadmissible changes"""
# TODO move this into a new validator
candidate_feature_diffs = []
valid_init_diffs = []
inadmissible_files = []
for diff in file_diffs:
valid,... | [
"def",
"_categorize_file_diffs",
"(",
"self",
",",
"file_diffs",
")",
":",
"# TODO move this into a new validator",
"candidate_feature_diffs",
"=",
"[",
"]",
"valid_init_diffs",
"=",
"[",
"]",
"inadmissible_files",
"=",
"[",
"]",
"for",
"diff",
"in",
"file_diffs",
"... | Partition file changes into admissible and inadmissible changes | [
"Partition",
"file",
"changes",
"into",
"admissible",
"and",
"inadmissible",
"changes"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/common.py#L152-L191 |
HDI-Project/ballet | ballet/validation/common.py | ChangeCollector._collect_feature_info | def _collect_feature_info(self, candidate_feature_diffs):
"""Collect feature info
Args:
candidate_feature_diffs (List[git.diff.Diff]): list of Diffs
corresponding to admissible file changes compared to
comparison ref
Returns:
List[Tuple]:... | python | def _collect_feature_info(self, candidate_feature_diffs):
"""Collect feature info
Args:
candidate_feature_diffs (List[git.diff.Diff]): list of Diffs
corresponding to admissible file changes compared to
comparison ref
Returns:
List[Tuple]:... | [
"def",
"_collect_feature_info",
"(",
"self",
",",
"candidate_feature_diffs",
")",
":",
"project_root",
"=",
"self",
".",
"project",
".",
"path",
"for",
"diff",
"in",
"candidate_feature_diffs",
":",
"path",
"=",
"diff",
".",
"b_path",
"modname",
"=",
"relpath_to_... | Collect feature info
Args:
candidate_feature_diffs (List[git.diff.Diff]): list of Diffs
corresponding to admissible file changes compared to
comparison ref
Returns:
List[Tuple]: list of tuple of importer, module name, and module
p... | [
"Collect",
"feature",
"info"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/validation/common.py#L196-L214 |
HDI-Project/ballet | ballet/util/ci.py | get_travis_branch | def get_travis_branch():
"""Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the
branch is stored ... | python | def get_travis_branch():
"""Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the
branch is stored ... | [
"def",
"get_travis_branch",
"(",
")",
":",
"# noqa E501",
"try",
":",
"travis_pull_request",
"=",
"get_travis_env_or_fail",
"(",
"'TRAVIS_PULL_REQUEST'",
")",
"if",
"truthy",
"(",
"travis_pull_request",
")",
":",
"travis_pull_request_branch",
"=",
"get_travis_env_or_fail"... | Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the
branch is stored in the TRAVIS_BRANCH environment... | [
"Get",
"current",
"branch",
"per",
"Travis",
"environment",
"variables"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/util/ci.py#L69-L89 |
HDI-Project/ballet | ballet/feature.py | make_mapper | def make_mapper(features):
"""Make a DataFrameMapper from a feature or list of features
Args:
features (Union[Feature, List[Feature]]): feature or list of features
Returns:
DataFrameMapper: mapper made from features
"""
if not features:
features = Feature(input=[], transfor... | python | def make_mapper(features):
"""Make a DataFrameMapper from a feature or list of features
Args:
features (Union[Feature, List[Feature]]): feature or list of features
Returns:
DataFrameMapper: mapper made from features
"""
if not features:
features = Feature(input=[], transfor... | [
"def",
"make_mapper",
"(",
"features",
")",
":",
"if",
"not",
"features",
":",
"features",
"=",
"Feature",
"(",
"input",
"=",
"[",
"]",
",",
"transformer",
"=",
"NullTransformer",
"(",
")",
")",
"if",
"not",
"iterable",
"(",
"features",
")",
":",
"feat... | Make a DataFrameMapper from a feature or list of features
Args:
features (Union[Feature, List[Feature]]): feature or list of features
Returns:
DataFrameMapper: mapper made from features | [
"Make",
"a",
"DataFrameMapper",
"from",
"a",
"feature",
"or",
"list",
"of",
"features"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/feature.py#L22-L37 |
HDI-Project/ballet | ballet/feature.py | _name_estimators | def _name_estimators(estimators):
"""Generate names for estimators.
Adapted from sklearn.pipeline._name_estimators
"""
def get_name(estimator):
if isinstance(estimator, DelegatingRobustTransformer):
return get_name(estimator._transformer)
return type(estimator).__name__.lo... | python | def _name_estimators(estimators):
"""Generate names for estimators.
Adapted from sklearn.pipeline._name_estimators
"""
def get_name(estimator):
if isinstance(estimator, DelegatingRobustTransformer):
return get_name(estimator._transformer)
return type(estimator).__name__.lo... | [
"def",
"_name_estimators",
"(",
"estimators",
")",
":",
"def",
"get_name",
"(",
"estimator",
")",
":",
"if",
"isinstance",
"(",
"estimator",
",",
"DelegatingRobustTransformer",
")",
":",
"return",
"get_name",
"(",
"estimator",
".",
"_transformer",
")",
"return",... | Generate names for estimators.
Adapted from sklearn.pipeline._name_estimators | [
"Generate",
"names",
"for",
"estimators",
"."
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/feature.py#L40-L62 |
HDI-Project/ballet | ballet/update.py | _push | def _push(project):
"""Push default branch and project template branch to remote
With default config (i.e. remote and branch names), equivalent to::
$ git push origin master:master project-template:project-template
Raises:
ballet.exc.BalletError: Push failed in some way
"""
repo =... | python | def _push(project):
"""Push default branch and project template branch to remote
With default config (i.e. remote and branch names), equivalent to::
$ git push origin master:master project-template:project-template
Raises:
ballet.exc.BalletError: Push failed in some way
"""
repo =... | [
"def",
"_push",
"(",
"project",
")",
":",
"repo",
"=",
"project",
".",
"repo",
"remote_name",
"=",
"project",
".",
"get",
"(",
"'project'",
",",
"'remote'",
")",
"remote",
"=",
"repo",
".",
"remote",
"(",
"remote_name",
")",
"result",
"=",
"_call_remote_... | Push default branch and project template branch to remote
With default config (i.e. remote and branch names), equivalent to::
$ git push origin master:master project-template:project-template
Raises:
ballet.exc.BalletError: Push failed in some way | [
"Push",
"default",
"branch",
"and",
"project",
"template",
"branch",
"to",
"remote"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/update.py#L82-L103 |
HDI-Project/ballet | ballet/templates/project_template/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/features/__init__.py | build | def build(X_df=None, y_df=None):
"""Build features and target
Args:
X_df (DataFrame): raw variables
y_df (DataFrame): raw target
Returns:
dict with keys X_df, features, mapper_X, X, y_df, encoder_y, y
"""
if X_df is None:
X_df, _ = load_data()
if y_df is None:
... | python | def build(X_df=None, y_df=None):
"""Build features and target
Args:
X_df (DataFrame): raw variables
y_df (DataFrame): raw target
Returns:
dict with keys X_df, features, mapper_X, X, y_df, encoder_y, y
"""
if X_df is None:
X_df, _ = load_data()
if y_df is None:
... | [
"def",
"build",
"(",
"X_df",
"=",
"None",
",",
"y_df",
"=",
"None",
")",
":",
"if",
"X_df",
"is",
"None",
":",
"X_df",
",",
"_",
"=",
"load_data",
"(",
")",
"if",
"y_df",
"is",
"None",
":",
"_",
",",
"y_df",
"=",
"load_data",
"(",
")",
"feature... | Build features and target
Args:
X_df (DataFrame): raw variables
y_df (DataFrame): raw target
Returns:
dict with keys X_df, features, mapper_X, X, y_df, encoder_y, y | [
"Build",
"features",
"and",
"target"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/templates/project_template/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/features/__init__.py#L37-L67 |
HDI-Project/ballet | ballet/templates/project_template/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/features/__init__.py | main | def main(input_dir, output_dir):
"""Engineer features"""
import ballet.util.log
ballet.util.log.enable(logger=logger, level='INFO', echo=False)
ballet.util.log.enable(logger=ballet.util.log.logger, level='INFO',
echo=False)
X_df, y_df = load_data(input_dir=input_dir)
... | python | def main(input_dir, output_dir):
"""Engineer features"""
import ballet.util.log
ballet.util.log.enable(logger=logger, level='INFO', echo=False)
ballet.util.log.enable(logger=ballet.util.log.logger, level='INFO',
echo=False)
X_df, y_df = load_data(input_dir=input_dir)
... | [
"def",
"main",
"(",
"input_dir",
",",
"output_dir",
")",
":",
"import",
"ballet",
".",
"util",
".",
"log",
"ballet",
".",
"util",
".",
"log",
".",
"enable",
"(",
"logger",
"=",
"logger",
",",
"level",
"=",
"'INFO'",
",",
"echo",
"=",
"False",
")",
... | Engineer features | [
"Engineer",
"features"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/templates/project_template/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/features/__init__.py#L74-L92 |
HDI-Project/ballet | ballet/templates/project_template/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/load_data.py | load_data | def load_data(input_dir=None):
"""Load data"""
if input_dir is not None:
tables = conf.get('tables')
entities_table_name = conf.get('data', 'entities_table_name')
entities_config = some(where(tables, name=entities_table_name))
X = load_table_from_config(input_dir, entities_confi... | python | def load_data(input_dir=None):
"""Load data"""
if input_dir is not None:
tables = conf.get('tables')
entities_table_name = conf.get('data', 'entities_table_name')
entities_config = some(where(tables, name=entities_table_name))
X = load_table_from_config(input_dir, entities_confi... | [
"def",
"load_data",
"(",
"input_dir",
"=",
"None",
")",
":",
"if",
"input_dir",
"is",
"not",
"None",
":",
"tables",
"=",
"conf",
".",
"get",
"(",
"'tables'",
")",
"entities_table_name",
"=",
"conf",
".",
"get",
"(",
"'data'",
",",
"'entities_table_name'",
... | Load data | [
"Load",
"data"
] | train | https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/templates/project_template/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/load_data.py#L7-L22 |
Cognexa/cxflow | cxflow/hooks/write_csv.py | WriteCSV._write_header | def _write_header(self, epoch_data: EpochData) -> None:
"""
Write CSV header row with column names.
Column names are inferred from the ``epoch_data`` and ``self.variables`` (if specified).
Variables and streams expected later on are stored in ``self._variables`` and ``self._streams`` re... | python | def _write_header(self, epoch_data: EpochData) -> None:
"""
Write CSV header row with column names.
Column names are inferred from the ``epoch_data`` and ``self.variables`` (if specified).
Variables and streams expected later on are stored in ``self._variables`` and ``self._streams`` re... | [
"def",
"_write_header",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"self",
".",
"_variables",
"=",
"self",
".",
"_variables",
"or",
"list",
"(",
"next",
"(",
"iter",
"(",
"epoch_data",
".",
"values",
"(",
")",
")",
")",
... | Write CSV header row with column names.
Column names are inferred from the ``epoch_data`` and ``self.variables`` (if specified).
Variables and streams expected later on are stored in ``self._variables`` and ``self._streams`` respectively.
:param epoch_data: epoch data to be logged | [
"Write",
"CSV",
"header",
"row",
"with",
"column",
"names",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/write_csv.py#L77-L94 |
Cognexa/cxflow | cxflow/hooks/write_csv.py | WriteCSV._write_row | def _write_row(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Write a single epoch result row to the CSV file.
:param epoch_id: epoch number (will be written at the first column)
:param epoch_data: epoch data
:raise KeyError: if the variable is missing and ``self._on_m... | python | def _write_row(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Write a single epoch result row to the CSV file.
:param epoch_id: epoch number (will be written at the first column)
:param epoch_data: epoch data
:raise KeyError: if the variable is missing and ``self._on_m... | [
"def",
"_write_row",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"# list of values to be written",
"values",
"=",
"[",
"epoch_id",
"]",
"for",
"stream_name",
"in",
"self",
".",
"_streams",
":",
"for"... | Write a single epoch result row to the CSV file.
:param epoch_id: epoch number (will be written at the first column)
:param epoch_data: epoch data
:raise KeyError: if the variable is missing and ``self._on_missing_variable`` is set to ``error``
:raise TypeError: if the variable has wron... | [
"Write",
"a",
"single",
"epoch",
"result",
"row",
"to",
"the",
"CSV",
"file",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/write_csv.py#L96-L141 |
Cognexa/cxflow | cxflow/hooks/write_csv.py | WriteCSV.after_epoch | def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Write a new row to the CSV file with the given epoch data.
In the case of first invocation, create the CSV header.
:param epoch_id: number of the epoch
:param epoch_data: epoch data to be logged
""... | python | def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Write a new row to the CSV file with the given epoch data.
In the case of first invocation, create the CSV header.
:param epoch_id: number of the epoch
:param epoch_data: epoch data to be logged
""... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"logging",
".",
"debug",
"(",
"'Saving epoch %d data to \"%s\"'",
",",
"epoch_id",
",",
"self",
".",
"_file_path",
")",
"if",
"not",
... | Write a new row to the CSV file with the given epoch data.
In the case of first invocation, create the CSV header.
:param epoch_id: number of the epoch
:param epoch_data: epoch data to be logged | [
"Write",
"a",
"new",
"row",
"to",
"the",
"CSV",
"file",
"with",
"the",
"given",
"epoch",
"data",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/write_csv.py#L143-L155 |
Cognexa/cxflow | cxflow/utils/names.py | get_random_name | def get_random_name(sep: str='-'):
"""
Generate random docker-like name with the given separator.
:param sep: adjective-name separator string
:return: random docker-like name
"""
r = random.SystemRandom()
return '{}{}{}'.format(r.choice(_left), sep, r.choice(_right)) | python | def get_random_name(sep: str='-'):
"""
Generate random docker-like name with the given separator.
:param sep: adjective-name separator string
:return: random docker-like name
"""
r = random.SystemRandom()
return '{}{}{}'.format(r.choice(_left), sep, r.choice(_right)) | [
"def",
"get_random_name",
"(",
"sep",
":",
"str",
"=",
"'-'",
")",
":",
"r",
"=",
"random",
".",
"SystemRandom",
"(",
")",
"return",
"'{}{}{}'",
".",
"format",
"(",
"r",
".",
"choice",
"(",
"_left",
")",
",",
"sep",
",",
"r",
".",
"choice",
"(",
... | Generate random docker-like name with the given separator.
:param sep: adjective-name separator string
:return: random docker-like name | [
"Generate",
"random",
"docker",
"-",
"like",
"name",
"with",
"the",
"given",
"separator",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/names.py#L40-L48 |
Cognexa/cxflow | cxflow/hooks/stop_after.py | StopAfter._check_train_time | def _check_train_time(self) -> None:
"""
Stop the training if the training time exceeded ``self._minutes``.
:raise TrainingTerminated: if the training time exceeded ``self._minutes``
"""
if self._minutes is not None and (datetime.now() - self._training_start).total_seconds()/60 ... | python | def _check_train_time(self) -> None:
"""
Stop the training if the training time exceeded ``self._minutes``.
:raise TrainingTerminated: if the training time exceeded ``self._minutes``
"""
if self._minutes is not None and (datetime.now() - self._training_start).total_seconds()/60 ... | [
"def",
"_check_train_time",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_minutes",
"is",
"not",
"None",
"and",
"(",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_training_start",
")",
".",
"total_seconds",
"(",
")",
"/",
"60",
">... | Stop the training if the training time exceeded ``self._minutes``.
:raise TrainingTerminated: if the training time exceeded ``self._minutes`` | [
"Stop",
"the",
"training",
"if",
"the",
"training",
"time",
"exceeded",
"self",
".",
"_minutes",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_after.py#L72-L79 |
Cognexa/cxflow | cxflow/hooks/stop_after.py | StopAfter.after_batch | def after_batch(self, stream_name: str, batch_data: Batch) -> None:
"""
If ``stream_name`` equals to :py:attr:`cxflow.constants.TRAIN_STREAM`,
increase the iterations counter and possibly stop the training; additionally, call :py:meth:`_check_train_time`.
:param stream_name: stream name... | python | def after_batch(self, stream_name: str, batch_data: Batch) -> None:
"""
If ``stream_name`` equals to :py:attr:`cxflow.constants.TRAIN_STREAM`,
increase the iterations counter and possibly stop the training; additionally, call :py:meth:`_check_train_time`.
:param stream_name: stream name... | [
"def",
"after_batch",
"(",
"self",
",",
"stream_name",
":",
"str",
",",
"batch_data",
":",
"Batch",
")",
"->",
"None",
":",
"self",
".",
"_check_train_time",
"(",
")",
"if",
"self",
".",
"_iters",
"is",
"not",
"None",
"and",
"stream_name",
"==",
"self",
... | If ``stream_name`` equals to :py:attr:`cxflow.constants.TRAIN_STREAM`,
increase the iterations counter and possibly stop the training; additionally, call :py:meth:`_check_train_time`.
:param stream_name: stream name
:param batch_data: ignored
:raise TrainingTerminated: if the number of ... | [
"If",
"stream_name",
"equals",
"to",
":",
"py",
":",
"attr",
":",
"cxflow",
".",
"constants",
".",
"TRAIN_STREAM",
"increase",
"the",
"iterations",
"counter",
"and",
"possibly",
"stop",
"the",
"training",
";",
"additionally",
"call",
":",
"py",
":",
"meth",
... | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_after.py#L85-L98 |
Cognexa/cxflow | cxflow/hooks/stop_after.py | StopAfter.after_epoch | def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Stop the training if the ``epoch_id`` reaches ``self._epochs``; additionally, call :py:meth:`_check_train_time`.
:param epoch_id: epoch id
:param epoch_data: ignored
:raise TrainingTerminated: if the ``epoc... | python | def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Stop the training if the ``epoch_id`` reaches ``self._epochs``; additionally, call :py:meth:`_check_train_time`.
:param epoch_id: epoch id
:param epoch_data: ignored
:raise TrainingTerminated: if the ``epoc... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"self",
".",
"_check_train_time",
"(",
")",
"if",
"self",
".",
"_epochs",
"is",
"not",
"None",
"and",
"epoch_id",
">=",
"self",
... | Stop the training if the ``epoch_id`` reaches ``self._epochs``; additionally, call :py:meth:`_check_train_time`.
:param epoch_id: epoch id
:param epoch_data: ignored
:raise TrainingTerminated: if the ``epoch_id`` reaches ``self._epochs`` | [
"Stop",
"the",
"training",
"if",
"the",
"epoch_id",
"reaches",
"self",
".",
"_epochs",
";",
"additionally",
"call",
":",
"py",
":",
"meth",
":",
"_check_train_time",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_after.py#L100-L111 |
Cognexa/cxflow | cxflow/utils/download.py | sanitize_url | def sanitize_url(url: str) -> str:
"""
Sanitize the given url so that it can be used as a valid filename.
:param url: url to create filename from
:raise ValueError: when the given url can not be sanitized
:return: created filename
"""
for part in reversed(url.split('/')):
filename ... | python | def sanitize_url(url: str) -> str:
"""
Sanitize the given url so that it can be used as a valid filename.
:param url: url to create filename from
:raise ValueError: when the given url can not be sanitized
:return: created filename
"""
for part in reversed(url.split('/')):
filename ... | [
"def",
"sanitize_url",
"(",
"url",
":",
"str",
")",
"->",
"str",
":",
"for",
"part",
"in",
"reversed",
"(",
"url",
".",
"split",
"(",
"'/'",
")",
")",
":",
"filename",
"=",
"re",
".",
"sub",
"(",
"r'[^a-zA-Z0-9_.\\-]'",
",",
"''",
",",
"part",
")",... | Sanitize the given url so that it can be used as a valid filename.
:param url: url to create filename from
:raise ValueError: when the given url can not be sanitized
:return: created filename | [
"Sanitize",
"the",
"given",
"url",
"so",
"that",
"it",
"can",
"be",
"used",
"as",
"a",
"valid",
"filename",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/download.py#L9-L25 |
Cognexa/cxflow | cxflow/utils/download.py | maybe_download_and_extract | def maybe_download_and_extract(data_root: str, url: str) -> None:
"""
Maybe download the specified file to ``data_root`` and try to unpack it with ``shutil.unpack_archive``.
:param data_root: data root to download the files to
:param url: url to download from
"""
# make sure data_root exis... | python | def maybe_download_and_extract(data_root: str, url: str) -> None:
"""
Maybe download the specified file to ``data_root`` and try to unpack it with ``shutil.unpack_archive``.
:param data_root: data root to download the files to
:param url: url to download from
"""
# make sure data_root exis... | [
"def",
"maybe_download_and_extract",
"(",
"data_root",
":",
"str",
",",
"url",
":",
"str",
")",
"->",
"None",
":",
"# make sure data_root exists",
"os",
".",
"makedirs",
"(",
"data_root",
",",
"exist_ok",
"=",
"True",
")",
"# create sanitized filename from url",
"... | Maybe download the specified file to ``data_root`` and try to unpack it with ``shutil.unpack_archive``.
:param data_root: data root to download the files to
:param url: url to download from | [
"Maybe",
"download",
"the",
"specified",
"file",
"to",
"data_root",
"and",
"try",
"to",
"unpack",
"it",
"with",
"shutil",
".",
"unpack_archive",
".",
":",
"param",
"data_root",
":",
"data",
"root",
"to",
"download",
"the",
"files",
"to",
":",
"param",
"url... | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/download.py#L28-L71 |
Cognexa/cxflow | cxflow/hooks/compute_stats.py | ComputeStats._raise_check_aggregation | def _raise_check_aggregation(aggregation: str):
"""
Check whether the given aggregation is present in NumPy or it is one of EXTRA_AGGREGATIONS.
:param aggregation: the aggregation name
:raise ValueError: if the specified aggregation is not supported or found in NumPy
"""
... | python | def _raise_check_aggregation(aggregation: str):
"""
Check whether the given aggregation is present in NumPy or it is one of EXTRA_AGGREGATIONS.
:param aggregation: the aggregation name
:raise ValueError: if the specified aggregation is not supported or found in NumPy
"""
... | [
"def",
"_raise_check_aggregation",
"(",
"aggregation",
":",
"str",
")",
":",
"if",
"aggregation",
"not",
"in",
"ComputeStats",
".",
"EXTRA_AGGREGATIONS",
"and",
"not",
"hasattr",
"(",
"np",
",",
"aggregation",
")",
":",
"raise",
"ValueError",
"(",
"'Aggregation ... | Check whether the given aggregation is present in NumPy or it is one of EXTRA_AGGREGATIONS.
:param aggregation: the aggregation name
:raise ValueError: if the specified aggregation is not supported or found in NumPy | [
"Check",
"whether",
"the",
"given",
"aggregation",
"is",
"present",
"in",
"NumPy",
"or",
"it",
"is",
"one",
"of",
"EXTRA_AGGREGATIONS",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/compute_stats.py#L64-L73 |
Cognexa/cxflow | cxflow/hooks/compute_stats.py | ComputeStats._compute_aggregation | def _compute_aggregation(aggregation: str, data: Iterable[Any]):
"""
Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS`.
... | python | def _compute_aggregation(aggregation: str, data: Iterable[Any]):
"""
Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS`.
... | [
"def",
"_compute_aggregation",
"(",
"aggregation",
":",
"str",
",",
"data",
":",
"Iterable",
"[",
"Any",
"]",
")",
":",
"ComputeStats",
".",
"_raise_check_aggregation",
"(",
"aggregation",
")",
"if",
"aggregation",
"==",
"'nanfraction'",
":",
"return",
"np",
"... | Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS`.
:param data: data to be aggregated
:raise ValueError: if the specified ag... | [
"Compute",
"the",
"specified",
"aggregation",
"on",
"the",
"given",
"data",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/compute_stats.py#L76-L90 |
Cognexa/cxflow | cxflow/hooks/compute_stats.py | ComputeStats._save_stats | def _save_stats(self, epoch_data: EpochData) -> None:
"""
Extend ``epoch_data`` by stream:variable:aggreagation data.
:param epoch_data: data source from which the statistics are computed
"""
for stream_name in epoch_data.keys():
for variable, aggregations in self._... | python | def _save_stats(self, epoch_data: EpochData) -> None:
"""
Extend ``epoch_data`` by stream:variable:aggreagation data.
:param epoch_data: data source from which the statistics are computed
"""
for stream_name in epoch_data.keys():
for variable, aggregations in self._... | [
"def",
"_save_stats",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"for",
"stream_name",
"in",
"epoch_data",
".",
"keys",
"(",
")",
":",
"for",
"variable",
",",
"aggregations",
"in",
"self",
".",
"_variable_aggregations",
".",
... | Extend ``epoch_data`` by stream:variable:aggreagation data.
:param epoch_data: data source from which the statistics are computed | [
"Extend",
"epoch_data",
"by",
"stream",
":",
"variable",
":",
"aggreagation",
"data",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/compute_stats.py#L92-L104 |
Cognexa/cxflow | cxflow/hooks/compute_stats.py | ComputeStats.after_epoch | def after_epoch(self, epoch_data: EpochData, **kwargs) -> None:
"""
Compute the specified aggregations and save them to the given epoch data.
:param epoch_data: epoch data to be processed
"""
self._save_stats(epoch_data)
super().after_epoch(epoch_data=epoch_data, **kwarg... | python | def after_epoch(self, epoch_data: EpochData, **kwargs) -> None:
"""
Compute the specified aggregations and save them to the given epoch data.
:param epoch_data: epoch data to be processed
"""
self._save_stats(epoch_data)
super().after_epoch(epoch_data=epoch_data, **kwarg... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"self",
".",
"_save_stats",
"(",
"epoch_data",
")",
"super",
"(",
")",
".",
"after_epoch",
"(",
"epoch_data",
"=",
"epoch_data",
",",... | Compute the specified aggregations and save them to the given epoch data.
:param epoch_data: epoch data to be processed | [
"Compute",
"the",
"specified",
"aggregations",
"and",
"save",
"them",
"to",
"the",
"given",
"epoch",
"data",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/compute_stats.py#L106-L113 |
Cognexa/cxflow | cxflow/utils/training_trace.py | TrainingTrace.save | def save(self) -> None:
"""
Save the training trace to :py:attr:`CXF_TRACE_FILE` file under the specified directory.
:raise ValueError: if no output directory was specified
"""
if self._output_dir is None:
raise ValueError('Can not save TrainingTrace without output d... | python | def save(self) -> None:
"""
Save the training trace to :py:attr:`CXF_TRACE_FILE` file under the specified directory.
:raise ValueError: if no output directory was specified
"""
if self._output_dir is None:
raise ValueError('Can not save TrainingTrace without output d... | [
"def",
"save",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_output_dir",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Can not save TrainingTrace without output dir.'",
")",
"yaml_to_file",
"(",
"self",
".",
"_trace",
",",
"self",
".",
"_output... | Save the training trace to :py:attr:`CXF_TRACE_FILE` file under the specified directory.
:raise ValueError: if no output directory was specified | [
"Save",
"the",
"training",
"trace",
"to",
":",
"py",
":",
"attr",
":",
"CXF_TRACE_FILE",
"file",
"under",
"the",
"specified",
"directory",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/training_trace.py#L74-L82 |
Cognexa/cxflow | cxflow/utils/training_trace.py | TrainingTrace.from_file | def from_file(filepath: str):
"""
Load training trace from the given ``filepath``.
:param filepath: training trace file path
:return: training trace
"""
trace = TrainingTrace()
trace._trace = load_config(filepath)
return trace | python | def from_file(filepath: str):
"""
Load training trace from the given ``filepath``.
:param filepath: training trace file path
:return: training trace
"""
trace = TrainingTrace()
trace._trace = load_config(filepath)
return trace | [
"def",
"from_file",
"(",
"filepath",
":",
"str",
")",
":",
"trace",
"=",
"TrainingTrace",
"(",
")",
"trace",
".",
"_trace",
"=",
"load_config",
"(",
"filepath",
")",
"return",
"trace"
] | Load training trace from the given ``filepath``.
:param filepath: training trace file path
:return: training trace | [
"Load",
"training",
"trace",
"from",
"the",
"given",
"filepath",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/training_trace.py#L85-L94 |
Cognexa/cxflow | cxflow/hooks/check.py | Check.after_epoch | def after_epoch(self, epoch_id: int, epoch_data: EpochData):
"""
Check termination conditions.
:param epoch_id: number of the processed epoch
:param epoch_data: epoch data to be checked
:raise KeyError: if the stream of variable was not found in ``epoch_data``
:raise Typ... | python | def after_epoch(self, epoch_id: int, epoch_data: EpochData):
"""
Check termination conditions.
:param epoch_id: number of the processed epoch
:param epoch_data: epoch data to be checked
:raise KeyError: if the stream of variable was not found in ``epoch_data``
:raise Typ... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"epoch_data",
":",
"EpochData",
")",
":",
"if",
"self",
".",
"_stream",
"not",
"in",
"epoch_data",
":",
"raise",
"KeyError",
"(",
"'The hook could not determine whether the threshold was exceeded a... | Check termination conditions.
:param epoch_id: number of the processed epoch
:param epoch_data: epoch data to be checked
:raise KeyError: if the stream of variable was not found in ``epoch_data``
:raise TypeError: if the monitored variable is not a scalar or scalar ``mean`` aggregation
... | [
"Check",
"termination",
"conditions",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/check.py#L43-L76 |
Cognexa/cxflow | cxflow/cli/train.py | train | def train(config_path: str, cl_arguments: Iterable[str], output_root: str) -> None:
"""
Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in wh... | python | def train(config_path: str, cl_arguments: Iterable[str], output_root: str) -> None:
"""
Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in wh... | [
"def",
"train",
"(",
"config_path",
":",
"str",
",",
"cl_arguments",
":",
"Iterable",
"[",
"str",
"]",
",",
"output_root",
":",
"str",
")",
"->",
"None",
":",
"config",
"=",
"None",
"try",
":",
"config_path",
"=",
"find_config",
"(",
"config_path",
")",
... | Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in which the training directory will be created | [
"Load",
"config",
"and",
"start",
"the",
"training",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/train.py#L11-L29 |
Cognexa/cxflow | cxflow/cli/eval.py | evaluate | def evaluate(model_path: str, stream_name: str, config_path: Optional[str], cl_arguments: Iterable[str],
output_root: str) -> None:
"""
Evaluate the given model on the specified data stream.
Configuration is updated by the respective predict.stream_name section, in particular:
- hooks ... | python | def evaluate(model_path: str, stream_name: str, config_path: Optional[str], cl_arguments: Iterable[str],
output_root: str) -> None:
"""
Evaluate the given model on the specified data stream.
Configuration is updated by the respective predict.stream_name section, in particular:
- hooks ... | [
"def",
"evaluate",
"(",
"model_path",
":",
"str",
",",
"stream_name",
":",
"str",
",",
"config_path",
":",
"Optional",
"[",
"str",
"]",
",",
"cl_arguments",
":",
"Iterable",
"[",
"str",
"]",
",",
"output_root",
":",
"str",
")",
"->",
"None",
":",
"conf... | Evaluate the given model on the specified data stream.
Configuration is updated by the respective predict.stream_name section, in particular:
- hooks section is entirely replaced
- model and dataset sections are updated
:param model_path: path to the model to be evaluated
:param stream_nam... | [
"Evaluate",
"the",
"given",
"model",
"on",
"the",
"specified",
"data",
"stream",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/eval.py#L12-L57 |
Cognexa/cxflow | cxflow/cli/eval.py | predict | def predict(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:
"""
Run prediction from the specified config path.
If the config contains a ``predict`` section:
- override hooks with ``predict.hooks`` if present
- update dataset, model and ... | python | def predict(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:
"""
Run prediction from the specified config path.
If the config contains a ``predict`` section:
- override hooks with ``predict.hooks`` if present
- update dataset, model and ... | [
"def",
"predict",
"(",
"config_path",
":",
"str",
",",
"restore_from",
":",
"Optional",
"[",
"str",
"]",
",",
"cl_arguments",
":",
"Iterable",
"[",
"str",
"]",
",",
"output_root",
":",
"str",
")",
"->",
"None",
":",
"config",
"=",
"None",
"try",
":",
... | Run prediction from the specified config path.
If the config contains a ``predict`` section:
- override hooks with ``predict.hooks`` if present
- update dataset, model and main loop sections if the respective sections are present
:param config_path: path to the config file or the directory in ... | [
"Run",
"prediction",
"from",
"the",
"specified",
"config",
"path",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/eval.py#L60-L99 |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop._create_epoch_data | def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData:
"""Create empty epoch data double dict."""
if streams is None:
streams = [self._train_stream_name] + self._extra_streams
return OrderedDict([(stream_name, OrderedDict()) for stream_name in streams]) | python | def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData:
"""Create empty epoch data double dict."""
if streams is None:
streams = [self._train_stream_name] + self._extra_streams
return OrderedDict([(stream_name, OrderedDict()) for stream_name in streams]) | [
"def",
"_create_epoch_data",
"(",
"self",
",",
"streams",
":",
"Optional",
"[",
"Iterable",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"EpochData",
":",
"if",
"streams",
"is",
"None",
":",
"streams",
"=",
"[",
"self",
".",
"_train_stream_name",
"]",
... | Create empty epoch data double dict. | [
"Create",
"empty",
"epoch",
"data",
"double",
"dict",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L96-L100 |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop._check_sources | def _check_sources(self, batch: Dict[str, object]) -> None:
"""
Check for unused and missing sources.
:param batch: batch to be checked
:raise ValueError: if a source is missing or unused and ``self._on_unused_sources`` is set to ``error``
"""
unused_sources = [source fo... | python | def _check_sources(self, batch: Dict[str, object]) -> None:
"""
Check for unused and missing sources.
:param batch: batch to be checked
:raise ValueError: if a source is missing or unused and ``self._on_unused_sources`` is set to ``error``
"""
unused_sources = [source fo... | [
"def",
"_check_sources",
"(",
"self",
",",
"batch",
":",
"Dict",
"[",
"str",
",",
"object",
"]",
")",
"->",
"None",
":",
"unused_sources",
"=",
"[",
"source",
"for",
"source",
"in",
"batch",
".",
"keys",
"(",
")",
"if",
"source",
"not",
"in",
"self",... | Check for unused and missing sources.
:param batch: batch to be checked
:raise ValueError: if a source is missing or unused and ``self._on_unused_sources`` is set to ``error`` | [
"Check",
"for",
"unused",
"and",
"missing",
"sources",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L102-L125 |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop._run_epoch | def _run_epoch(self, stream: StreamWrapper, train: bool) -> None:
"""
Iterate through the given stream and evaluate/train the model with the received batches.
Calls :py:meth:`cxflow.hooks.AbstractHook.after_batch` events.
:param stream: stream to iterate
:param train: if set to... | python | def _run_epoch(self, stream: StreamWrapper, train: bool) -> None:
"""
Iterate through the given stream and evaluate/train the model with the received batches.
Calls :py:meth:`cxflow.hooks.AbstractHook.after_batch` events.
:param stream: stream to iterate
:param train: if set to... | [
"def",
"_run_epoch",
"(",
"self",
",",
"stream",
":",
"StreamWrapper",
",",
"train",
":",
"bool",
")",
"->",
"None",
":",
"nonempty_batch_count",
"=",
"0",
"for",
"i",
",",
"batch_input",
"in",
"enumerate",
"(",
"stream",
")",
":",
"self",
".",
"raise_ch... | Iterate through the given stream and evaluate/train the model with the received batches.
Calls :py:meth:`cxflow.hooks.AbstractHook.after_batch` events.
:param stream: stream to iterate
:param train: if set to ``True``, the model will be trained
:raise ValueError: in case of empty batch... | [
"Iterate",
"through",
"the",
"given",
"stream",
"and",
"evaluate",
"/",
"train",
"the",
"model",
"with",
"the",
"received",
"batches",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L127-L179 |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop.train_by_stream | def train_by_stream(self, stream: StreamWrapper) -> None:
"""
Train the model with the given stream.
:param stream: stream to train with
"""
self._run_epoch(stream=stream, train=True) | python | def train_by_stream(self, stream: StreamWrapper) -> None:
"""
Train the model with the given stream.
:param stream: stream to train with
"""
self._run_epoch(stream=stream, train=True) | [
"def",
"train_by_stream",
"(",
"self",
",",
"stream",
":",
"StreamWrapper",
")",
"->",
"None",
":",
"self",
".",
"_run_epoch",
"(",
"stream",
"=",
"stream",
",",
"train",
"=",
"True",
")"
] | Train the model with the given stream.
:param stream: stream to train with | [
"Train",
"the",
"model",
"with",
"the",
"given",
"stream",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L182-L188 |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop.evaluate_stream | def evaluate_stream(self, stream: StreamWrapper) -> None:
"""
Evaluate the given stream.
:param stream: stream to be evaluated
:param stream_name: stream name
"""
self._run_epoch(stream=stream, train=False) | python | def evaluate_stream(self, stream: StreamWrapper) -> None:
"""
Evaluate the given stream.
:param stream: stream to be evaluated
:param stream_name: stream name
"""
self._run_epoch(stream=stream, train=False) | [
"def",
"evaluate_stream",
"(",
"self",
",",
"stream",
":",
"StreamWrapper",
")",
"->",
"None",
":",
"self",
".",
"_run_epoch",
"(",
"stream",
"=",
"stream",
",",
"train",
"=",
"False",
")"
] | Evaluate the given stream.
:param stream: stream to be evaluated
:param stream_name: stream name | [
"Evaluate",
"the",
"given",
"stream",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L190-L197 |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop.get_stream | def get_stream(self, stream_name: str) -> StreamWrapper:
"""
Get a :py:class:`StreamWrapper` with the given name.
:param stream_name: stream name
:return: dataset function name providing the respective stream
:raise AttributeError: if the dataset does not provide the function cr... | python | def get_stream(self, stream_name: str) -> StreamWrapper:
"""
Get a :py:class:`StreamWrapper` with the given name.
:param stream_name: stream name
:return: dataset function name providing the respective stream
:raise AttributeError: if the dataset does not provide the function cr... | [
"def",
"get_stream",
"(",
"self",
",",
"stream_name",
":",
"str",
")",
"->",
"StreamWrapper",
":",
"if",
"stream_name",
"not",
"in",
"self",
".",
"_streams",
":",
"stream_fn_name",
"=",
"'{}_stream'",
".",
"format",
"(",
"stream_name",
")",
"try",
":",
"st... | Get a :py:class:`StreamWrapper` with the given name.
:param stream_name: stream name
:return: dataset function name providing the respective stream
:raise AttributeError: if the dataset does not provide the function creating the stream | [
"Get",
"a",
":",
"py",
":",
"class",
":",
"StreamWrapper",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L199-L220 |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop._run_zeroth_epoch | def _run_zeroth_epoch(self, streams: Iterable[str]) -> None:
"""
Run zeroth epoch on the specified streams.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
:param streams: stream names to be evaluated
"""
for stream_name in streams:
with... | python | def _run_zeroth_epoch(self, streams: Iterable[str]) -> None:
"""
Run zeroth epoch on the specified streams.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
:param streams: stream names to be evaluated
"""
for stream_name in streams:
with... | [
"def",
"_run_zeroth_epoch",
"(",
"self",
",",
"streams",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"stream_name",
"in",
"streams",
":",
"with",
"self",
".",
"get_stream",
"(",
"stream_name",
")",
"as",
"stream",
":",
"self",
".",
... | Run zeroth epoch on the specified streams.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
:param streams: stream names to be evaluated | [
"Run",
"zeroth",
"epoch",
"on",
"the",
"specified",
"streams",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L222-L237 |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop._try_run | def _try_run(self, run_func: Callable[[], None]) -> None:
"""
Try running the given function (training/prediction).
Calls
- :py:meth:`cxflow.hooks.AbstractHook.before_training`
- :py:meth:`cxflow.hooks.AbstractHook.after_training`
:param run_func: function to be... | python | def _try_run(self, run_func: Callable[[], None]) -> None:
"""
Try running the given function (training/prediction).
Calls
- :py:meth:`cxflow.hooks.AbstractHook.before_training`
- :py:meth:`cxflow.hooks.AbstractHook.after_training`
:param run_func: function to be... | [
"def",
"_try_run",
"(",
"self",
",",
"run_func",
":",
"Callable",
"[",
"[",
"]",
",",
"None",
"]",
")",
"->",
"None",
":",
"# Initialization: before_training",
"for",
"hook",
"in",
"self",
".",
"_hooks",
":",
"hook",
".",
"before_training",
"(",
")",
"tr... | Try running the given function (training/prediction).
Calls
- :py:meth:`cxflow.hooks.AbstractHook.before_training`
- :py:meth:`cxflow.hooks.AbstractHook.after_training`
:param run_func: function to be run | [
"Try",
"running",
"the",
"given",
"function",
"(",
"training",
"/",
"prediction",
")",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L239-L260 |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop.run_training | def run_training(self, trace: Optional[TrainingTrace]=None) -> None:
"""
Run the main loop in the training mode.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch_profile`
"""
for stream_name in [se... | python | def run_training(self, trace: Optional[TrainingTrace]=None) -> None:
"""
Run the main loop in the training mode.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch_profile`
"""
for stream_name in [se... | [
"def",
"run_training",
"(",
"self",
",",
"trace",
":",
"Optional",
"[",
"TrainingTrace",
"]",
"=",
"None",
")",
"->",
"None",
":",
"for",
"stream_name",
"in",
"[",
"self",
".",
"_train_stream_name",
"]",
"+",
"self",
".",
"_extra_streams",
":",
"self",
"... | Run the main loop in the training mode.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch_profile` | [
"Run",
"the",
"main",
"loop",
"in",
"the",
"training",
"mode",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L262-L310 |
Cognexa/cxflow | cxflow/main_loop.py | MainLoop.run_evaluation | def run_evaluation(self, stream_name: str) -> None:
"""
Run the main loop with the given stream in the prediction mode.
:param stream_name: name of the stream to be evaluated
"""
def prediction():
logging.info('Running prediction')
self._run_zeroth_epoch(... | python | def run_evaluation(self, stream_name: str) -> None:
"""
Run the main loop with the given stream in the prediction mode.
:param stream_name: name of the stream to be evaluated
"""
def prediction():
logging.info('Running prediction')
self._run_zeroth_epoch(... | [
"def",
"run_evaluation",
"(",
"self",
",",
"stream_name",
":",
"str",
")",
"->",
"None",
":",
"def",
"prediction",
"(",
")",
":",
"logging",
".",
"info",
"(",
"'Running prediction'",
")",
"self",
".",
"_run_zeroth_epoch",
"(",
"[",
"stream_name",
"]",
")",... | Run the main loop with the given stream in the prediction mode.
:param stream_name: name of the stream to be evaluated | [
"Run",
"the",
"main",
"loop",
"with",
"the",
"given",
"stream",
"in",
"the",
"prediction",
"mode",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/main_loop.py#L312-L322 |
Cognexa/cxflow | cxflow/models/ensemble.py | major_vote | def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]:
"""
For the given iterable of object iterations, return an iterable of the most common object at each position of the
inner iterations.
E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the m... | python | def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]:
"""
For the given iterable of object iterations, return an iterable of the most common object at each position of the
inner iterations.
E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the m... | [
"def",
"major_vote",
"(",
"all_votes",
":",
"Iterable",
"[",
"Iterable",
"[",
"Hashable",
"]",
"]",
")",
"->",
"Iterable",
"[",
"Hashable",
"]",
":",
"return",
"[",
"Counter",
"(",
"votes",
")",
".",
"most_common",
"(",
")",
"[",
"0",
"]",
"[",
"0",
... | For the given iterable of object iterations, return an iterable of the most common object at each position of the
inner iterations.
E.g.: for [[1, 2], [1, 3], [2, 3]] the return value would be [1, 3] as 1 and 3 are the most common objects
at the first and second positions respectively.
:param all_vote... | [
"For",
"the",
"given",
"iterable",
"of",
"object",
"iterations",
"return",
"an",
"iterable",
"of",
"the",
"most",
"common",
"object",
"at",
"each",
"position",
"of",
"the",
"inner",
"iterations",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/models/ensemble.py#L17-L28 |
Cognexa/cxflow | cxflow/models/ensemble.py | Ensemble._load_models | def _load_models(self) -> None:
"""Maybe load all the models to be assembled together and save them to the ``self._models`` attribute."""
if self._models is None:
logging.info('Loading %d models', len(self._model_paths))
def load_model(model_path: str):
logging.d... | python | def _load_models(self) -> None:
"""Maybe load all the models to be assembled together and save them to the ``self._models`` attribute."""
if self._models is None:
logging.info('Loading %d models', len(self._model_paths))
def load_model(model_path: str):
logging.d... | [
"def",
"_load_models",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_models",
"is",
"None",
":",
"logging",
".",
"info",
"(",
"'Loading %d models'",
",",
"len",
"(",
"self",
".",
"_model_paths",
")",
")",
"def",
"load_model",
"(",
"model_path... | Maybe load all the models to be assembled together and save them to the ``self._models`` attribute. | [
"Maybe",
"load",
"all",
"the",
"models",
"to",
"be",
"assembled",
"together",
"and",
"save",
"them",
"to",
"the",
"self",
".",
"_models",
"attribute",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/models/ensemble.py#L113-L129 |
Cognexa/cxflow | cxflow/models/ensemble.py | Ensemble.run | def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch:
"""
Run feed-forward pass with the given batch using all the models, aggregate and return the results.
.. warning::
:py:class:`Ensemble` can not be trained.
:param batch: batch to be proces... | python | def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch:
"""
Run feed-forward pass with the given batch using all the models, aggregate and return the results.
.. warning::
:py:class:`Ensemble` can not be trained.
:param batch: batch to be proces... | [
"def",
"run",
"(",
"self",
",",
"batch",
":",
"Batch",
",",
"train",
":",
"bool",
"=",
"False",
",",
"stream",
":",
"StreamWrapper",
"=",
"None",
")",
"->",
"Batch",
":",
"if",
"train",
":",
"raise",
"ValueError",
"(",
"'Ensemble model cannot be trained.'"... | Run feed-forward pass with the given batch using all the models, aggregate and return the results.
.. warning::
:py:class:`Ensemble` can not be trained.
:param batch: batch to be processed
:param train: ``True`` if this batch should be used for model update, ``False`` otherwise
... | [
"Run",
"feed",
"-",
"forward",
"pass",
"with",
"the",
"given",
"batch",
"using",
"all",
"the",
"models",
"aggregate",
"and",
"return",
"the",
"results",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/models/ensemble.py#L141-L172 |
Cognexa/cxflow | cxflow/utils/reflection.py | parse_fully_qualified_name | def parse_fully_qualified_name(fq_name: str) -> Tuple[Optional[str], str]:
"""
Parse the given fully-quallified name (separated with dots) to a tuple of module and class names.
:param fq_name: fully qualified name separated with dots
:return: ``None`` instead of module if the given name contains no sep... | python | def parse_fully_qualified_name(fq_name: str) -> Tuple[Optional[str], str]:
"""
Parse the given fully-quallified name (separated with dots) to a tuple of module and class names.
:param fq_name: fully qualified name separated with dots
:return: ``None`` instead of module if the given name contains no sep... | [
"def",
"parse_fully_qualified_name",
"(",
"fq_name",
":",
"str",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"str",
"]",
",",
"str",
"]",
":",
"last_dot",
"=",
"fq_name",
".",
"rfind",
"(",
"'.'",
")",
"if",
"last_dot",
"!=",
"-",
"1",
":",
"return",
"... | Parse the given fully-quallified name (separated with dots) to a tuple of module and class names.
:param fq_name: fully qualified name separated with dots
:return: ``None`` instead of module if the given name contains no separators (dots). | [
"Parse",
"the",
"given",
"fully",
"-",
"quallified",
"name",
"(",
"separated",
"with",
"dots",
")",
"to",
"a",
"tuple",
"of",
"module",
"and",
"class",
"names",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L14-L25 |
Cognexa/cxflow | cxflow/utils/reflection.py | get_attribute | def get_attribute(module_name: str, attribute_name: str):
"""
Get the specified module attribute. It most cases, it will be a class or function.
:param module_name: module name
:param attribute_name: attribute name
:return: module attribute
"""
assert isinstance(module_name, str)
assert... | python | def get_attribute(module_name: str, attribute_name: str):
"""
Get the specified module attribute. It most cases, it will be a class or function.
:param module_name: module name
:param attribute_name: attribute name
:return: module attribute
"""
assert isinstance(module_name, str)
assert... | [
"def",
"get_attribute",
"(",
"module_name",
":",
"str",
",",
"attribute_name",
":",
"str",
")",
":",
"assert",
"isinstance",
"(",
"module_name",
",",
"str",
")",
"assert",
"isinstance",
"(",
"attribute_name",
",",
"str",
")",
"_module",
"=",
"importlib",
"."... | Get the specified module attribute. It most cases, it will be a class or function.
:param module_name: module name
:param attribute_name: attribute name
:return: module attribute | [
"Get",
"the",
"specified",
"module",
"attribute",
".",
"It",
"most",
"cases",
"it",
"will",
"be",
"a",
"class",
"or",
"function",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L28-L40 |
Cognexa/cxflow | cxflow/utils/reflection.py | create_object | def create_object(module_name: str, class_name: str, args: Iterable=(), kwargs: Dict[str, Any]=_EMPTY_DICT):
"""
Create an object instance of the given class from the given module.
Args and kwargs are passed to the constructor.
This mimics the following code:
.. code-block:: python
from m... | python | def create_object(module_name: str, class_name: str, args: Iterable=(), kwargs: Dict[str, Any]=_EMPTY_DICT):
"""
Create an object instance of the given class from the given module.
Args and kwargs are passed to the constructor.
This mimics the following code:
.. code-block:: python
from m... | [
"def",
"create_object",
"(",
"module_name",
":",
"str",
",",
"class_name",
":",
"str",
",",
"args",
":",
"Iterable",
"=",
"(",
")",
",",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"_EMPTY_DICT",
")",
":",
"return",
"get_attribute",
"(",
... | Create an object instance of the given class from the given module.
Args and kwargs are passed to the constructor.
This mimics the following code:
.. code-block:: python
from module import class
return class(*args, **kwargs)
:param module_name: module name
:param class_name: clas... | [
"Create",
"an",
"object",
"instance",
"of",
"the",
"given",
"class",
"from",
"the",
"given",
"module",
".",
"Args",
"and",
"kwargs",
"are",
"passed",
"to",
"the",
"constructor",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L43-L61 |
Cognexa/cxflow | cxflow/utils/reflection.py | list_submodules | def list_submodules(module_name: str) -> List[str]: # pylint: disable=invalid-sequence-index
"""
List full names of all the submodules in the given module.
:param module_name: name of the module of which the submodules will be listed
"""
_module = importlib.import_module(module_name)
return [... | python | def list_submodules(module_name: str) -> List[str]: # pylint: disable=invalid-sequence-index
"""
List full names of all the submodules in the given module.
:param module_name: name of the module of which the submodules will be listed
"""
_module = importlib.import_module(module_name)
return [... | [
"def",
"list_submodules",
"(",
"module_name",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# pylint: disable=invalid-sequence-index",
"_module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"return",
"[",
"module_name",
"+",
"'.'",
"... | List full names of all the submodules in the given module.
:param module_name: name of the module of which the submodules will be listed | [
"List",
"full",
"names",
"of",
"all",
"the",
"submodules",
"in",
"the",
"given",
"module",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L64-L71 |
Cognexa/cxflow | cxflow/utils/reflection.py | find_class_module | def find_class_module(module_name: str, class_name: str) \
-> Tuple[List[str], List[Tuple[str, Exception]]]: # pylint: disable=invalid-sequence-index
"""
Find sub-modules of the given module that contain the given class.
Moreover, return a list of sub-modules that could not be imported as a list ... | python | def find_class_module(module_name: str, class_name: str) \
-> Tuple[List[str], List[Tuple[str, Exception]]]: # pylint: disable=invalid-sequence-index
"""
Find sub-modules of the given module that contain the given class.
Moreover, return a list of sub-modules that could not be imported as a list ... | [
"def",
"find_class_module",
"(",
"module_name",
":",
"str",
",",
"class_name",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"str",
"]",
",",
"List",
"[",
"Tuple",
"[",
"str",
",",
"Exception",
"]",
"]",
"]",
":",
"# pylint: disable=invalid-sequence-in... | Find sub-modules of the given module that contain the given class.
Moreover, return a list of sub-modules that could not be imported as a list of (sub-module name, Exception) tuples.
:param module_name: name of the module to be searched
:param class_name: searched class name
:return: a tuple of sub-mo... | [
"Find",
"sub",
"-",
"modules",
"of",
"the",
"given",
"module",
"that",
"contain",
"the",
"given",
"class",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L74-L94 |
Cognexa/cxflow | cxflow/utils/reflection.py | get_class_module | def get_class_module(module_name: str, class_name: str) -> Optional[str]:
"""
Get a sub-module of the given module which has the given class.
This method wraps `utils.reflection.find_class_module method` with the following behavior:
- raise error when multiple sub-modules with different classes with t... | python | def get_class_module(module_name: str, class_name: str) -> Optional[str]:
"""
Get a sub-module of the given module which has the given class.
This method wraps `utils.reflection.find_class_module method` with the following behavior:
- raise error when multiple sub-modules with different classes with t... | [
"def",
"get_class_module",
"(",
"module_name",
":",
"str",
",",
"class_name",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"matched_modules",
",",
"erroneous_modules",
"=",
"find_class_module",
"(",
"module_name",
",",
"class_name",
")",
"for",
"su... | Get a sub-module of the given module which has the given class.
This method wraps `utils.reflection.find_class_module method` with the following behavior:
- raise error when multiple sub-modules with different classes with the same name are found
- return None when no sub-module is found
- warn about ... | [
"Get",
"a",
"sub",
"-",
"module",
"of",
"the",
"given",
"module",
"which",
"has",
"the",
"given",
"class",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/reflection.py#L97-L133 |
Cognexa/cxflow | cxflow/entry_point.py | entry_point | def entry_point() -> None:
"""**cxflow** entry point."""
# make sure the path contains the current working directory
sys.path.insert(0, os.getcwd())
parser = get_cxflow_arg_parser(True)
# parse CLI arguments
known_args, unknown_args = parser.parse_known_args()
# show help if no subcomman... | python | def entry_point() -> None:
"""**cxflow** entry point."""
# make sure the path contains the current working directory
sys.path.insert(0, os.getcwd())
parser = get_cxflow_arg_parser(True)
# parse CLI arguments
known_args, unknown_args = parser.parse_known_args()
# show help if no subcomman... | [
"def",
"entry_point",
"(",
")",
"->",
"None",
":",
"# make sure the path contains the current working directory",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"getcwd",
"(",
")",
")",
"parser",
"=",
"get_cxflow_arg_parser",
"(",
"True",
")",
"#... | **cxflow** entry point. | [
"**",
"cxflow",
"**",
"entry",
"point",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/entry_point.py#L26-L79 |
Cognexa/cxflow | cxflow/cli/args.py | get_cxflow_arg_parser | def get_cxflow_arg_parser(add_common_arguments: bool=False) -> ArgumentParser:
"""
Create the **cxflow** argument parser.
:return: an instance of the parser
"""
# create parser
main_parser = ArgumentParser('cxflow',
description='cxflow: lightweight framework for... | python | def get_cxflow_arg_parser(add_common_arguments: bool=False) -> ArgumentParser:
"""
Create the **cxflow** argument parser.
:return: an instance of the parser
"""
# create parser
main_parser = ArgumentParser('cxflow',
description='cxflow: lightweight framework for... | [
"def",
"get_cxflow_arg_parser",
"(",
"add_common_arguments",
":",
"bool",
"=",
"False",
")",
"->",
"ArgumentParser",
":",
"# create parser",
"main_parser",
"=",
"ArgumentParser",
"(",
"'cxflow'",
",",
"description",
"=",
"'cxflow: lightweight framework for machine learning ... | Create the **cxflow** argument parser.
:return: an instance of the parser | [
"Create",
"the",
"**",
"cxflow",
"**",
"argument",
"parser",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/args.py#L7-L94 |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._get_stream | def _get_stream(self) -> Iterator:
"""Possibly create and return raw dataset stream iterator."""
if self._stream is None:
self._stream = iter(self._get_stream_fn())
return self._stream | python | def _get_stream(self) -> Iterator:
"""Possibly create and return raw dataset stream iterator."""
if self._stream is None:
self._stream = iter(self._get_stream_fn())
return self._stream | [
"def",
"_get_stream",
"(",
"self",
")",
"->",
"Iterator",
":",
"if",
"self",
".",
"_stream",
"is",
"None",
":",
"self",
".",
"_stream",
"=",
"iter",
"(",
"self",
".",
"_get_stream_fn",
"(",
")",
")",
"return",
"self",
".",
"_stream"
] | Possibly create and return raw dataset stream iterator. | [
"Possibly",
"create",
"and",
"return",
"raw",
"dataset",
"stream",
"iterator",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L78-L82 |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._enqueue_batches | def _enqueue_batches(self, stop_event: Event) -> None:
"""
Enqueue all the stream batches. If specified, stop after ``epoch_size`` batches.
.. note::
Signal the epoch end with ``None``.
Stop when:
- ``stop_event`` is risen
- stream ends and epoch size is not... | python | def _enqueue_batches(self, stop_event: Event) -> None:
"""
Enqueue all the stream batches. If specified, stop after ``epoch_size`` batches.
.. note::
Signal the epoch end with ``None``.
Stop when:
- ``stop_event`` is risen
- stream ends and epoch size is not... | [
"def",
"_enqueue_batches",
"(",
"self",
",",
"stop_event",
":",
"Event",
")",
"->",
"None",
":",
"while",
"True",
":",
"self",
".",
"_stream",
"=",
"self",
".",
"_get_stream",
"(",
")",
"while",
"True",
":",
"# Acquire the semaphore before processing the next ba... | Enqueue all the stream batches. If specified, stop after ``epoch_size`` batches.
.. note::
Signal the epoch end with ``None``.
Stop when:
- ``stop_event`` is risen
- stream ends and epoch size is not set
- specified number of batches is enqueued
.. note::
... | [
"Enqueue",
"all",
"the",
"stream",
"batches",
".",
"If",
"specified",
"stop",
"after",
"epoch_size",
"batches",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L92-L138 |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._dequeue_batch | def _dequeue_batch(self) -> Optional[Batch]:
"""
Return a single batch from queue or ``None`` signaling epoch end.
:raise ChildProcessError: if the enqueueing thread ended unexpectedly
"""
if self._enqueueing_thread is None:
raise ValueError('StreamWrapper `{}` with ... | python | def _dequeue_batch(self) -> Optional[Batch]:
"""
Return a single batch from queue or ``None`` signaling epoch end.
:raise ChildProcessError: if the enqueueing thread ended unexpectedly
"""
if self._enqueueing_thread is None:
raise ValueError('StreamWrapper `{}` with ... | [
"def",
"_dequeue_batch",
"(",
"self",
")",
"->",
"Optional",
"[",
"Batch",
"]",
":",
"if",
"self",
".",
"_enqueueing_thread",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'StreamWrapper `{}` with buffer of size `{}` was used outside with-resource environment.'",
".",
... | Return a single batch from queue or ``None`` signaling epoch end.
:raise ChildProcessError: if the enqueueing thread ended unexpectedly | [
"Return",
"a",
"single",
"batch",
"from",
"queue",
"or",
"None",
"signaling",
"epoch",
"end",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L140-L167 |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._next_batch | def _next_batch(self) -> Optional[Batch]:
"""
Return a single batch or ``None`` signaling epoch end.
.. note::
Signal the epoch end with ``None``.
Stop when:
- stream ends and epoch size is not set
- specified number of batches is returned
:return: ... | python | def _next_batch(self) -> Optional[Batch]:
"""
Return a single batch or ``None`` signaling epoch end.
.. note::
Signal the epoch end with ``None``.
Stop when:
- stream ends and epoch size is not set
- specified number of batches is returned
:return: ... | [
"def",
"_next_batch",
"(",
"self",
")",
"->",
"Optional",
"[",
"Batch",
"]",
":",
"if",
"self",
".",
"_epoch_limit_reached",
"(",
")",
":",
"self",
".",
"_batch_count",
"=",
"0",
"return",
"None",
"try",
":",
"batch",
"=",
"next",
"(",
"self",
".",
"... | Return a single batch or ``None`` signaling epoch end.
.. note::
Signal the epoch end with ``None``.
Stop when:
- stream ends and epoch size is not set
- specified number of batches is returned
:return: a single batch or ``None`` signaling epoch end | [
"Return",
"a",
"single",
"batch",
"or",
"None",
"signaling",
"epoch",
"end",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L169-L197 |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._start_thread | def _start_thread(self):
"""Start an enqueueing thread."""
self._stopping_event = Event()
self._enqueueing_thread = Thread(target=self._enqueue_batches, args=(self._stopping_event,))
self._enqueueing_thread.start() | python | def _start_thread(self):
"""Start an enqueueing thread."""
self._stopping_event = Event()
self._enqueueing_thread = Thread(target=self._enqueue_batches, args=(self._stopping_event,))
self._enqueueing_thread.start() | [
"def",
"_start_thread",
"(",
"self",
")",
":",
"self",
".",
"_stopping_event",
"=",
"Event",
"(",
")",
"self",
".",
"_enqueueing_thread",
"=",
"Thread",
"(",
"target",
"=",
"self",
".",
"_enqueue_batches",
",",
"args",
"=",
"(",
"self",
".",
"_stopping_eve... | Start an enqueueing thread. | [
"Start",
"an",
"enqueueing",
"thread",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L199-L203 |
Cognexa/cxflow | cxflow/datasets/stream_wrapper.py | StreamWrapper._stop_thread | def _stop_thread(self):
"""Stop the enqueueing thread. Keep the queue content and stream state."""
self._stopping_event.set()
queue_content = []
try: # give the enqueueing thread chance to put a batch to the queue and check the stopping event
while True:
queu... | python | def _stop_thread(self):
"""Stop the enqueueing thread. Keep the queue content and stream state."""
self._stopping_event.set()
queue_content = []
try: # give the enqueueing thread chance to put a batch to the queue and check the stopping event
while True:
queu... | [
"def",
"_stop_thread",
"(",
"self",
")",
":",
"self",
".",
"_stopping_event",
".",
"set",
"(",
")",
"queue_content",
"=",
"[",
"]",
"try",
":",
"# give the enqueueing thread chance to put a batch to the queue and check the stopping event",
"while",
"True",
":",
"queue_c... | Stop the enqueueing thread. Keep the queue content and stream state. | [
"Stop",
"the",
"enqueueing",
"thread",
".",
"Keep",
"the",
"queue",
"content",
"and",
"stream",
"state",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/stream_wrapper.py#L205-L221 |
Cognexa/cxflow | cxflow/hooks/save.py | SaveEvery._after_n_epoch | def _after_n_epoch(self, epoch_id: int, **_) -> None:
"""
Save the model every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch
"""
SaveEvery.save_model(model=self._model, name_suffix=str(epoch_id), on_failure=self._on_save_failure) | python | def _after_n_epoch(self, epoch_id: int, **_) -> None:
"""
Save the model every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch
"""
SaveEvery.save_model(model=self._model, name_suffix=str(epoch_id), on_failure=self._on_save_failure) | [
"def",
"_after_n_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"*",
"*",
"_",
")",
"->",
"None",
":",
"SaveEvery",
".",
"save_model",
"(",
"model",
"=",
"self",
".",
"_model",
",",
"name_suffix",
"=",
"str",
"(",
"epoch_id",
")",
",",
"on_fa... | Save the model every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch | [
"Save",
"the",
"model",
"every",
"n_epochs",
"epoch",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L47-L53 |
Cognexa/cxflow | cxflow/hooks/save.py | SaveEvery.save_model | def save_model(model: AbstractModel, name_suffix: str, on_failure: str) -> None:
"""
Save the given model with the given name_suffix. On failure, take the specified action.
:param model: the model to be saved
:param name_suffix: name to be used for saving
:param on_failure: acti... | python | def save_model(model: AbstractModel, name_suffix: str, on_failure: str) -> None:
"""
Save the given model with the given name_suffix. On failure, take the specified action.
:param model: the model to be saved
:param name_suffix: name to be used for saving
:param on_failure: acti... | [
"def",
"save_model",
"(",
"model",
":",
"AbstractModel",
",",
"name_suffix",
":",
"str",
",",
"on_failure",
":",
"str",
")",
"->",
"None",
":",
"try",
":",
"logging",
".",
"debug",
"(",
"'Saving the model'",
")",
"save_path",
"=",
"model",
".",
"save",
"... | Save the given model with the given name_suffix. On failure, take the specified action.
:param model: the model to be saved
:param name_suffix: name to be used for saving
:param on_failure: action to be taken on failure; one of :py:attr:`SAVE_FAILURE_ACTIONS`
:raise IOError: on save fai... | [
"Save",
"the",
"given",
"model",
"with",
"the",
"given",
"name_suffix",
".",
"On",
"failure",
"take",
"the",
"specified",
"action",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L56-L73 |
Cognexa/cxflow | cxflow/hooks/save.py | SaveBest._get_value | def _get_value(self, epoch_data: EpochData) -> float:
"""
Retrieve the value of the monitored variable from the given epoch data.
:param epoch_data: epoch data which determine whether the model will be saved or not
:raise KeyError: if any of the specified stream, variable or aggregation... | python | def _get_value(self, epoch_data: EpochData) -> float:
"""
Retrieve the value of the monitored variable from the given epoch data.
:param epoch_data: epoch data which determine whether the model will be saved or not
:raise KeyError: if any of the specified stream, variable or aggregation... | [
"def",
"_get_value",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"float",
":",
"if",
"self",
".",
"_stream_name",
"not",
"in",
"epoch_data",
":",
"raise",
"KeyError",
"(",
"'Stream `{}` was not found in the epoch data.\\nAvailable streams are `{}`.'",
... | Retrieve the value of the monitored variable from the given epoch data.
:param epoch_data: epoch data which determine whether the model will be saved or not
:raise KeyError: if any of the specified stream, variable or aggregation is not present in the ``epoch_data``
:raise TypeError: if the var... | [
"Retrieve",
"the",
"value",
"of",
"the",
"monitored",
"variable",
"from",
"the",
"given",
"epoch",
"data",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L129-L160 |
Cognexa/cxflow | cxflow/hooks/save.py | SaveBest._is_value_better | def _is_value_better(self, new_value: float) -> bool:
"""
Test if the new value is better than the best so far.
:param new_value: current value of the objective function
"""
if self._best_value is None:
return True
if self._condition == 'min':
ret... | python | def _is_value_better(self, new_value: float) -> bool:
"""
Test if the new value is better than the best so far.
:param new_value: current value of the objective function
"""
if self._best_value is None:
return True
if self._condition == 'min':
ret... | [
"def",
"_is_value_better",
"(",
"self",
",",
"new_value",
":",
"float",
")",
"->",
"bool",
":",
"if",
"self",
".",
"_best_value",
"is",
"None",
":",
"return",
"True",
"if",
"self",
".",
"_condition",
"==",
"'min'",
":",
"return",
"new_value",
"<",
"self"... | Test if the new value is better than the best so far.
:param new_value: current value of the objective function | [
"Test",
"if",
"the",
"new",
"value",
"is",
"better",
"than",
"the",
"best",
"so",
"far",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L162-L173 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.